+ * This class is intended for use as a key to a map.
+ *
*
- *
This class is intended for use as a key to a map.
- *
- * @author Glen Husman
* @param The type of elements in the array.
+ * @author Glen Husman
* @see Arrays
*/
public final class ArrayWrapper {
- private E[] array;
+ /**
+ * Creates an array wrapper with some elements.
+ *
+ * @param elements The elements of the array.
+ */
+ public ArrayWrapper(E... elements) {
+ setArray(elements);
+ }
- /**
- * Creates an array wrapper with some elements.
- * @param elements The elements of the array.
- */
- public ArrayWrapper(E... elements) {
- setArray(elements);
- }
+ private E[] _array;
- /**
- * Converts an iterable element collection to an array of elements.
- * The iteration order of the specified object will be used as the array element order.
- * @param list The iterable of objects which will be converted to an array.
- * @param c The type of the elements of the array.
- * @return An array of elements in the specified iterable.
- */
- @SuppressWarnings("unchecked")
- public static T[] toArray(Iterable extends T> list, Class c) {
- int size = -1;
- if (list instanceof Collection>) {
- @SuppressWarnings("rawtypes") Collection coll = (Collection) list;
- size = coll.size();
- }
+ /**
+ * Retrieves a reference to the wrapped array instance.
+ *
+ * @return The array wrapped by this instance.
+ */
+ public E[] getArray() {
+ return _array;
+ }
- if (size < 0) {
- size = 0;
- // Ugly hack: Count it ourselves
- for (@SuppressWarnings("unused") T element : list) {
- size++;
- }
- }
+ /**
+ * Set this wrapper to wrap a new array instance.
+ *
+ * @param array The new wrapped array.
+ */
+ public void setArray(E[] array) {
+ Validate.notNull(array, "The array must not be null.");
+ _array = array;
+ }
- T[] result = (T[]) Array.newInstance(c, size);
- int i = 0;
- for (T element : list) { // Assumes iteration order is consistent
- result[i++] = element; // Assign array element at index THEN increment counter
- }
- return result;
- }
+ /**
+ * Determines if this object has a value equivalent to another object.
+ *
+ * @see Arrays#equals(Object[], Object[])
+ */
+ @SuppressWarnings("rawtypes")
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof ArrayWrapper)) {
+ return false;
+ }
+ return Arrays.equals(_array, ((ArrayWrapper) other)._array);
+ }
- /**
- * Retrieves a reference to the wrapped array instance.
- * @return The array wrapped by this instance.
- */
- public E[] getArray() {
- return this.array;
- }
+ /**
+ * Gets the hash code represented by this objects value.
+ *
+ * @return This object's hash code.
+ * @see Arrays#hashCode(Object[])
+ */
+ @Override
+ public int hashCode() {
+ return Arrays.hashCode(_array);
+ }
- /**
- * Set this wrapper to wrap a new array instance.
- * @param array The new wrapped array.
- */
- public void setArray(E[] array) {
- Validate.notNull(array, "The array must not be null.");
- this.array = array;
- }
+ /**
+ * Converts an iterable element collection to an array of elements.
+ * The iteration order of the specified object will be used as the array element order.
+ *
+ * @param list The iterable of objects which will be converted to an array.
+ * @param c The type of the elements of the array.
+ * @return An array of elements in the specified iterable.
+ */
+ @SuppressWarnings("unchecked")
+ public static T[] toArray(Iterable extends T> list, Class c) {
+ int size = -1;
+ if (list instanceof Collection>) {
+ @SuppressWarnings("rawtypes")
+ Collection coll = (Collection) list;
+ size = coll.size();
+ }
- /**
- * Determines if this object has a value equivalent to another object.
- * @see Arrays#equals(Object[], Object[])
- */
- @SuppressWarnings("rawtypes")
- @Override
- public boolean equals(Object other) {
- if (!(other instanceof ArrayWrapper)) {
- return false;
- }
- return Arrays.equals(this.array, ((ArrayWrapper) other).array);
- }
- /**
- * Gets the hash code represented by this objects value.
- * @see Arrays#hashCode(Object[])
- * @return This object's hash code.
- */
- @Override
- public int hashCode() {
- return Arrays.hashCode(this.array);
- }
+ if (size < 0) {
+ size = 0;
+ // Ugly hack: Count it ourselves
+ for (@SuppressWarnings("unused") T element : list) {
+ size++;
+ }
+ }
+
+ T[] result = (T[]) Array.newInstance(c, size);
+ int i = 0;
+ for (T element : list) { // Assumes iteration order is consistent
+ result[i++] = element; // Assign array element at index THEN increment counter
+ }
+ return result;
+ }
+
}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java
index 0c6a23eac..ba61fe261 100644
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java
@@ -1,25 +1,10 @@
package com.plotsquared.bukkit.chat;
-import static com.plotsquared.bukkit.chat.TextualComponent.rawText;
-
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;
-import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable;
-import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization;
-import org.bukkit.Achievement;
-import org.bukkit.Bukkit;
-import org.bukkit.ChatColor;
-import org.bukkit.Material;
-import org.bukkit.Statistic;
-import org.bukkit.Statistic.Type;
-import org.bukkit.command.CommandSender;
-import org.bukkit.entity.EntityType;
-import org.bukkit.entity.Player;
-import org.bukkit.inventory.ItemStack;
-
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Constructor;
@@ -29,849 +14,874 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
+import org.bukkit.Achievement;
+import org.bukkit.Bukkit;
+import org.bukkit.ChatColor;
+import org.bukkit.Material;
+import org.bukkit.Statistic;
+import org.bukkit.Statistic.Type;
+import org.bukkit.command.CommandSender;
+import org.bukkit.configuration.serialization.ConfigurationSerializable;
+import org.bukkit.configuration.serialization.ConfigurationSerialization;
+import org.bukkit.entity.EntityType;
+import org.bukkit.entity.Player;
+import org.bukkit.inventory.ItemStack;
+
+
+import static com.plotsquared.bukkit.chat.TextualComponent.rawText;
/**
- * Represents a formattable message. Such messages can use elements such as colors, formatting codes, hover and click data, and other features
- * provided by the vanilla Minecraft JSON message formatter.
- * This class allows plugins to emulate the functionality of the vanilla Minecraft
- * tellraw command.
- *
This class follows the builder pattern, allowing for method chaining.
- * It is set up such that invocations of property-setting methods will affect
- * the current editing component, and a call to {@link #then(String)} or
- * {@link #text(TextualComponent)} will append a new editing component to the
- * end of the message, optionally initializing it with text. Further
- * property-setting method calls will affect that editing component.
+ * Represents a formattable message. Such messages can use elements such as colors, formatting codes, hover and click data, and other features provided by the vanilla Minecraft JSON message formatter.
+ * This class allows plugins to emulate the functionality of the vanilla Minecraft tellraw command.
+ *
+ * This class follows the builder pattern, allowing for method chaining.
+ * It is set up such that invocations of property-setting methods will affect the current editing component,
+ * and a call to {@link #then()} or {@link #then(String)} will append a new editing component to the end of the message,
+ * optionally initializing it with text. Further property-setting method calls will affect that editing component.
+ *
*/
public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable, ConfigurationSerializable {
- private static final JsonParser _stringParser = new JsonParser();
- private static Constructor> nmsPacketPlayOutChatConstructor;
- // The ChatSerializer's instance of Gson
- private static Object nmsChatSerializerGsonInstance;
- private static Method fromJsonMethod;
+ static {
+ ConfigurationSerialization.registerClass(FancyMessage.class);
+ }
- static {
- ConfigurationSerialization.registerClass(FancyMessage.class);
- }
+ private List messageParts;
+ private String jsonString;
+ private boolean dirty;
- private List messageParts;
- private String jsonString;
- private boolean dirty;
+ private static Constructor> nmsPacketPlayOutChatConstructor;
- /**
- * Creates a JSON message with text.
- * @param firstPartText The existing text in the message.
- */
- public FancyMessage(String firstPartText) {
- this(rawText(firstPartText));
- }
+ @Override
+ public FancyMessage clone() throws CloneNotSupportedException {
+ FancyMessage instance = (FancyMessage) super.clone();
+ instance.messageParts = new ArrayList(messageParts.size());
+ for (int i = 0; i < messageParts.size(); i++) {
+ instance.messageParts.add(i, messageParts.get(i).clone());
+ }
+ instance.dirty = false;
+ instance.jsonString = null;
+ return instance;
+ }
- public FancyMessage(TextualComponent firstPartText) {
- this.messageParts = new ArrayList<>();
- this.messageParts.add(new MessagePart(firstPartText));
- this.jsonString = null;
- this.dirty = false;
+ /**
+ * Creates a JSON message with text.
+ *
+ * @param firstPartText The existing text in the message.
+ */
+ public FancyMessage(final String firstPartText) {
+ this(rawText(firstPartText));
+ }
- if (nmsPacketPlayOutChatConstructor == null) {
- try {
- nmsPacketPlayOutChatConstructor =
- Reflection.getNMSClass("PacketPlayOutChat").getDeclaredConstructor(Reflection.getNMSClass("IChatBaseComponent"));
- nmsPacketPlayOutChatConstructor.setAccessible(true);
- } catch (NoSuchMethodException e) {
- Bukkit.getLogger().log(Level.SEVERE, "Could not find Minecraft method or constructor.", e);
- } catch (SecurityException e) {
- Bukkit.getLogger().log(Level.WARNING, "Could not access constructor.", e);
- }
- }
- }
+ public FancyMessage(final com.plotsquared.bukkit.chat.TextualComponent firstPartText) {
+ messageParts = new ArrayList();
+ messageParts.add(new MessagePart(firstPartText));
+ jsonString = null;
+ dirty = false;
- /**
- * Creates a JSON message without text.
- */
- public FancyMessage() {
- this((TextualComponent) null);
- }
+ if (nmsPacketPlayOutChatConstructor == null) {
+ try {
+ nmsPacketPlayOutChatConstructor = com.plotsquared.bukkit.chat.Reflection.getNMSClass("PacketPlayOutChat").getDeclaredConstructor(com.plotsquared.bukkit.chat.Reflection.getNMSClass("IChatBaseComponent"));
+ nmsPacketPlayOutChatConstructor.setAccessible(true);
+ } catch (NoSuchMethodException e) {
+ Bukkit.getLogger().log(Level.SEVERE, "Could not find Minecraft method or constructor.", e);
+ } catch (SecurityException e) {
+ Bukkit.getLogger().log(Level.WARNING, "Could not access constructor.", e);
+ }
+ }
+ }
- /**
- * Deserialize a JSON-represented message from a mapping of key-value pairs.
- * This is called by the Bukkit serialization API.
- * It is not intended for direct public API consumption.
- * @param serialized The key-value mapping which represents a fancy message.
- */
- @SuppressWarnings("unchecked")
- public static FancyMessage deserialize(Map serialized) {
- FancyMessage msg = new FancyMessage();
- msg.messageParts = (List) serialized.get("messageParts");
- msg.jsonString = serialized.containsKey("JSON") ? serialized.get("JSON").toString() : null;
- msg.dirty = !serialized.containsKey("JSON");
- return msg;
- }
+ /**
+ * Creates a JSON message without text.
+ */
+ public FancyMessage() {
+ this((com.plotsquared.bukkit.chat.TextualComponent) null);
+ }
- /**
- * Deserialize a fancy message from its JSON representation. This JSON
- * representation is of the format of hat returned by
- * {@link #toJSONString()}, and is compatible with vanilla inputs.
- * @param json The JSON string which represents a fancy message.
- * @return A {@code FancyMessage} representing the parametrized JSON message.
- */
- public static FancyMessage deserialize(String json) {
- JsonObject serialized = _stringParser.parse(json).getAsJsonObject();
- JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component
- FancyMessage returnVal = new FancyMessage();
- returnVal.messageParts.clear();
- for (JsonElement mPrt : extra) {
- MessagePart component = new MessagePart();
- JsonObject messagePart = mPrt.getAsJsonObject();
- for (Map.Entry entry : messagePart.entrySet()) {
- // Deserialize text
- if (TextualComponent.isTextKey(entry.getKey())) {
- // The map mimics the YAML serialization, which has a "key" field and one or more "value" fields
- Map serializedMapForm = new HashMap<>(); // Must be object due to Bukkit serializer API compliance
- serializedMapForm.put("key", entry.getKey());
- if (entry.getValue().isJsonPrimitive()) {
- // Assume string
- serializedMapForm.put("value", entry.getValue().getAsString());
- } else {
- // Composite object, but we assume each element is a string
- for (Map.Entry compositeNestedElement : entry.getValue().getAsJsonObject().entrySet()) {
- serializedMapForm.put("value." + compositeNestedElement.getKey(), compositeNestedElement.getValue().getAsString());
- }
- }
- component.text = TextualComponent.deserialize(serializedMapForm);
- } else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) {
- if (entry.getValue().getAsBoolean()) {
- component.styles.add(MessagePart.stylesToNames.inverse().get(entry.getKey()));
- }
- } else if (entry.getKey().equals("color")) {
- component.color = ChatColor.valueOf(entry.getValue().getAsString().toUpperCase());
- } else if (entry.getKey().equals("clickEvent")) {
- JsonObject object = entry.getValue().getAsJsonObject();
- component.clickActionName = object.get("action").getAsString();
- component.clickActionData = object.get("value").getAsString();
- } else if (entry.getKey().equals("hoverEvent")) {
- JsonObject object = entry.getValue().getAsJsonObject();
- component.hoverActionName = object.get("action").getAsString();
- if (object.get("value").isJsonPrimitive()) {
- // Assume string
- component.hoverActionData = new JsonString(object.get("value").getAsString());
- } else {
- // Assume composite type
- // The only composite type we currently store is another FancyMessage
- // Therefore, recursion time!
- component.hoverActionData =
- deserialize(object.get("value").toString() /* This should properly serialize the JSON object as a JSON string */);
- }
- } else if (entry.getKey().equals("insertion")) {
- component.insertionData = entry.getValue().getAsString();
- } else if (entry.getKey().equals("with")) {
- for (JsonElement object : entry.getValue().getAsJsonArray()) {
- if (object.isJsonPrimitive()) {
- component.translationReplacements.add(new JsonString(object.getAsString()));
- } else {
- // Only composite type stored in this array is - again - FancyMessages
- // Recurse within this function to parse this as a translation replacement
- component.translationReplacements.add(deserialize(object.toString()));
- }
- }
- }
- }
- returnVal.messageParts.add(component);
- }
- return returnVal;
- }
+ /**
+ * Sets the text of the current editing component to a value.
+ *
+ * @param text The new text of the current editing component.
+ * @return This builder instance.
+ */
+ public FancyMessage text(String text) {
+ MessagePart latest = latest();
+ latest.text = rawText(text);
+ dirty = true;
+ return this;
+ }
- @Override
- public FancyMessage clone() throws CloneNotSupportedException {
- FancyMessage instance = (FancyMessage) super.clone();
- instance.messageParts = new ArrayList<>(this.messageParts.size());
- for (int i = 0; i < this.messageParts.size(); i++) {
- instance.messageParts.add(i, this.messageParts.get(i).clone());
- }
- instance.dirty = false;
- instance.jsonString = null;
- return instance;
- }
+ /**
+ * Sets the text of the current editing component to a value.
+ *
+ * @param text The new text of the current editing component.
+ * @return This builder instance.
+ */
+ public FancyMessage text(com.plotsquared.bukkit.chat.TextualComponent text) {
+ MessagePart latest = latest();
+ latest.text = text;
+ dirty = true;
+ return this;
+ }
- /**
- * Sets the text of the current editing component to a value.
- * @param text The new text of the current editing component.
- * @return This builder instance.
- */
- public FancyMessage text(String text) {
- MessagePart latest = latest();
- latest.text = rawText(text);
- this.dirty = true;
- return this;
- }
+ /**
+ * Sets the color of the current editing component to a value.
+ *
+ * @param color The new color of the current editing component.
+ * @return This builder instance.
+ * @throws IllegalArgumentException If the specified {@code ChatColor} enumeration value is not a color (but a format value).
+ */
+ public FancyMessage color(final ChatColor color) {
+ if (!color.isColor()) {
+ throw new IllegalArgumentException(color.name() + " is not a color");
+ }
+ latest().color = color;
+ dirty = true;
+ return this;
+ }
- /**
- * Sets the text of the current editing component to a value.
- * @param text The new text of the current editing component.
- * @return This builder instance.
- */
- public FancyMessage text(TextualComponent text) {
- MessagePart latest = latest();
- latest.text = text;
- this.dirty = true;
- return this;
- }
+ /**
+ * Sets the stylization of the current editing component.
+ *
+ * @param styles The array of styles to apply to the editing component.
+ * @return This builder instance.
+ * @throws IllegalArgumentException If any of the enumeration values in the array do not represent formatters.
+ */
+ public FancyMessage style(ChatColor... styles) {
+ for (final ChatColor style : styles) {
+ if (!style.isFormat()) {
+ throw new IllegalArgumentException(style.name() + " is not a style");
+ }
+ }
+ latest().styles.addAll(Arrays.asList(styles));
+ dirty = true;
+ return this;
+ }
- /**
- * Sets the color of the current editing component to a value.
- * @param color The new color of the current editing component.
- * @return This builder instance.
- * @exception IllegalArgumentException If the specified {@code ChatColor} enumeration value is not a color (but a format value).
- */
- public FancyMessage color(ChatColor color) {
- latest().color = color;
- this.dirty = true;
- return this;
- }
+ /**
+ * Set the behavior of the current editing component to instruct the client to open a file on the client side filesystem when the currently edited part of the {@code FancyMessage} is clicked.
+ *
+ * @param path The path of the file on the client filesystem.
+ * @return This builder instance.
+ */
+ public FancyMessage file(final String path) {
+ onClick("open_file", path);
+ return this;
+ }
- /**
- * Sets the stylization of the current editing component.
- * @param styles The array of styles to apply to the editing component.
- * @return This builder instance.
- * @exception IllegalArgumentException If any of the enumeration values in the array do not represent formatters.
- */
- public FancyMessage style(ChatColor... styles) {
- for (ChatColor style : styles) {
- if (!style.isFormat()) {
- throw new IllegalArgumentException(style.name() + " is not a style");
- }
- }
- latest().styles.addAll(Arrays.asList(styles));
- this.dirty = true;
- return this;
- }
+ /**
+ * Set the behavior of the current editing component to instruct the client to open a webpage in the client's web browser when the currently edited part of the {@code FancyMessage} is clicked.
+ *
+ * @param url The URL of the page to open when the link is clicked.
+ * @return This builder instance.
+ */
+ public FancyMessage link(final String url) {
+ onClick("open_url", url);
+ return this;
+ }
- /**
- * Set the behavior of the current editing component to instruct the client to open a file on the client side filesystem when the currently
- * edited part of the {@code FancyMessage} is clicked.
- * @param path The path of the file on the client filesystem.
- * @return This builder instance.
- */
- public FancyMessage file(String path) {
- onClick("open_file", path);
- return this;
- }
+ /**
+ * Set the behavior of the current editing component to instruct the client to replace the chat input box content with the specified string when the currently edited part of the {@code FancyMessage} is clicked.
+ * The client will not immediately send the command to the server to be executed unless the client player submits the command/chat message, usually with the enter key.
+ *
+ * @param command The text to display in the chat bar of the client.
+ * @return This builder instance.
+ */
+ public FancyMessage suggest(final String command) {
+ onClick("suggest_command", command);
+ return this;
+ }
- /**
- * Set the behavior of the current editing component to instruct the client to open a webpage in the client's web browser when the currently
- * edited part of the {@code FancyMessage} is clicked.
- * @param url The URL of the page to open when the link is clicked.
- * @return This builder instance.
- */
- public FancyMessage link(String url) {
- onClick("open_url", url);
- return this;
- }
+ /**
+ * Set the behavior of the current editing component to instruct the client to append the chat input box content with the specified string when the currently edited part of the {@code FancyMessage} is SHIFT-CLICKED.
+ * The client will not immediately send the command to the server to be executed unless the client player submits the command/chat message, usually with the enter key.
+ *
+ * @param command The text to append to the chat bar of the client.
+ * @return This builder instance.
+ */
+ public FancyMessage insert(final String command) {
+ latest().insertionData = command;
+ dirty = true;
+ return this;
+ }
- /**
- * Set the behavior of the current editing component to instruct the client to replace the chat input box content with the specified string
- * when the currently edited part of the {@code FancyMessage} is clicked.
- * The client will not immediately send the command to the server to be executed unless the client player submits the command/chat message,
- * usually with the enter key.
- * @param command The text to display in the chat bar of the client.
- * @return This builder instance.
- */
- public FancyMessage suggest(String command) {
- onClick("suggest_command", command);
- return this;
- }
+ /**
+ * Set the behavior of the current editing component to instruct the client to send the specified string to the server as a chat message when the currently edited part of the {@code FancyMessage} is clicked.
+ * The client will immediately send the command to the server to be executed when the editing component is clicked.
+ *
+ * @param command The text to display in the chat bar of the client.
+ * @return This builder instance.
+ */
+ public FancyMessage command(final String command) {
+ onClick("run_command", command);
+ return this;
+ }
- /**
- * Set the behavior of the current editing component to instruct the client to append the chat input box content with the specified string when
- * the currently edited part of the {@code FancyMessage} is SHIFT-CLICKED.
- * The client will not immediately send the command to the server to be executed unless the client player submits the command/chat message,
- * usually with the enter key.
- * @param command The text to append to the chat bar of the client.
- * @return This builder instance.
- */
- public FancyMessage insert(String command) {
- latest().insertionData = command;
- this.dirty = true;
- return this;
- }
+ /**
+ * Set the behavior of the current editing component to display information about an achievement when the client hovers over the text.
+ *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
+ *
+ * @param name The name of the achievement to display, excluding the "achievement." prefix.
+ * @return This builder instance.
+ */
+ public FancyMessage achievementTooltip(final String name) {
+ onHover("show_achievement", new JsonString("achievement." + name));
+ return this;
+ }
- /**
- * Set the behavior of the current editing component to instruct the client to send the specified string to the server as a chat message when
- * the currently edited part of the {@code FancyMessage} is clicked.
- * The client will immediately send the command to the server to be executed when the editing component is clicked.
- * @param command The text to display in the chat bar of the client.
- * @return This builder instance.
- */
- public FancyMessage command(String command) {
- onClick("run_command", command);
- return this;
- }
+ /**
+ * Set the behavior of the current editing component to display information about an achievement when the client hovers over the text.
+ *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
+ *
+ * @param which The achievement to display.
+ * @return This builder instance.
+ */
+ public FancyMessage achievementTooltip(final Achievement which) {
+ try {
+ Object achievement = com.plotsquared.bukkit.chat.Reflection.getMethod(com.plotsquared.bukkit.chat.Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement", Achievement.class).invoke(null, which);
+ return achievementTooltip((String) com.plotsquared.bukkit.chat.Reflection.getField(com.plotsquared.bukkit.chat.Reflection.getNMSClass("Achievement"), "name").get(achievement));
+ } catch (IllegalAccessException e) {
+ Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
+ return this;
+ } catch (IllegalArgumentException e) {
+ Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
+ return this;
+ } catch (InvocationTargetException e) {
+ Bukkit.getLogger().log(Level.WARNING, "A error has occured durring invoking of method.", e);
+ return this;
+ }
+ }
- /**
- * Set the behavior of the current editing component to display information about an achievement when the client hovers over the text.
- *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
- * @param name The name of the achievement to display, excluding the "achievement." prefix.
- * @return This builder instance.
- */
- public FancyMessage achievementTooltip(String name) {
- onHover("show_achievement", new JsonString("achievement." + name));
- return this;
- }
+ /**
+ * Set the behavior of the current editing component to display information about a parameterless statistic when the client hovers over the text.
+ *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
+ *
+ * @param which The statistic to display.
+ * @return This builder instance.
+ * @throws IllegalArgumentException If the statistic requires a parameter which was not supplied.
+ */
+ public FancyMessage statisticTooltip(final Statistic which) {
+ Type type = which.getType();
+ if (type != Type.UNTYPED) {
+ throw new IllegalArgumentException("That statistic requires an additional " + type + " parameter!");
+ }
+ try {
+ Object statistic = com.plotsquared.bukkit.chat.Reflection.getMethod(com.plotsquared.bukkit.chat.Reflection.getOBCClass("CraftStatistic"), "getNMSStatistic", Statistic.class).invoke(null, which);
+ return achievementTooltip((String) com.plotsquared.bukkit.chat.Reflection.getField(com.plotsquared.bukkit.chat.Reflection.getNMSClass("Statistic"), "name").get(statistic));
+ } catch (IllegalAccessException e) {
+ Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
+ return this;
+ } catch (IllegalArgumentException e) {
+ Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
+ return this;
+ } catch (InvocationTargetException e) {
+ Bukkit.getLogger().log(Level.WARNING, "A error has occured durring invoking of method.", e);
+ return this;
+ }
+ }
- /**
- * Set the behavior of the current editing component to display information about an achievement when the client hovers over the text.
- *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
- * @param which The achievement to display.
- * @return This builder instance.
- */
- public FancyMessage achievementTooltip(Achievement which) {
- try {
- Object achievement =
- Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement", Achievement.class).invoke(null, which);
- return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Achievement"), "name").get(achievement));
- } catch (IllegalAccessException e) {
- Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
- return this;
- } catch (IllegalArgumentException e) {
- Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
- return this;
- } catch (InvocationTargetException e) {
- Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e);
- return this;
- }
- }
+ /**
+ * Set the behavior of the current editing component to display information about a statistic parameter with a material when the client hovers over the text.
+ *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
+ *
+ * @param which The statistic to display.
+ * @param item The sole material parameter to the statistic.
+ * @return This builder instance.
+ * @throws IllegalArgumentException If the statistic requires a parameter which was not supplied, or was supplied a parameter that was not required.
+ */
+ public FancyMessage statisticTooltip(final Statistic which, Material item) {
+ Type type = which.getType();
+ if (type == Type.UNTYPED) {
+ throw new IllegalArgumentException("That statistic needs no additional parameter!");
+ }
+ if ((type == Type.BLOCK && item.isBlock()) || type == Type.ENTITY) {
+ throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!");
+ }
+ try {
+ Object statistic = com.plotsquared.bukkit.chat.Reflection.getMethod(com.plotsquared.bukkit.chat.Reflection.getOBCClass("CraftStatistic"), "getMaterialStatistic", Statistic.class, Material.class).invoke(null, which, item);
+ return achievementTooltip((String) com.plotsquared.bukkit.chat.Reflection.getField(com.plotsquared.bukkit.chat.Reflection.getNMSClass("Statistic"), "name").get(statistic));
+ } catch (IllegalAccessException e) {
+ Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
+ return this;
+ } catch (IllegalArgumentException e) {
+ Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
+ return this;
+ } catch (InvocationTargetException e) {
+ Bukkit.getLogger().log(Level.WARNING, "A error has occured durring invoking of method.", e);
+ return this;
+ }
+ }
- /**
- * Set the behavior of the current editing component to display information about a parameterless statistic when the client hovers over the text.
- *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
- * @param which The statistic to display.
- * @return This builder instance.
- * @exception IllegalArgumentException If the statistic requires a parameter which was not supplied.
- */
- public FancyMessage statisticTooltip(Statistic which) {
- Type type = which.getType();
- if (type != Type.UNTYPED) {
- throw new IllegalArgumentException("That statistic requires an additional " + type + " parameter!");
- }
- try {
- Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSStatistic", Statistic.class).invoke(null, which);
- return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic));
- } catch (IllegalAccessException e) {
- Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
- return this;
- } catch (IllegalArgumentException e) {
- Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
- return this;
- } catch (InvocationTargetException e) {
- Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e);
- return this;
- }
- }
+ /**
+ * Set the behavior of the current editing component to display information about a statistic parameter with an entity type when the client hovers over the text.
+ *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
+ *
+ * @param which The statistic to display.
+ * @param entity The sole entity type parameter to the statistic.
+ * @return This builder instance.
+ * @throws IllegalArgumentException If the statistic requires a parameter which was not supplied, or was supplied a parameter that was not required.
+ */
+ public FancyMessage statisticTooltip(final Statistic which, EntityType entity) {
+ Type type = which.getType();
+ if (type == Type.UNTYPED) {
+ throw new IllegalArgumentException("That statistic needs no additional parameter!");
+ }
+ if (type != Type.ENTITY) {
+ throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!");
+ }
+ try {
+ Object statistic = com.plotsquared.bukkit.chat.Reflection.getMethod(com.plotsquared.bukkit.chat.Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic", Statistic.class, EntityType.class).invoke(null, which, entity);
+ return achievementTooltip((String) com.plotsquared.bukkit.chat.Reflection.getField(com.plotsquared.bukkit.chat.Reflection.getNMSClass("Statistic"), "name").get(statistic));
+ } catch (IllegalAccessException e) {
+ Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
+ return this;
+ } catch (IllegalArgumentException e) {
+ Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
+ return this;
+ } catch (InvocationTargetException e) {
+ Bukkit.getLogger().log(Level.WARNING, "A error has occured durring invoking of method.", e);
+ return this;
+ }
+ }
- /**
- * Set the behavior of the current editing component to display information about a statistic parameter with a material when the client hovers
- * over the text.
- *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
- * @param which The statistic to display.
- * @param item The sole material parameter to the statistic.
- * @return This builder instance.
- * @exception IllegalArgumentException If the statistic requires a parameter which was not supplied, or was supplied a parameter that was not
- * required.
- */
- public FancyMessage statisticTooltip(Statistic which, Material item) {
- Type type = which.getType();
- if (type == Type.UNTYPED) {
- throw new IllegalArgumentException("That statistic needs no additional parameter!");
- }
- if (type == Type.BLOCK && item.isBlock() || type == Type.ENTITY) {
- throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!");
- }
- try {
- Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getMaterialStatistic", Statistic.class, Material.class)
- .invoke(null, which, item);
- return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic));
- } catch (IllegalAccessException e) {
- Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
- return this;
- } catch (IllegalArgumentException e) {
- Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
- return this;
- } catch (InvocationTargetException e) {
- Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e);
- return this;
- }
- }
+ /**
+ * Set the behavior of the current editing component to display information about an item when the client hovers over the text.
+ *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
+ *
+ * @param itemJSON A string representing the JSON-serialized NBT data tag of an {@link ItemStack}.
+ * @return This builder instance.
+ */
+ public FancyMessage itemTooltip(final String itemJSON) {
+ onHover("show_item", new JsonString(itemJSON)); // Seems a bit hacky, considering we have a JSON object as a parameter
+ return this;
+ }
- /**
- * Set the behavior of the current editing component to display information about a statistic parameter with an entity type when the client
- * hovers over the text.
- *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
- * @param which The statistic to display.
- * @param entity The sole entity type parameter to the statistic.
- * @return This builder instance.
- * @exception IllegalArgumentException If the statistic requires a parameter which was not supplied, or was supplied a parameter that was not
- * required.
- */
- public FancyMessage statisticTooltip(Statistic which, EntityType entity) {
- Type type = which.getType();
- if (type == Type.UNTYPED) {
- throw new IllegalArgumentException("That statistic needs no additional parameter!");
- }
- if (type != Type.ENTITY) {
- throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!");
- }
- try {
- Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic", Statistic.class, EntityType.class)
- .invoke(null, which, entity);
- return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic));
- } catch (IllegalAccessException e) {
- Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
- return this;
- } catch (IllegalArgumentException e) {
- Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
- return this;
- } catch (InvocationTargetException e) {
- Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e);
- return this;
- }
- }
+ /**
+ * Set the behavior of the current editing component to display information about an item when the client hovers over the text.
+ *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
+ *
+ * @param itemStack The stack for which to display information.
+ * @return This builder instance.
+ */
+ public FancyMessage itemTooltip(final ItemStack itemStack) {
+ try {
+ Object nmsItem = com.plotsquared.bukkit.chat.Reflection.getMethod(com.plotsquared.bukkit.chat.Reflection.getOBCClass("inventory.CraftItemStack"), "asNMSCopy", ItemStack.class).invoke(null, itemStack);
+ return itemTooltip(com.plotsquared.bukkit.chat.Reflection.getMethod(com.plotsquared.bukkit.chat.Reflection.getNMSClass("ItemStack"), "save", com.plotsquared.bukkit.chat.Reflection.getNMSClass("NBTTagCompound")).invoke(nmsItem, com.plotsquared.bukkit.chat.Reflection.getNMSClass("NBTTagCompound").newInstance()).toString());
+ } catch (Exception e) {
+ e.printStackTrace();
+ return this;
+ }
+ }
- /**
- * Set the behavior of the current editing component to display information about an item when the client hovers over the text.
- *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
- * @param itemJSON A string representing the JSON-serialized NBT data tag of an {@link ItemStack}.
- * @return This builder instance.
- */
- public FancyMessage itemTooltip(String itemJSON) {
- onHover("show_item", new JsonString(itemJSON)); // Seems a bit hacky, considering we have a JSON object as a parameter
- return this;
- }
+ /**
+ * Set the behavior of the current editing component to display raw text when the client hovers over the text.
+ *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
+ *
+ * @param text The text, which supports newlines, which will be displayed to the client upon hovering.
+ * @return This builder instance.
+ */
+ public FancyMessage tooltip(final String text) {
+ onHover("show_text", new JsonString(text));
+ return this;
+ }
- /**
- * Set the behavior of the current editing component to display information about an item when the client hovers over the text.
- *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
- * @param itemStack The stack for which to display information.
- * @return This builder instance.
- */
- public FancyMessage itemTooltip(ItemStack itemStack) {
- try {
- Object nmsItem =
- Reflection.getMethod(Reflection.getOBCClass("inventory.CraftItemStack"), "asNMSCopy", ItemStack.class).invoke(null, itemStack);
- return itemTooltip(Reflection.getMethod(Reflection.getNMSClass("ItemStack"), "save", Reflection.getNMSClass("NBTTagCompound"))
- .invoke(nmsItem, Reflection.getNMSClass("NBTTagCompound").newInstance()).toString());
- } catch (IllegalAccessException | IllegalArgumentException | InstantiationException | InvocationTargetException e) {
- e.printStackTrace();
- return this;
- }
- }
+ /**
+ * Set the behavior of the current editing component to display raw text when the client hovers over the text.
+ *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
+ *
+ * @param lines The lines of text which will be displayed to the client upon hovering. The iteration order of this object will be the order in which the lines of the tooltip are created.
+ * @return This builder instance.
+ */
+ public FancyMessage tooltip(final Iterable lines) {
+ tooltip(com.plotsquared.bukkit.chat.ArrayWrapper.toArray(lines, String.class));
+ return this;
+ }
- /**
- * Set the behavior of the current editing component to display raw text when the client hovers over the text.
- *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
- * @param text The text, which supports newlines, which will be displayed to the client upon hovering.
- * @return This builder instance.
- */
- public FancyMessage tooltip(String text) {
- onHover("show_text", new JsonString(text));
- return this;
- }
+ /**
+ * Set the behavior of the current editing component to display raw text when the client hovers over the text.
+ *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
+ *
+ * @param lines The lines of text which will be displayed to the client upon hovering.
+ * @return This builder instance.
+ */
+ public FancyMessage tooltip(final String... lines) {
+ StringBuilder builder = new StringBuilder();
+ for (int i = 0; i < lines.length; i++) {
+ builder.append(lines[i]);
+ if (i != lines.length - 1) {
+ builder.append('\n');
+ }
+ }
+ tooltip(builder.toString());
+ return this;
+ }
- /**
- * Set the behavior of the current editing component to display raw text when the client hovers over the text.
- *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
- * @param lines The lines of text which will be displayed to the client upon hovering. The iteration order of this object will be the order in
- * which the lines of the tooltip are created.
- * @return This builder instance.
- */
- public FancyMessage tooltip(Iterable lines) {
- tooltip(ArrayWrapper.toArray(lines, String.class));
- return this;
- }
-
- /*
+ /**
+ * Set the behavior of the current editing component to display formatted text when the client hovers over the text.
+ *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
+ *
+ * @param text The formatted text which will be displayed to the client upon hovering.
+ * @return This builder instance.
+ */
+ public FancyMessage formattedTooltip(FancyMessage text) {
+ for (MessagePart component : text.messageParts) {
+ if (component.clickActionData != null && component.clickActionName != null) {
+ throw new IllegalArgumentException("The tooltip text cannot have click data.");
+ } else if (component.hoverActionData != null && component.hoverActionName != null) {
+ throw new IllegalArgumentException("The tooltip text cannot have a tooltip.");
+ }
+ }
+ onHover("show_text", text);
+ return this;
+ }
- /**
- * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the
- * message.
- * @param replacements The replacements, in order, that will be used in the language-specific message.
- * @return This builder instance.
- *//* ------------
- public FancyMessage translationReplacements(final Iterable extends CharSequence> replacements){
- for(CharSequence str : replacements){
- latest().translationReplacements.add(new JsonString(str));
- }
+ /**
+ * Set the behavior of the current editing component to display the specified lines of formatted text when the client hovers over the text.
+ *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
+ *
+ * @param lines The lines of formatted text which will be displayed to the client upon hovering.
+ * @return This builder instance.
+ */
+ public FancyMessage formattedTooltip(FancyMessage... lines) {
+ if (lines.length < 1) {
+ onHover(null, null); // Clear tooltip
+ return this;
+ }
- return this;
- }
+ FancyMessage result = new FancyMessage();
+ result.messageParts.clear(); // Remove the one existing text component that exists by default, which destabilizes the object
- */
+ for (int i = 0; i < lines.length; i++) {
+ try {
+ for (MessagePart component : lines[i]) {
+ if (component.clickActionData != null && component.clickActionName != null) {
+ throw new IllegalArgumentException("The tooltip text cannot have click data.");
+ } else if (component.hoverActionData != null && component.hoverActionName != null) {
+ throw new IllegalArgumentException("The tooltip text cannot have a tooltip.");
+ }
+ if (component.hasText()) {
+ result.messageParts.add(component.clone());
+ }
+ }
+ if (i != lines.length - 1) {
+ result.messageParts.add(new MessagePart(rawText("\n")));
+ }
+ } catch (CloneNotSupportedException e) {
+ Bukkit.getLogger().log(Level.WARNING, "Failed to clone object", e);
+ return this;
+ }
+ }
+ return formattedTooltip(result.messageParts.isEmpty() ? null : result); // Throws NPE if size is 0, intended
+ }
- /**
- * Set the behavior of the current editing component to display raw text when the client hovers over the text.
- *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
- * @param lines The lines of text which will be displayed to the client upon hovering.
- * @return This builder instance.
- */
- public FancyMessage tooltip(String... lines) {
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < lines.length; i++) {
- builder.append(lines[i]);
- if (i != lines.length - 1) {
- builder.append('\n');
- }
- }
- tooltip(builder.toString());
- return this;
- }
+ /**
+ * Set the behavior of the current editing component to display the specified lines of formatted text when the client hovers over the text.
+ *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
+ *
+ * @param lines The lines of text which will be displayed to the client upon hovering. The iteration order of this object will be the order in which the lines of the tooltip are created.
+ * @return This builder instance.
+ */
+ public FancyMessage formattedTooltip(final Iterable lines) {
+ return formattedTooltip(com.plotsquared.bukkit.chat.ArrayWrapper.toArray(lines, FancyMessage.class));
+ }
- /**
- * Set the behavior of the current editing component to display formatted text when the client hovers over the text.
- *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
- * @param text The formatted text which will be displayed to the client upon hovering.
- * @return This builder instance.
- */
- public FancyMessage formattedTooltip(FancyMessage text) {
- for (MessagePart component : text.messageParts) {
- if (component.clickActionData != null && component.clickActionName != null) {
- throw new IllegalArgumentException("The tooltip text cannot have click data.");
- } else if (component.hoverActionData != null && component.hoverActionName != null) {
- throw new IllegalArgumentException("The tooltip text cannot have a tooltip.");
- }
- }
- onHover("show_text", text);
- return this;
- }
+ /**
+ * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message.
+ *
+ * @param replacements The replacements, in order, that will be used in the language-specific message.
+ * @return This builder instance.
+ */
+ public FancyMessage translationReplacements(final String... replacements) {
+ for (String str : replacements) {
+ latest().translationReplacements.add(new JsonString(str));
+ }
+ dirty = true;
- /**
- * Set the behavior of the current editing component to display the specified lines of formatted text when the client hovers over the text.
- *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
- * @param lines The lines of formatted text which will be displayed to the client upon hovering.
- * @return This builder instance.
- */
- public FancyMessage formattedTooltip(FancyMessage... lines) {
- if (lines.length < 1) {
- onHover(null, null); // Clear tooltip
- return this;
- }
+ return this;
+ }
+ /*
- FancyMessage result = new FancyMessage();
- result.messageParts.clear(); // Remove the one existing text component that exists by default, which destabilizes the object
+ /**
+ * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message.
+ * @param replacements The replacements, in order, that will be used in the language-specific message.
+ * @return This builder instance.
+ */ /* ------------
+ public FancyMessage translationReplacements(final Iterable extends CharSequence> replacements){
+ for(CharSequence str : replacements){
+ latest().translationReplacements.add(new JsonString(str));
+ }
- for (int i = 0; i < lines.length; i++) {
- try {
- for (MessagePart component : lines[i]) {
- if (component.clickActionData != null && component.clickActionName != null) {
- throw new IllegalArgumentException("The tooltip text cannot have click data.");
- } else if (component.hoverActionData != null && component.hoverActionName != null) {
- throw new IllegalArgumentException("The tooltip text cannot have a tooltip.");
- }
- if (component.hasText()) {
- result.messageParts.add(component.clone());
- }
- }
- if (i != lines.length - 1) {
- result.messageParts.add(new MessagePart(rawText("\n")));
- }
- } catch (CloneNotSupportedException e) {
- Bukkit.getLogger().log(Level.WARNING, "Failed to clone object", e);
- return this;
- }
- }
- return formattedTooltip(result.messageParts.isEmpty() ? null : result); // Throws NPE if size is 0, intended
- }
+ return this;
+ }
- /**
- * Set the behavior of the current editing component to display the specified lines of formatted text when the client hovers over the text.
- *
Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.
- * @param lines The lines of text which will be displayed to the client upon hovering. The iteration order of this object will be the order in
- * which the lines of the tooltip are created.
- * @return This builder instance.
- */
- public FancyMessage formattedTooltip(Iterable lines) {
- return formattedTooltip(ArrayWrapper.toArray(lines, FancyMessage.class));
- }
+ */
- /**
- * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the
- * message.
- * @param replacements The replacements, in order, that will be used in the language-specific message.
- * @return This builder instance.
- */
- public FancyMessage translationReplacements(String... replacements) {
- for (String str : replacements) {
- latest().translationReplacements.add(new JsonString(str));
- }
- this.dirty = true;
+ /**
+ * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message.
+ *
+ * @param replacements The replacements, in order, that will be used in the language-specific message.
+ * @return This builder instance.
+ */
+ public FancyMessage translationReplacements(final FancyMessage... replacements) {
+ for (FancyMessage str : replacements) {
+ latest().translationReplacements.add(str);
+ }
- return this;
- }
+ dirty = true;
- /**
- * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the
- * message.
- * @param replacements The replacements, in order, that will be used in the language-specific message.
- * @return This builder instance.
- */
- public FancyMessage translationReplacements(FancyMessage... replacements) {
- Collections.addAll(latest().translationReplacements, replacements);
+ return this;
+ }
- this.dirty = true;
+ /**
+ * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message.
+ *
+ * @param replacements The replacements, in order, that will be used in the language-specific message.
+ * @return This builder instance.
+ */
+ public FancyMessage translationReplacements(final Iterable replacements) {
+ return translationReplacements(com.plotsquared.bukkit.chat.ArrayWrapper.toArray(replacements, FancyMessage.class));
+ }
- return this;
- }
+ /**
+ * Terminate construction of the current editing component, and begin construction of a new message component.
+ * After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this method.
+ *
+ * @param text The text which will populate the new message component.
+ * @return This builder instance.
+ */
+ public FancyMessage then(final String text) {
+ return then(rawText(text));
+ }
- /**
- * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the
- * message.
- * @param replacements The replacements, in order, that will be used in the language-specific message.
- * @return This builder instance.
- */
- public FancyMessage translationReplacements(Iterable replacements) {
- return translationReplacements(ArrayWrapper.toArray(replacements, FancyMessage.class));
- }
+ /**
+ * Terminate construction of the current editing component, and begin construction of a new message component.
+ * After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this method.
+ *
+ * @param text The text which will populate the new message component.
+ * @return This builder instance.
+ */
+ public FancyMessage then(final com.plotsquared.bukkit.chat.TextualComponent text) {
+ if (!latest().hasText()) {
+ throw new IllegalStateException("previous message part has no text");
+ }
+ messageParts.add(new MessagePart(text));
+ dirty = true;
+ return this;
+ }
- /**
- * Terminate construction of the current editing component, and begin construction of a new message component.
- * After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this
- * method.
- * @param text The text which will populate the new message component.
- * @return This builder instance.
- */
- public FancyMessage then(String text) {
- return then(rawText(text));
- }
+ /**
+ * Terminate construction of the current editing component, and begin construction of a new message component.
+ * After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this method.
+ *
+ * @return This builder instance.
+ */
+ public FancyMessage then() {
+ if (!latest().hasText()) {
+ throw new IllegalStateException("previous message part has no text");
+ }
+ messageParts.add(new MessagePart());
+ dirty = true;
+ return this;
+ }
- /**
- * Terminate construction of the current editing component, and begin construction of a new message component.
- * After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this
- * method.
- * @param text The text which will populate the new message component.
- * @return This builder instance.
- */
- public FancyMessage then(TextualComponent text) {
- if (!latest().hasText()) {
- throw new IllegalStateException("previous message part has no text");
- }
- this.messageParts.add(new MessagePart(text));
- this.dirty = true;
- return this;
- }
+ @Override
+ public void writeJson(JsonWriter writer) throws IOException {
+ if (messageParts.size() == 1) {
+ latest().writeJson(writer);
+ } else {
+ writer.beginObject().name("text").value("").name("extra").beginArray();
+ for (final MessagePart part : this) {
+ part.writeJson(writer);
+ }
+ writer.endArray().endObject();
+ }
+ }
- /**
- * Terminate construction of the current editing component, and begin construction of a new message component.
- * After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this
- * method.
- * @return This builder instance.
- */
- public FancyMessage then() {
- if (!latest().hasText()) {
- throw new IllegalStateException("previous message part has no text");
- }
- this.messageParts.add(new MessagePart());
- this.dirty = true;
- return this;
- }
+ /**
+ * Serialize this fancy message, converting it into syntactically-valid JSON using a {@link JsonWriter}.
+ * This JSON should be compatible with vanilla formatter commands such as {@code /tellraw}.
+ *
+ * @return The JSON string representing this object.
+ */
+ public String toJSONString() {
+ if (!dirty && jsonString != null) {
+ return jsonString;
+ }
+ StringWriter string = new StringWriter();
+ JsonWriter json = new JsonWriter(string);
+ try {
+ writeJson(json);
+ json.close();
+ } catch (IOException e) {
+ throw new RuntimeException("invalid message");
+ }
+ jsonString = string.toString();
+ dirty = false;
+ return jsonString;
+ }
- @Override
- public void writeJson(JsonWriter writer) throws IOException {
- if (this.messageParts.size() == 1) {
- latest().writeJson(writer);
- } else {
- writer.beginObject().name("text").value("").name("extra").beginArray();
- for (MessagePart part : this) {
- part.writeJson(writer);
- }
- writer.endArray().endObject();
- }
- }
+ /**
+ * Sends this message to a player. The player will receive the fully-fledged formatted display of this message.
+ *
+ * @param player The player who will receive the message.
+ */
+ public void send(Player player) {
+ send(player, toJSONString());
+ }
- /**
- * Serialize this fancy message, converting it into syntactically-valid JSON using a {@link JsonWriter}.
- * This JSON should be compatible with vanilla formatter commands such as {@code /tellraw}.
- * @return The JSON string representing this object.
- */
- public String toJSONString() {
- if (!this.dirty && this.jsonString != null) {
- return this.jsonString;
- }
- StringWriter string = new StringWriter();
- JsonWriter json = new JsonWriter(string);
- try {
- writeJson(json);
- json.close();
- } catch (IOException ignored) {
- throw new RuntimeException("invalid message");
- }
- this.jsonString = string.toString();
- this.dirty = false;
- return this.jsonString;
- }
+ private void send(CommandSender sender, String jsonString) {
+ if (!(sender instanceof Player)) {
+ sender.sendMessage(toOldMessageFormat());
+ return;
+ }
+ Player player = (Player) sender;
+ try {
+ Object handle = com.plotsquared.bukkit.chat.Reflection.getHandle(player);
+ Object connection = com.plotsquared.bukkit.chat.Reflection.getField(handle.getClass(), "playerConnection").get(handle);
+ com.plotsquared.bukkit.chat.Reflection.getMethod(connection.getClass(), "sendPacket", com.plotsquared.bukkit.chat.Reflection.getNMSClass("Packet")).invoke(connection, createChatPacket(jsonString));
+ } catch (IllegalArgumentException e) {
+ Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
+ } catch (IllegalAccessException e) {
+ Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
+ } catch (InstantiationException e) {
+ Bukkit.getLogger().log(Level.WARNING, "Underlying class is abstract.", e);
+ } catch (InvocationTargetException e) {
+ Bukkit.getLogger().log(Level.WARNING, "A error has occured durring invoking of method.", e);
+ } catch (NoSuchMethodException e) {
+ Bukkit.getLogger().log(Level.WARNING, "Could not find method.", e);
+ } catch (ClassNotFoundException e) {
+ Bukkit.getLogger().log(Level.WARNING, "Could not find class.", e);
+ }
+ }
- /**
- * Sends this message to a player. The player will receive the fully-fledged formatted display of this message.
- * @param player The player who will receive the message.
- */
- public void send(Player player) {
- send(player, toJSONString());
- }
+ // The ChatSerializer's instance of Gson
+ private static Object nmsChatSerializerGsonInstance;
+ private static Method fromJsonMethod;
- private void send(CommandSender sender, String jsonString) {
- if (!(sender instanceof Player)) {
- sender.sendMessage(toOldMessageFormat());
- return;
- }
- Player player = (Player) sender;
- try {
- Object handle = Reflection.getHandle(player);
- Object connection = Reflection.getField(handle.getClass(), "playerConnection").get(handle);
- Reflection.getMethod(connection.getClass(), "sendPacket", Reflection.getNMSClass("Packet"))
- .invoke(connection, createChatPacket(jsonString));
- } catch (IllegalArgumentException e) {
- Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
- } catch (IllegalAccessException e) {
- Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
- } catch (InstantiationException e) {
- Bukkit.getLogger().log(Level.WARNING, "Underlying class is abstract.", e);
- } catch (InvocationTargetException e) {
- Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e);
- } catch (NoSuchMethodException e) {
- Bukkit.getLogger().log(Level.WARNING, "Could not find method.", e);
- } catch (ClassNotFoundException e) {
- Bukkit.getLogger().log(Level.WARNING, "Could not find class.", e);
- }
- }
+ private Object createChatPacket(String json) throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
+ if (nmsChatSerializerGsonInstance == null) {
+ // Find the field and its value, completely bypassing obfuscation
+ Class> chatSerializerClazz;
- private Object createChatPacket(String json)
- throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException,
- ClassNotFoundException {
- if (nmsChatSerializerGsonInstance == null) {
- // Find the field and its value, completely bypassing obfuscation
- Class> chatSerializerClazz;
+ // Get the three parts of the version string (major version is currently unused)
+ // vX_Y_RZ
+ // X = major
+ // Y = minor
+ // Z = revision
+ final String version = com.plotsquared.bukkit.chat.Reflection.getVersion();
+ String[] split = version.substring(1, version.length() - 1).split("_"); // Remove trailing dot
+ //int majorVersion = Integer.parseInt(split[0]);
+ int minorVersion = Integer.parseInt(split[1]);
+ int revisionVersion = Integer.parseInt(split[2].substring(1)); // Substring to ignore R
- String version = Reflection.getVersion();
- double majorVersion = Double.parseDouble(version.replace('_', '.').substring(1, 4));
- int lesserVersion = Integer.parseInt(version.substring(6, 7));
+ if (minorVersion < 8 || (minorVersion == 8 && revisionVersion == 1)) {
+ chatSerializerClazz = com.plotsquared.bukkit.chat.Reflection.getNMSClass("ChatSerializer");
+ } else {
+ chatSerializerClazz = com.plotsquared.bukkit.chat.Reflection.getNMSClass("IChatBaseComponent$ChatSerializer");
+ }
- if (majorVersion < 1.8 || majorVersion == 1.8 && lesserVersion == 1) {
- chatSerializerClazz = Reflection.getNMSClass("ChatSerializer");
- } else {
- chatSerializerClazz = Reflection.getNMSClass("IChatBaseComponent$ChatSerializer");
- }
+ if (chatSerializerClazz == null) {
+ throw new ClassNotFoundException("Can't find the ChatSerializer class");
+ }
- if (chatSerializerClazz == null) {
- throw new ClassNotFoundException("Can't find the ChatSerializer class");
- }
+ for (Field declaredField : chatSerializerClazz.getDeclaredFields()) {
+ if (Modifier.isFinal(declaredField.getModifiers()) && Modifier.isStatic(declaredField.getModifiers()) && declaredField.getType().getName().endsWith("Gson")) {
+ // We've found our field
+ declaredField.setAccessible(true);
+ nmsChatSerializerGsonInstance = declaredField.get(null);
+ fromJsonMethod = nmsChatSerializerGsonInstance.getClass().getMethod("fromJson", String.class, Class.class);
+ break;
+ }
+ }
+ }
- for (Field declaredField : chatSerializerClazz.getDeclaredFields()) {
- if (Modifier.isFinal(declaredField.getModifiers()) && Modifier.isStatic(declaredField.getModifiers()) && declaredField.getType()
- .getName().endsWith("Gson")) {
- // We've found our field
- declaredField.setAccessible(true);
- nmsChatSerializerGsonInstance = declaredField.get(null);
- fromJsonMethod = nmsChatSerializerGsonInstance.getClass().getMethod("fromJson", String.class, Class.class);
- break;
- }
- }
- }
+ // Since the method is so simple, and all the obfuscated methods have the same name, it's easier to reimplement 'IChatBaseComponent a(String)' than to reflectively call it
+ // Of course, the implementation may change, but fuzzy matches might break with signature changes
+ Object serializedChatComponent = fromJsonMethod.invoke(nmsChatSerializerGsonInstance, json, com.plotsquared.bukkit.chat.Reflection.getNMSClass("IChatBaseComponent"));
- /*
- Since the method is so simple, and all the obfuscated methods have the same name, it's easier to reimplement 'IChatBaseComponent a(String)'
- than to reflectively call it
- Of course, the implementation may change, but fuzzy matches might break with signature changes
- */
- Object serializedChatComponent = fromJsonMethod.invoke(nmsChatSerializerGsonInstance, json, Reflection.getNMSClass("IChatBaseComponent"));
+ return nmsPacketPlayOutChatConstructor.newInstance(serializedChatComponent);
+ }
- return nmsPacketPlayOutChatConstructor.newInstance(serializedChatComponent);
- }
+ /**
+ * Sends this message to a command sender.
+ * If the sender is a player, they will receive the fully-fledged formatted display of this message.
+ * Otherwise, they will receive a version of this message with less formatting.
+ *
+ * @param sender The command sender who will receive the message.
+ * @see #toOldMessageFormat()
+ */
+ public void send(CommandSender sender) {
+ send(sender, toJSONString());
+ }
- /**
- * Sends this message to a command sender.
- * If the sender is a player, they will receive the fully-fledged formatted display of this message.
- * Otherwise, they will receive a version of this message with less formatting.
- * @param sender The command sender who will receive the message.
- * @see #toOldMessageFormat()
- */
- public void send(CommandSender sender) {
- send(sender, toJSONString());
- }
+ /**
+ * Sends this message to multiple command senders.
+ *
+ * @param senders The command senders who will receive the message.
+ * @see #send(CommandSender)
+ */
+ public void send(final Iterable extends CommandSender> senders) {
+ String string = toJSONString();
+ for (final CommandSender sender : senders) {
+ send(sender, string);
+ }
+ }
- /**
- * Sends this message to multiple command senders.
- * @param senders The command senders who will receive the message.
- * @see #send(CommandSender)
- */
- public void send(Iterable extends CommandSender> senders) {
- String string = toJSONString();
- for (CommandSender sender : senders) {
- send(sender, string);
- }
- }
+ /**
+ * Convert this message to a human-readable string with limited formatting.
+ * This method is used to send this message to clients without JSON formatting support.
+ *
+ * Serialization of this message by using this message will include (in this order for each message part):
+ *
+ *
The color of each message part.
+ *
The applicable stylizations for each message part.
+ *
The core text of the message part.
+ *
+ * The primary omissions are tooltips and clickable actions. Consequently, this method should be used only as a last resort.
+ *
+ *
+ * Color and formatting can be removed from the returned string by using {@link ChatColor#stripColor(String)}.
+ *
+ * @return A human-readable string representing limited formatting in addition to the core text of this message.
+ */
+ public String toOldMessageFormat() {
+ StringBuilder result = new StringBuilder();
+ for (MessagePart part : this) {
+ result.append(part.color == null ? "" : part.color);
+ for (ChatColor formatSpecifier : part.styles) {
+ result.append(formatSpecifier);
+ }
+ result.append(part.text);
+ }
+ return result.toString();
+ }
- /**
- * Convert this message to a human-readable string with limited formatting.
- * This method is used to send this message to clients without JSON formatting support.
- *
- * Serialization of this message by using this message will include (in this order for each message part):
- *
- *
The color of each message part.
- *
The applicable stylization for each message part.
- *
The core text of the message part.
- *
- * The primary omissions are tooltips and clickable actions. Consequently, this method should be used only as a last resort.
- *
- *
- * Color and formatting can be removed from the returned string by using {@link ChatColor#stripColor(String)}.
- * @return A human-readable string representing limited formatting in addition to the core text of this message.
- */
- public String toOldMessageFormat() {
- StringBuilder result = new StringBuilder();
- for (MessagePart part : this) {
- result.append(part.color == null ? "" : part.color);
- for (ChatColor formatSpecifier : part.styles) {
- result.append(formatSpecifier);
- }
- result.append(part.text);
- }
- return result.toString();
- }
+ private MessagePart latest() {
+ return messageParts.get(messageParts.size() - 1);
+ }
- private MessagePart latest() {
- return this.messageParts.get(this.messageParts.size() - 1);
- }
+ private void onClick(final String name, final String data) {
+ final MessagePart latest = latest();
+ latest.clickActionName = name;
+ latest.clickActionData = data;
+ dirty = true;
+ }
- private void onClick(String name, String data) {
- MessagePart latest = latest();
- latest.clickActionName = name;
- latest.clickActionData = data;
- this.dirty = true;
- }
+ private void onHover(final String name, final JsonRepresentedObject data) {
+ final MessagePart latest = latest();
+ latest.hoverActionName = name;
+ latest.hoverActionData = data;
+ dirty = true;
+ }
- private void onHover(String name, JsonRepresentedObject data) {
- MessagePart latest = latest();
- latest.hoverActionName = name;
- latest.hoverActionData = data;
- this.dirty = true;
- }
+ // Doc copied from interface
+ public Map serialize() {
+ HashMap map = new HashMap();
+ map.put("messageParts", messageParts);
+// map.put("JSON", toJSONString());
+ return map;
+ }
- // Doc copied from interface
- @Override
- public Map serialize() {
- HashMap map = new HashMap<>();
- map.put("messageParts", this.messageParts);
- // map.put("JSON", toJSONString());
- return map;
- }
+ /**
+ * Deserializes a JSON-represented message from a mapping of key-value pairs.
+ * This is called by the Bukkit serialization API.
+ * It is not intended for direct public API consumption.
+ *
+ * @param serialized The key-value mapping which represents a fancy message.
+ */
+ @SuppressWarnings("unchecked")
+ public static FancyMessage deserialize(Map serialized) {
+ FancyMessage msg = new FancyMessage();
+ msg.messageParts = (List) serialized.get("messageParts");
+ msg.jsonString = serialized.containsKey("JSON") ? serialized.get("JSON").toString() : null;
+ msg.dirty = !serialized.containsKey("JSON");
+ return msg;
+ }
+
+ /**
+ * Internally called method. Not for API consumption.
+ */
+ public Iterator iterator() {
+ return messageParts.iterator();
+ }
+
+ private static JsonParser _stringParser = new JsonParser();
+
+ /**
+ * Deserializes a fancy message from its JSON representation. This JSON representation is of the format of
+ * that returned by {@link #toJSONString()}, and is compatible with vanilla inputs.
+ *
+ * @param json The JSON string which represents a fancy message.
+ * @return A {@code FancyMessage} representing the parameterized JSON message.
+ */
+ public static FancyMessage deserialize(String json) {
+ JsonObject serialized = _stringParser.parse(json).getAsJsonObject();
+ JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component
+ FancyMessage returnVal = new FancyMessage();
+ returnVal.messageParts.clear();
+ for (JsonElement mPrt : extra) {
+ MessagePart component = new MessagePart();
+ JsonObject messagePart = mPrt.getAsJsonObject();
+ for (Map.Entry entry : messagePart.entrySet()) {
+ // Deserialize text
+ if (com.plotsquared.bukkit.chat.TextualComponent.isTextKey(entry.getKey())) {
+ // The map mimics the YAML serialization, which has a "key" field and one or more "value" fields
+ Map serializedMapForm = new HashMap(); // Must be object due to Bukkit serializer API compliance
+ serializedMapForm.put("key", entry.getKey());
+ if (entry.getValue().isJsonPrimitive()) {
+ // Assume string
+ serializedMapForm.put("value", entry.getValue().getAsString());
+ } else {
+ // Composite object, but we assume each element is a string
+ for (Map.Entry compositeNestedElement : entry.getValue().getAsJsonObject().entrySet()) {
+ serializedMapForm.put("value." + compositeNestedElement.getKey(), compositeNestedElement.getValue().getAsString());
+ }
+ }
+ component.text = com.plotsquared.bukkit.chat.TextualComponent.deserialize(serializedMapForm);
+ } else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) {
+ if (entry.getValue().getAsBoolean()) {
+ component.styles.add(MessagePart.stylesToNames.inverse().get(entry.getKey()));
+ }
+ } else if (entry.getKey().equals("color")) {
+ component.color = ChatColor.valueOf(entry.getValue().getAsString().toUpperCase());
+ } else if (entry.getKey().equals("clickEvent")) {
+ JsonObject object = entry.getValue().getAsJsonObject();
+ component.clickActionName = object.get("action").getAsString();
+ component.clickActionData = object.get("value").getAsString();
+ } else if (entry.getKey().equals("hoverEvent")) {
+ JsonObject object = entry.getValue().getAsJsonObject();
+ component.hoverActionName = object.get("action").getAsString();
+ if (object.get("value").isJsonPrimitive()) {
+ // Assume string
+ component.hoverActionData = new JsonString(object.get("value").getAsString());
+ } else {
+ // Assume composite type
+ // The only composite type we currently store is another FancyMessage
+ // Therefore, recursion time!
+ component.hoverActionData = deserialize(object.get("value").toString() /* This should properly serialize the JSON object as a JSON string */);
+ }
+ } else if (entry.getKey().equals("insertion")) {
+ component.insertionData = entry.getValue().getAsString();
+ } else if (entry.getKey().equals("with")) {
+ for (JsonElement object : entry.getValue().getAsJsonArray()) {
+ if (object.isJsonPrimitive()) {
+ component.translationReplacements.add(new JsonString(object.getAsString()));
+ } else {
+ // Only composite type stored in this array is - again - FancyMessages
+ // Recurse within this function to parse this as a translation replacement
+ component.translationReplacements.add(deserialize(object.toString()));
+ }
+ }
+ }
+ }
+ returnVal.messageParts.add(component);
+ }
+ return returnVal;
+ }
- /**
- * Internally called method. Not for API consumption.
- */
- @Override
- public Iterator iterator() {
- return this.messageParts.iterator();
- }
}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java
index 0b3d7a98c..e76593f29 100644
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java
@@ -9,11 +9,11 @@ import java.io.IOException;
*/
interface JsonRepresentedObject {
- /**
- * Writes the JSON representation of this object to the specified writer.
- * @param writer The JSON writer which will receive the object.
- * @throws IOException If an error occurs writing to the stream.
- */
- void writeJson(JsonWriter writer) throws IOException;
-
+ /**
+ * Writes the JSON representation of this object to the specified writer.
+ * @param writer The JSON writer which will receive the object.
+ * @throws IOException If an error occurs writing to the stream.
+ */
+ public void writeJson(JsonWriter writer) throws IOException;
+
}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java
index 823511bb1..e62d98364 100644
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java
@@ -1,12 +1,12 @@
package com.plotsquared.bukkit.chat;
-import com.google.gson.stream.JsonWriter;
-import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
+import com.google.gson.stream.JsonWriter;
+import org.bukkit.configuration.serialization.ConfigurationSerializable;
+
/**
* Represents a JSON string value.
* Writes by this object will not write name values nor begin/end objects in the JSON stream.
@@ -14,34 +14,34 @@ import java.util.Map;
*/
final class JsonString implements JsonRepresentedObject, ConfigurationSerializable {
- private final String value;
+ private String _value;
- public JsonString(CharSequence value) {
- this.value = value == null ? null : value.toString();
- }
+ public JsonString(CharSequence value) {
+ _value = value == null ? null : value.toString();
+ }
- public static JsonString deserialize(Map map) {
- return new JsonString(map.get("stringValue").toString());
- }
+ @Override
+ public void writeJson(JsonWriter writer) throws IOException {
+ writer.value(getValue());
+ }
- @Override
- public void writeJson(JsonWriter writer) throws IOException {
- writer.value(getValue());
- }
+ public String getValue() {
+ return _value;
+ }
- public String getValue() {
- return this.value;
- }
+ public Map serialize() {
+ HashMap theSingleValue = new HashMap();
+ theSingleValue.put("stringValue", _value);
+ return theSingleValue;
+ }
- @Override
- public Map serialize() {
- HashMap theSingleValue = new HashMap<>();
- theSingleValue.put("stringValue", this.value);
- return theSingleValue;
- }
+ public static JsonString deserialize(Map map) {
+ return new JsonString(map.get("stringValue").toString());
+ }
+
+ @Override
+ public String toString() {
+ return _value;
+ }
- @Override
- public String toString() {
- return this.value;
- }
}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java
index 6c5d17e16..dcdc71ee3 100644
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java
@@ -3,10 +3,10 @@ package com.plotsquared.bukkit.chat;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.gson.stream.JsonWriter;
-import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable;
-import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
+import org.bukkit.configuration.serialization.ConfigurationSerializable;
+import org.bukkit.configuration.serialization.ConfigurationSerialization;
import java.io.IOException;
import java.util.ArrayList;
@@ -19,133 +19,137 @@ import java.util.logging.Level;
*/
final class MessagePart implements JsonRepresentedObject, ConfigurationSerializable, Cloneable {
- static final BiMap stylesToNames;
+ ChatColor color = ChatColor.WHITE;
+ ArrayList styles = new ArrayList();
+ String clickActionName = null, clickActionData = null, hoverActionName = null;
+ JsonRepresentedObject hoverActionData = null;
+ TextualComponent text = null;
+ String insertionData = null;
+ ArrayList translationReplacements = new ArrayList();
- static {
- ImmutableBiMap.Builder builder = ImmutableBiMap.builder();
- for (ChatColor style : ChatColor.values()) {
- if (!style.isFormat()) {
- continue;
- }
+ MessagePart(final TextualComponent text) {
+ this.text = text;
+ }
- String styleName;
- switch (style) {
- case MAGIC:
- styleName = "obfuscated";
- break;
- case UNDERLINE:
- styleName = "underlined";
- break;
- default:
- styleName = style.name().toLowerCase();
- break;
- }
+ MessagePart() {
+ this.text = null;
+ }
- builder.put(style, styleName);
- }
- stylesToNames = builder.build();
- }
+ boolean hasText() {
+ return text != null;
+ }
- static {
- ConfigurationSerialization.registerClass(MessagePart.class);
- }
+ @Override
+ @SuppressWarnings("unchecked")
+ public MessagePart clone() throws CloneNotSupportedException {
+ MessagePart obj = (MessagePart) super.clone();
+ obj.styles = (ArrayList) styles.clone();
+ if (hoverActionData instanceof JsonString) {
+ obj.hoverActionData = new JsonString(((JsonString) hoverActionData).getValue());
+ } else if (hoverActionData instanceof FancyMessage) {
+ obj.hoverActionData = ((FancyMessage) hoverActionData).clone();
+ }
+ obj.translationReplacements = (ArrayList) translationReplacements.clone();
+ return obj;
- ChatColor color = ChatColor.WHITE;
- ArrayList styles = new ArrayList<>();
- String clickActionName = null, clickActionData = null, hoverActionName = null;
- JsonRepresentedObject hoverActionData = null;
- TextualComponent text = null;
- String insertionData = null;
- ArrayList translationReplacements = new ArrayList<>();
+ }
- MessagePart(TextualComponent text) {
- this.text = text;
- }
+ static final BiMap stylesToNames;
- MessagePart() {
- this.text = null;
- }
+ static {
+ ImmutableBiMap.Builder builder = ImmutableBiMap.builder();
+ for (final ChatColor style : ChatColor.values()) {
+ if (!style.isFormat()) {
+ continue;
+ }
- @SuppressWarnings("unchecked")
- public static MessagePart deserialize(Map serialized) {
- MessagePart part = new MessagePart((TextualComponent) serialized.get("text"));
- part.styles = (ArrayList) serialized.get("styles");
- part.color = ChatColor.getByChar(serialized.get("color").toString());
- part.hoverActionName = (String) serialized.get("hoverActionName");
- part.hoverActionData = (JsonRepresentedObject) serialized.get("hoverActionData");
- part.clickActionName = (String) serialized.get("clickActionName");
- part.clickActionData = (String) serialized.get("clickActionData");
- part.insertionData = (String) serialized.get("insertion");
- part.translationReplacements = (ArrayList) serialized.get("translationReplacements");
- return part;
- }
+ String styleName;
+ switch (style) {
+ case MAGIC:
+ styleName = "obfuscated";
+ break;
+ case UNDERLINE:
+ styleName = "underlined";
+ break;
+ default:
+ styleName = style.name().toLowerCase();
+ break;
+ }
- boolean hasText() {
- return this.text != null;
- }
+ builder.put(style, styleName);
+ }
+ stylesToNames = builder.build();
+ }
- @Override
- @SuppressWarnings("unchecked")
- public MessagePart clone() throws CloneNotSupportedException {
- MessagePart obj = (MessagePart) super.clone();
- obj.styles = (ArrayList) this.styles.clone();
- if (this.hoverActionData instanceof JsonString) {
- obj.hoverActionData = new JsonString(((JsonString) this.hoverActionData).getValue());
- } else if (this.hoverActionData instanceof FancyMessage) {
- obj.hoverActionData = ((FancyMessage) this.hoverActionData).clone();
- }
- obj.translationReplacements = (ArrayList) this.translationReplacements.clone();
- return obj;
+ public void writeJson(JsonWriter json) {
+ try {
+ json.beginObject();
+ text.writeJson(json);
+ json.name("color").value(color.name().toLowerCase());
+ for (final ChatColor style : styles) {
+ json.name(stylesToNames.get(style)).value(true);
+ }
+ if (clickActionName != null && clickActionData != null) {
+ json.name("clickEvent")
+ .beginObject()
+ .name("action").value(clickActionName)
+ .name("value").value(clickActionData)
+ .endObject();
+ }
+ if (hoverActionName != null && hoverActionData != null) {
+ json.name("hoverEvent")
+ .beginObject()
+ .name("action").value(hoverActionName)
+ .name("value");
+ hoverActionData.writeJson(json);
+ json.endObject();
+ }
+ if (insertionData != null) {
+ json.name("insertion").value(insertionData);
+ }
+ if (translationReplacements.size() > 0 && text != null && TextualComponent.isTranslatableText(text)) {
+ json.name("with").beginArray();
+ for (JsonRepresentedObject obj : translationReplacements) {
+ obj.writeJson(json);
+ }
+ json.endArray();
+ }
+ json.endObject();
+ } catch (IOException e) {
+ Bukkit.getLogger().log(Level.WARNING, "A problem occured during writing of JSON string", e);
+ }
+ }
- }
+ public Map serialize() {
+ HashMap map = new HashMap();
+ map.put("text", text);
+ map.put("styles", styles);
+ map.put("color", color.getChar());
+ map.put("hoverActionName", hoverActionName);
+ map.put("hoverActionData", hoverActionData);
+ map.put("clickActionName", clickActionName);
+ map.put("clickActionData", clickActionData);
+ map.put("insertion", insertionData);
+ map.put("translationReplacements", translationReplacements);
+ return map;
+ }
- @Override
- public void writeJson(JsonWriter json) {
- try {
- json.beginObject();
- this.text.writeJson(json);
- json.name("color").value(this.color.name().toLowerCase());
- for (ChatColor style : this.styles) {
- json.name(stylesToNames.get(style)).value(true);
- }
- if ((this.clickActionName != null) && (this.clickActionData != null)) {
- json.name("clickEvent").beginObject().name("action").value(this.clickActionName).name("value").value(this.clickActionData)
- .endObject();
- }
- if ((this.hoverActionName != null) && (this.hoverActionData != null)) {
- json.name("hoverEvent").beginObject().name("action").value(this.hoverActionName).name("value");
- this.hoverActionData.writeJson(json);
- json.endObject();
- }
- if (this.insertionData != null) {
- json.name("insertion").value(this.insertionData);
- }
- if (!this.translationReplacements.isEmpty() && (this.text != null) && TextualComponent.isTranslatableText(this.text)) {
- json.name("with").beginArray();
- for (JsonRepresentedObject obj : this.translationReplacements) {
- obj.writeJson(json);
- }
- json.endArray();
- }
- json.endObject();
- } catch (IOException e) {
- Bukkit.getLogger().log(Level.WARNING, "A problem occurred during writing of JSON string", e);
- }
- }
+ @SuppressWarnings("unchecked")
+ public static MessagePart deserialize(Map serialized) {
+ MessagePart part = new MessagePart((TextualComponent) serialized.get("text"));
+ part.styles = (ArrayList) serialized.get("styles");
+ part.color = ChatColor.getByChar(serialized.get("color").toString());
+ part.hoverActionName = (String) serialized.get("hoverActionName");
+ part.hoverActionData = (JsonRepresentedObject) serialized.get("hoverActionData");
+ part.clickActionName = (String) serialized.get("clickActionName");
+ part.clickActionData = (String) serialized.get("clickActionData");
+ part.insertionData = (String) serialized.get("insertion");
+ part.translationReplacements = (ArrayList) serialized.get("translationReplacements");
+ return part;
+ }
- @Override
- public Map serialize() {
- HashMap map = new HashMap<>();
- map.put("text", this.text);
- map.put("styles", this.styles);
- map.put("color", this.color.getChar());
- map.put("hoverActionName", this.hoverActionName);
- map.put("hoverActionData", this.hoverActionData);
- map.put("clickActionName", this.clickActionName);
- map.put("clickActionData", this.clickActionData);
- map.put("insertion", this.insertionData);
- map.put("translationReplacements", this.translationReplacements);
- return map;
- }
+ static {
+ ConfigurationSerialization.registerClass(MessagePart.class);
+ }
}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java
index a67b886e6..636c20091 100644
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java
@@ -1,9 +1,8 @@
package com.plotsquared.bukkit.chat;
-import com.intellectualcrafters.plot.PS;
+import org.bukkit.Bukkit;
import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
@@ -15,191 +14,205 @@ import java.util.Map;
*/
public final class Reflection {
- /**
- * Stores loaded classes from the {@code net.minecraft.server} package.
- */
- private static final Map> _loadedNMSClasses = new HashMap<>();
- /**
- * Stores loaded classes from the {@code org.bukkit.craftbukkit} package (and subpackages).
- */
- private static final Map> _loadedOBCClasses = new HashMap<>();
- private static final Map, Map> _loadedFields = new HashMap<>();
- /**
- * Contains loaded methods in a cache.
- * The map maps [types to maps of [method names to maps of [parameter types to method instances]]].
- */
- private static final Map, Map>, Method>>> _loadedMethods = new HashMap<>();
+ private static String _versionString;
- /**
- * Gets the version string from the package name of the CraftBukkit server implementation.
- * This is needed to bypass the JAR package name changing on each update.
- * @return The version string of the OBC and NMS packages, including the trailing dot.
- */
- public static synchronized String getVersion() {
- return PS.get().IMP.getNMSPackage();
- }
+ private Reflection() { }
- /**
- * Gets a {@link Class} object representing a type contained within the {@code net.minecraft.server} versioned package.
- * The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this
- * method simultaneously).
- * @param className The name of the class, excluding the package, within NMS.
- * @return The class instance representing the specified NMS class, or {@code null} if it could not be loaded.
- */
- public static synchronized Class> getNMSClass(String className) {
- if (_loadedNMSClasses.containsKey(className)) {
- return _loadedNMSClasses.get(className);
- }
+ /**
+ * Gets the version string from the package name of the CraftBukkit server implementation.
+ * This is needed to bypass the JAR package name changing on each update.
+ *
+ * @return The version string of the OBC and NMS packages, including the trailing dot.
+ */
+ public synchronized static String getVersion() {
+ if (_versionString == null) {
+ if (Bukkit.getServer() == null) {
+ // The server hasn't started, static initializer call?
+ return null;
+ }
+ String name = Bukkit.getServer().getClass().getPackage().getName();
+ _versionString = name.substring(name.lastIndexOf('.') + 1) + ".";
+ }
- String fullName = "net.minecraft.server." + getVersion() + '.' + className;
- Class> clazz;
- try {
- clazz = Class.forName(fullName);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- _loadedNMSClasses.put(className, null);
- return null;
- }
- _loadedNMSClasses.put(className, clazz);
- return clazz;
- }
+ return _versionString;
+ }
- /**
- * Gets a {@link Class} object representing a type contained within the {@code org.bukkit.craftbukkit} versioned package.
- * The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this
- * method simultaneously).
- * @param className The name of the class, excluding the package, within OBC. This name may contain a subpackage name, such as {@code inventory
- * .CraftItemStack}.
- * @return The class instance representing the specified OBC class, or {@code null} if it could not be loaded.
- */
- public static synchronized Class> getOBCClass(String className) {
- if (_loadedOBCClasses.containsKey(className)) {
- return _loadedOBCClasses.get(className);
- }
+ /**
+ * Stores loaded classes from the {@code net.minecraft.server} package.
+ */
+ private static final Map> _loadedNMSClasses = new HashMap>();
- String fullName = "org.bukkit.craftbukkit." + getVersion() + '.' + className;
- Class> clazz;
- try {
- clazz = Class.forName(fullName);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- _loadedOBCClasses.put(className, null);
- return null;
- }
- _loadedOBCClasses.put(className, clazz);
- return clazz;
- }
+ /**
+ * Stores loaded classes from the {@code org.bukkit.craftbukkit} package (and subpackages).
+ */
+ private static final Map> _loadedOBCClasses = new HashMap>();
- /**
- * Attempts to get the NMS handle of a CraftBukkit object.
- *
- * The only match currently attempted by this method is a retrieval by using a parameterless {@code getHandle()} method implemented by the
- * runtime type of the specified object.
- *
- * @param obj The object for which to retrieve an NMS handle.
- * @return The NMS handle of the specified object, or {@code null} if it could not be retrieved using {@code getHandle()}.
- */
- public static synchronized Object getHandle(Object obj) {
- try {
- return getMethod(obj.getClass(), "getHandle").invoke(obj);
- } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
- e.printStackTrace();
- return null;
- }
- }
+ /**
+ * Gets a {@link Class} object representing a type contained within the {@code net.minecraft.server} versioned package.
+ * The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously).
+ *
+ * @param className The name of the class, excluding the package, within NMS.
+ * @return The class instance representing the specified NMS class, or {@code null} if it could not be loaded.
+ */
+ public synchronized static Class> getNMSClass(String className) {
+ if (_loadedNMSClasses.containsKey(className)) {
+ return _loadedNMSClasses.get(className);
+ }
- /**
- * Retrieves a {@link Field} instance declared by the specified class with the specified name.
- * Java access modifiers are ignored during this retrieval.
- * No guarantee is made as to whether the field returned will be an
- * instance or static field.
- *
- * A global caching mechanism within this class is used to store fields. Combined with synchronization, this guarantees that
- * no field will be reflectively looked up twice.
- *
- *
- * If a field is deemed suitable for return,
- * {@link Field#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned.
- * This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance.
- *
- * @param clazz The class which contains the field to retrieve.
- * @param name The declared name of the field in the class.
- * @return A field object with the specified name declared by the specified class.
- * @see Class#getDeclaredField(String)
- */
- public static synchronized Field getField(Class> clazz, String name) {
- Map loaded;
- if (!_loadedFields.containsKey(clazz)) {
- loaded = new HashMap<>();
- _loadedFields.put(clazz, loaded);
- } else {
- loaded = _loadedFields.get(clazz);
- }
- if (loaded.containsKey(name)) {
- // If the field is loaded (or cached as not existing), return the relevant value, which might be null
- return loaded.get(name);
- }
- try {
- Field field = clazz.getDeclaredField(name);
- field.setAccessible(true);
- loaded.put(name, field);
- return field;
- } catch (NoSuchFieldException | SecurityException e) {
- // Error loading
- e.printStackTrace();
- // Cache field as not existing
- loaded.put(name, null);
- return null;
- }
- }
+ String fullName = "net.minecraft.server." + getVersion() + className;
+ Class> clazz = null;
+ try {
+ clazz = Class.forName(fullName);
+ } catch (Exception e) {
+ e.printStackTrace();
+ _loadedNMSClasses.put(className, null);
+ return null;
+ }
+ _loadedNMSClasses.put(className, clazz);
+ return clazz;
+ }
- /**
- * Retrieves a {@link Method} instance declared by the specified class with the specified name and argument types.
- * Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field
- * returned will be an instance or static field.
- *
- * A global caching mechanism within this class is used to store method. Combined with synchronization, this guarantees that
- * no method will be reflectively looked up twice.
- *
- *
- * If a method is deemed suitable for return, {@link Method#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code
- * true} before it is returned.
- * This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance.
- *
- *
- *
- * This method does not search superclasses of the specified type for methods with the specified signature.
- * Callers wishing this behavior should use {@link Class#getDeclaredMethod(String, Class...)}.
- * @param clazz The class which contains the method to retrieve.
- * @param name The declared name of the method in the class.
- * @param args The formal argument types of the method.
- * @return A method object with the specified name declared by the specified class.
- */
- public static synchronized Method getMethod(Class> clazz, String name, Class>... args) {
- if (!_loadedMethods.containsKey(clazz)) {
- _loadedMethods.put(clazz, new HashMap>, Method>>());
- }
+ /**
+ * Gets a {@link Class} object representing a type contained within the {@code org.bukkit.craftbukkit} versioned package.
+ * The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously).
+ *
+ * @param className The name of the class, excluding the package, within OBC. This name may contain a subpackage name, such as {@code inventory.CraftItemStack}.
+ * @return The class instance representing the specified OBC class, or {@code null} if it could not be loaded.
+ */
+ public synchronized static Class> getOBCClass(String className) {
+ if (_loadedOBCClasses.containsKey(className)) {
+ return _loadedOBCClasses.get(className);
+ }
- Map>, Method>> loadedMethodNames = _loadedMethods.get(clazz);
- if (!loadedMethodNames.containsKey(name)) {
- loadedMethodNames.put(name, new HashMap>, Method>());
- }
+ String fullName = "org.bukkit.craftbukkit." + getVersion() + className;
+ Class> clazz = null;
+ try {
+ clazz = Class.forName(fullName);
+ } catch (Exception e) {
+ e.printStackTrace();
+ _loadedOBCClasses.put(className, null);
+ return null;
+ }
+ _loadedOBCClasses.put(className, clazz);
+ return clazz;
+ }
- Map>, Method> loadedSignatures = loadedMethodNames.get(name);
- ArrayWrapper> wrappedArg = new ArrayWrapper<>(args);
- if (loadedSignatures.containsKey(wrappedArg)) {
- return loadedSignatures.get(wrappedArg);
- }
+ /**
+ * Attempts to get the NMS handle of a CraftBukkit object.
+ *
+ * The only match currently attempted by this method is a retrieval by using a parameterless {@code getHandle()} method implemented by the runtime type of the specified object.
+ *
+ *
+ * @param obj The object for which to retrieve an NMS handle.
+ * @return The NMS handle of the specified object, or {@code null} if it could not be retrieved using {@code getHandle()}.
+ */
+ public synchronized static Object getHandle(Object obj) {
+ try {
+ return getMethod(obj.getClass(), "getHandle").invoke(obj);
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
- for (Method m : clazz.getMethods()) {
- if (m.getName().equals(name) && Arrays.equals(args, m.getParameterTypes())) {
- m.setAccessible(true);
- loadedSignatures.put(wrappedArg, m);
- return m;
- }
- }
- loadedSignatures.put(wrappedArg, null);
- return null;
- }
+ private static final Map, Map> _loadedFields = new HashMap, Map>();
+
+ /**
+ * Retrieves a {@link Field} instance declared by the specified class with the specified name.
+ * Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field
+ * returned will be an instance or static field.
+ *
+ * A global caching mechanism within this class is used to store fields. Combined with synchronization, this guarantees that
+ * no field will be reflectively looked up twice.
+ *
+ *
+ * If a field is deemed suitable for return, {@link Field#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned.
+ * This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance.
+ *
+ *
+ * @param clazz The class which contains the field to retrieve.
+ * @param name The declared name of the field in the class.
+ * @return A field object with the specified name declared by the specified class.
+ * @see Class#getDeclaredField(String)
+ */
+ public synchronized static Field getField(Class> clazz, String name) {
+ Map loaded;
+ if (!_loadedFields.containsKey(clazz)) {
+ loaded = new HashMap();
+ _loadedFields.put(clazz, loaded);
+ } else {
+ loaded = _loadedFields.get(clazz);
+ }
+ if (loaded.containsKey(name)) {
+ // If the field is loaded (or cached as not existing), return the relevant value, which might be null
+ return loaded.get(name);
+ }
+ try {
+ Field field = clazz.getDeclaredField(name);
+ field.setAccessible(true);
+ loaded.put(name, field);
+ return field;
+ } catch (Exception e) {
+ // Error loading
+ e.printStackTrace();
+ // Cache field as not existing
+ loaded.put(name, null);
+ return null;
+ }
+ }
+
+ /**
+ * Contains loaded methods in a cache.
+ * The map maps [types to maps of [method names to maps of [parameter types to method instances]]].
+ */
+ private static final Map, Map>, Method>>> _loadedMethods = new HashMap, Map>, Method>>>();
+
+ /**
+ * Retrieves a {@link Method} instance declared by the specified class with the specified name and argument types.
+ * Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field
+ * returned will be an instance or static field.
+ *
+ * A global caching mechanism within this class is used to store method. Combined with synchronization, this guarantees that
+ * no method will be reflectively looked up twice.
+ *
+ *
+ * If a method is deemed suitable for return, {@link Method#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned.
+ * This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance.
+ *
+ *
+ * This method does not search superclasses of the specified type for methods with the specified signature.
+ * Callers wishing this behavior should use {@link Class#getDeclaredMethod(String, Class...)}.
+ *
+ * @param clazz The class which contains the method to retrieve.
+ * @param name The declared name of the method in the class.
+ * @param args The formal argument types of the method.
+ * @return A method object with the specified name declared by the specified class.
+ */
+ public synchronized static Method getMethod(Class> clazz, String name, Class>... args) {
+ if (!_loadedMethods.containsKey(clazz)) {
+ _loadedMethods.put(clazz, new HashMap>, Method>>());
+ }
+
+ Map>, Method>> loadedMethodNames = _loadedMethods.get(clazz);
+ if (!loadedMethodNames.containsKey(name)) {
+ loadedMethodNames.put(name, new HashMap>, Method>());
+ }
+
+ Map>, Method> loadedSignatures = loadedMethodNames.get(name);
+ ArrayWrapper> wrappedArg = new ArrayWrapper>(args);
+ if (loadedSignatures.containsKey(wrappedArg)) {
+ return loadedSignatures.get(wrappedArg);
+ }
+
+ for (Method m : clazz.getMethods()) {
+ if (m.getName().equals(name) && Arrays.equals(args, m.getParameterTypes())) {
+ m.setAccessible(true);
+ loadedSignatures.put(wrappedArg, m);
+ return m;
+ }
+ }
+ loadedSignatures.put(wrappedArg, null);
+ return null;
+ }
}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java
index a3651d15a..002aea95b 100644
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java
@@ -3,8 +3,8 @@ package com.plotsquared.bukkit.chat;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.gson.stream.JsonWriter;
-import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable;
-import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization;
+import org.bukkit.configuration.serialization.ConfigurationSerializable;
+import org.bukkit.configuration.serialization.ConfigurationSerialization;
import java.io.IOException;
import java.util.HashMap;
@@ -18,285 +18,280 @@ import java.util.Map;
*/
public abstract class TextualComponent implements Cloneable {
- static {
- ConfigurationSerialization.registerClass(TextualComponent.ArbitraryTextTypeComponent.class);
- ConfigurationSerialization.registerClass(TextualComponent.ComplexTextTypeComponent.class);
- }
+ static {
+ ConfigurationSerialization.registerClass(TextualComponent.ArbitraryTextTypeComponent.class);
+ ConfigurationSerialization.registerClass(TextualComponent.ComplexTextTypeComponent.class);
+ }
- static TextualComponent deserialize(Map map) {
- if (map.containsKey("key") && (map.size() == 2) && map.containsKey("value")) {
- // Arbitrary text component
- return ArbitraryTextTypeComponent.deserialize(map);
- } else if ((map.size() >= 2) && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */) {
- // Complex JSON object
- return ComplexTextTypeComponent.deserialize(map);
- }
+ @Override
+ public String toString() {
+ return getReadableString();
+ }
- return null;
- }
+ /**
+ * @return The JSON key used to represent text components of this type.
+ */
+ public abstract String getKey();
- static boolean isTextKey(String key) {
- return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector");
- }
+ /**
+ * @return A readable String
+ */
+ public abstract String getReadableString();
- static boolean isTranslatableText(TextualComponent component) {
- return (component instanceof ComplexTextTypeComponent) && component.getKey().equals("translate");
- }
+ /**
+ * Clones a textual component instance.
+ * The returned object should not reference this textual component instance, but should maintain the same key and value.
+ */
+ @Override
+ public abstract TextualComponent clone() throws CloneNotSupportedException;
- /**
- * Create a textual component representing a string literal.
- * This is the default type of textual component when a single string literal is given to a method.
- * @param textValue The text which will be represented.
- * @return The text component representing the specified literal text.
- */
- public static TextualComponent rawText(String textValue) {
- return new ArbitraryTextTypeComponent("text", textValue);
- }
+ /**
+ * Writes the text data represented by this textual component to the specified JSON writer object.
+ * A new object within the writer is not started.
+ *
+ * @param writer The object to which to write the JSON data.
+ * @throws IOException If an error occurs while writing to the stream.
+ */
+ public abstract void writeJson(JsonWriter writer) throws IOException;
- /**
- * Create a textual component representing a localized string.
- * The client will see this text component as their localized version of the specified string key, which can be overridden by a
- * resource pack.
- *
- * If the specified translation key is not present on the client resource pack, the translation key will be displayed as a string literal to
- * the client.
- *
- * @param translateKey The string key which maps to localized text.
- * @return The text component representing the specified localized text.
- */
- public static TextualComponent localizedText(String translateKey) {
- return new ArbitraryTextTypeComponent("translate", translateKey);
- }
+ static TextualComponent deserialize(Map map) {
+ if (map.containsKey("key") && map.size() == 2 && map.containsKey("value")) {
+ // Arbitrary text component
+ return ArbitraryTextTypeComponent.deserialize(map);
+ } else if (map.size() >= 2 && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */) {
+ // Complex JSON object
+ return ComplexTextTypeComponent.deserialize(map);
+ }
- private static void throwUnsupportedSnapshot() {
- throw new UnsupportedOperationException("This feature is only supported in snapshot releases.");
- }
+ return null;
+ }
- /**
- * Create a textual component representing a scoreboard value.
- * The client will see their own score for the specified objective as the text represented by this component.
- *
- * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.
- *
- * @param scoreboardObjective The name of the objective for which to display the score.
- * @return The text component representing the specified scoreboard score (for the viewing player), or {@code null} if an error occurs during
- * JSON serialization.
- */
- public static TextualComponent objectiveScore(String scoreboardObjective) {
- return objectiveScore("*", scoreboardObjective);
- }
+ static boolean isTextKey(String key) {
+ return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector");
+ }
- /**
- * Create a textual component representing a scoreboard value.
- * The client will see the score of the specified player for the specified objective as the text represented by this component.
- *
- * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.
- *
- * @param playerName The name of the player whos score will be shown. If this string represents the single-character sequence "*", the viewing
- * player's score will be displayed.
- * Standard minecraft selectors (@a, @p, etc) are not supported.
- * @param scoreboardObjective The name of the objective for which to display the score.
- * @return The text component representing the specified scoreboard score for the specified player, or {@code null} if an error occurs during
- * JSON serialization.
- */
- public static TextualComponent objectiveScore(String playerName, String scoreboardObjective) {
- throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE
- // OVERLOADS documentation accordingly
+ static boolean isTranslatableText(TextualComponent component) {
+ return component instanceof ComplexTextTypeComponent && ((ComplexTextTypeComponent) component).getKey().equals("translate");
+ }
- return new ComplexTextTypeComponent("score",
- ImmutableMap.builder().put("name", playerName).put("objective", scoreboardObjective).build());
- }
+ /**
+ * Internal class used to represent all types of text components.
+ * Exception validating done is on keys and values.
+ */
+ private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
- /**
- * Create a textual component representing a player name, retrievable by using a standard minecraft selector.
- * The client will see the players or entities captured by the specified selector as the text represented by this component.
- *
- * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.
- *
- * @param selector The minecraft player or entity selector which will capture the entities whose string representations will be displayed in
- * the place of this text component.
- * @return The text component representing the name of the entities captured by the selector.
- */
- public static TextualComponent selector(String selector) {
- throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE
- // OVERLOADS documentation accordingly
+ public ArbitraryTextTypeComponent(String key, String value) {
+ setKey(key);
+ setValue(value);
+ }
- return new ArbitraryTextTypeComponent("selector", selector);
- }
+ @Override
+ public String getKey() {
+ return _key;
+ }
- @Override
- public String toString() {
- return getReadableString();
- }
+ public void setKey(String key) {
+ Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
+ _key = key;
+ }
- /**
- * @return The JSON key used to represent text components of this type.
- */
- public abstract String getKey();
+ public String getValue() {
+ return _value;
+ }
- /**
- * @return A readable String
- */
- public abstract String getReadableString();
+ public void setValue(String value) {
+ Preconditions.checkArgument(value != null, "The value must be specified.");
+ _value = value;
+ }
- /**
- * Clones a textual component instance.
- * The returned object should not reference this textual component instance, but should maintain the same key and value.
- */
- @Override
- public abstract TextualComponent clone() throws CloneNotSupportedException;
+ private String _key;
+ private String _value;
- /**
- * Writes the text data represented by this textual component to the specified JSON writer object.
- * A new object within the writer is not started.
- * @param writer The object to which to write the JSON data.
- * @throws IOException If an error occurs while writing to the stream.
- */
- public abstract void writeJson(JsonWriter writer) throws IOException;
+ @Override
+ public TextualComponent clone() throws CloneNotSupportedException {
+ // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
+ return new ArbitraryTextTypeComponent(getKey(), getValue());
+ }
- /**
- * Internal class used to represent all types of text components.
- * Exception validating done is on keys and values.
- */
- private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
+ @Override
+ public void writeJson(JsonWriter writer) throws IOException {
+ writer.name(getKey()).value(getValue());
+ }
- private String _key;
- private String _value;
+ @SuppressWarnings("serial")
+ public Map serialize() {
+ return new HashMap() {{
+ put("key", getKey());
+ put("value", getValue());
+ }};
+ }
- public ArbitraryTextTypeComponent(String key, String value) {
- setKey(key);
- setValue(value);
- }
+ public static ArbitraryTextTypeComponent deserialize(Map map) {
+ return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString());
+ }
- public static ArbitraryTextTypeComponent deserialize(Map map) {
- return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString());
- }
+ @Override
+ public String getReadableString() {
+ return getValue();
+ }
+ }
- @Override
- public String getKey() {
- return this._key;
- }
+ /**
+ * Internal class used to represent a text component with a nested JSON value.
+ * Exception validating done is on keys and values.
+ */
+ private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
- public void setKey(String key) {
- Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified.");
- this._key = key;
- }
+ public ComplexTextTypeComponent(String key, Map values) {
+ setKey(key);
+ setValue(values);
+ }
- public String getValue() {
- return this._value;
- }
+ @Override
+ public String getKey() {
+ return _key;
+ }
- public void setValue(String value) {
- Preconditions.checkArgument(value != null, "The value must be specified.");
- this._value = value;
- }
+ public void setKey(String key) {
+ Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
+ _key = key;
+ }
- @Override
- public TextualComponent clone() {
- // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
- return new ArbitraryTextTypeComponent(getKey(), getValue());
- }
+ public Map getValue() {
+ return _value;
+ }
- @Override
- public void writeJson(JsonWriter writer) throws IOException {
- writer.name(getKey()).value(getValue());
- }
+ public void setValue(Map value) {
+ Preconditions.checkArgument(value != null, "The value must be specified.");
+ _value = value;
+ }
- @Override
- @SuppressWarnings("serial")
- public Map serialize() {
- return new HashMap() {
- {
- put("key", getKey());
- put("value", getValue());
- }
- };
- }
+ private String _key;
+ private Map _value;
- @Override
- public String getReadableString() {
- return getValue();
- }
- }
+ @Override
+ public TextualComponent clone() throws CloneNotSupportedException {
+ // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
+ return new ComplexTextTypeComponent(getKey(), getValue());
+ }
- /**
- * Internal class used to represent a text component with a nested JSON value.
- * Exception validating done is on keys and values.
- */
- private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
+ @Override
+ public void writeJson(JsonWriter writer) throws IOException {
+ writer.name(getKey());
+ writer.beginObject();
+ for (Map.Entry jsonPair : _value.entrySet()) {
+ writer.name(jsonPair.getKey()).value(jsonPair.getValue());
+ }
+ writer.endObject();
+ }
- private String _key;
- private Map _value;
+ @SuppressWarnings("serial")
+ public Map serialize() {
+ return new java.util.HashMap() {{
+ put("key", getKey());
+ for (Map.Entry valEntry : getValue().entrySet()) {
+ put("value." + valEntry.getKey(), valEntry.getValue());
+ }
+ }};
+ }
- public ComplexTextTypeComponent(String key, Map values) {
- setKey(key);
- setValue(values);
- }
+ public static ComplexTextTypeComponent deserialize(Map map) {
+ String key = null;
+ Map value = new HashMap();
+ for (Map.Entry valEntry : map.entrySet()) {
+ if (valEntry.getKey().equals("key")) {
+ key = (String) valEntry.getValue();
+ } else if (valEntry.getKey().startsWith("value.")) {
+ value.put(((String) valEntry.getKey()).substring(6) /* Strips out the value prefix */, valEntry.getValue().toString());
+ }
+ }
+ return new ComplexTextTypeComponent(key, value);
+ }
- public static ComplexTextTypeComponent deserialize(Map map) {
- String key = null;
- Map value = new HashMap<>();
- for (Map.Entry valEntry : map.entrySet()) {
- if (valEntry.getKey().equals("key")) {
- key = (String) valEntry.getValue();
- } else if (valEntry.getKey().startsWith("value.")) {
- value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, valEntry.getValue().toString());
- }
- }
- return new ComplexTextTypeComponent(key, value);
- }
+ @Override
+ public String getReadableString() {
+ return getKey();
+ }
+ }
- @Override
- public String getKey() {
- return this._key;
- }
+ /**
+ * Create a textual component representing a string literal.
+ * This is the default type of textual component when a single string literal is given to a method.
+ *
+ * @param textValue The text which will be represented.
+ * @return The text component representing the specified literal text.
+ */
+ public static TextualComponent rawText(String textValue) {
+ return new ArbitraryTextTypeComponent("text", textValue);
+ }
- public void setKey(String key) {
- Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified.");
- this._key = key;
- }
- public Map getValue() {
- return this._value;
- }
+ /**
+ * Create a textual component representing a localized string.
+ * The client will see this text component as their localized version of the specified string key, which can be overridden by a resource pack.
+ *
+ * If the specified translation key is not present on the client resource pack, the translation key will be displayed as a string literal to the client.
+ *
+ *
+ * @param translateKey The string key which maps to localized text.
+ * @return The text component representing the specified localized text.
+ */
+ public static TextualComponent localizedText(String translateKey) {
+ return new ArbitraryTextTypeComponent("translate", translateKey);
+ }
- public void setValue(Map value) {
- Preconditions.checkArgument(value != null, "The value must be specified.");
- this._value = value;
- }
+ private static void throwUnsupportedSnapshot() {
+ throw new UnsupportedOperationException("This feature is only supported in snapshot releases.");
+ }
- @Override
- public TextualComponent clone() {
- // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
- return new ComplexTextTypeComponent(getKey(), getValue());
- }
+ /**
+ * Create a textual component representing a scoreboard value.
+ * The client will see their own score for the specified objective as the text represented by this component.
+ *
+ * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.
+ *
+ *
+ * @param scoreboardObjective The name of the objective for which to display the score.
+ * @return The text component representing the specified scoreboard score (for the viewing player), or {@code null} if an error occurs during JSON serialization.
+ */
+ public static TextualComponent objectiveScore(String scoreboardObjective) {
+ return objectiveScore("*", scoreboardObjective);
+ }
- @Override
- public void writeJson(JsonWriter writer) throws IOException {
- writer.name(getKey());
- writer.beginObject();
- for (Map.Entry jsonPair : this._value.entrySet()) {
- writer.name(jsonPair.getKey()).value(jsonPair.getValue());
- }
- writer.endObject();
- }
+ /**
+ * Create a textual component representing a scoreboard value.
+ * The client will see the score of the specified player for the specified objective as the text represented by this component.
+ *
+ * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.
+ *
+ *
+ * @param playerName The name of the player whos score will be shown. If this string represents the single-character sequence "*", the viewing player's score will be displayed.
+ * Standard minecraft selectors (@a, @p, etc) are not supported.
+ * @param scoreboardObjective The name of the objective for which to display the score.
+ * @return The text component representing the specified scoreboard score for the specified player, or {@code null} if an error occurs during JSON serialization.
+ */
+ public static TextualComponent objectiveScore(String playerName, String scoreboardObjective) {
+ throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE OVERLOADS documentation accordingly
- @Override
- @SuppressWarnings("serial")
- public Map serialize() {
- return new HashMap() {
- {
- put("key", getKey());
- for (Map.Entry valEntry : getValue().entrySet()) {
- put("value." + valEntry.getKey(), valEntry.getValue());
- }
- }
- };
- }
+ return new ComplexTextTypeComponent("score", ImmutableMap.builder()
+ .put("name", playerName)
+ .put("objective", scoreboardObjective)
+ .build());
+ }
- @Override
- public String getReadableString() {
- return getKey();
- }
- }
+ /**
+ * Create a textual component representing a player name, retrievable by using a standard minecraft selector.
+ * The client will see the players or entities captured by the specified selector as the text represented by this component.
+ *
+ * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.
+ *
+ *
+ * @param selector The minecraft player or entity selector which will capture the entities whose string representations will be displayed in the place of this text component.
+ * @return The text component representing the name of the entities captured by the selector.
+ */
+ public static TextualComponent selector(String selector) {
+ throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE OVERLOADS documentation accordingly
+
+ return new ArbitraryTextTypeComponent("selector", selector);
+ }
}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java
index bde42e9fc..3abd55d98 100644
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java
@@ -5,6 +5,8 @@ import com.intellectualcrafters.plot.generator.GeneratorWrapper;
import com.intellectualcrafters.plot.generator.HybridGen;
import com.intellectualcrafters.plot.generator.IndependentPlotGenerator;
import com.intellectualcrafters.plot.object.ChunkLoc;
+import com.intellectualcrafters.plot.object.ChunkWrapper;
+import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotManager;
@@ -12,25 +14,26 @@ import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.object.SetupObject;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil;
-import com.intellectualcrafters.plot.util.PlotChunk;
-import com.intellectualcrafters.plot.util.SetQueue;
+import com.intellectualcrafters.plot.util.MathMan;
+import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
+import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
+import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.block.GenChunk;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Random;
+import java.util.Set;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Random;
-import java.util.Set;
-
public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper {
- private final PlotChunk chunkSetter;
+ private final GenChunk chunkSetter;
private final PseudoRandom random = new PseudoRandom();
private final IndependentPlotGenerator plotGenerator;
private final List populators = new ArrayList<>();
@@ -46,14 +49,20 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
this.plotGenerator = generator;
this.platformGenerator = this;
this.populators.add(new BlockPopulator() {
+
+ private LocalBlockQueue queue;
+
@Override
public void populate(World world, Random r, Chunk c) {
+ if (queue == null) {
+ queue = GlobalBlockQueue.IMP.getNewQueue(world.getName(), false);
+ }
ChunkLoc loc = new ChunkLoc(c.getX(), c.getZ());
byte[][] resultData;
if (!BukkitPlotGenerator.this.dataMap.containsKey(loc)) {
- GenChunk result = (GenChunk) BukkitPlotGenerator.this.chunkSetter;
+ GenChunk result = BukkitPlotGenerator.this.chunkSetter;
// Set the chunk location
- result.setChunkWrapper(SetQueue.IMP.new ChunkWrapper(world.getName(), loc.x, loc.z));
+ result.setChunk(c);
// Set the result data
result.result = new short[16][];
result.result_data = new byte[16][];
@@ -81,10 +90,10 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
}
BukkitPlotGenerator.this.random.state = c.getX() << 16 | c.getZ() & 0xFFFF;
PlotArea area = PS.get().getPlotArea(world.getName(), null);
- SetQueue.ChunkWrapper wrap = SetQueue.IMP.new ChunkWrapper(area.worldname, c.getX(), c.getZ());
- PlotChunk> chunk = SetQueue.IMP.queue.getChunk(wrap);
+ ChunkWrapper wrap = new ChunkWrapper(area.worldname, c.getX(), c.getZ());
+ ScopedLocalBlockQueue chunk = queue.getForChunk(wrap.x, wrap.z);
if (BukkitPlotGenerator.this.plotGenerator.populateChunk(chunk, area, BukkitPlotGenerator.this.random)) {
- chunk.addToQueue();
+ queue.flush();
}
}
});
@@ -123,13 +132,16 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
}
@Override
- public void generateChunk(final PlotChunk> result, PlotArea settings, PseudoRandom random) {
+ public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings, PseudoRandom random) {
World w = BukkitUtil.getWorld(world);
- Random r = new Random(result.getChunkWrapper().hashCode());
+ Location min = result.getMin();
+ int cx = min.getX() >> 4;
+ int cz = min.getZ() >> 4;
+ Random r = new Random(MathMan.pair((short) cx, (short) cz));
BiomeGrid grid = new BiomeGrid() {
@Override
public void setBiome(int x, int z, Biome biome) {
- result.setBiome(x, z, biome.ordinal());
+ result.setBiome(x, z, biome.name());
}
@Override
@@ -139,13 +151,13 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
};
try {
// ChunkData will spill a bit
- ChunkData data = cg.generateChunkData(w, r, result.getX(), result.getZ(), grid);
+ ChunkData data = cg.generateChunkData(w, r, cx, cz, grid);
if (data != null) {
return;
}
} catch (Throwable ignored) {}
// Populator spillage
- short[][] tmp = cg.generateExtBlockSections(w, r, result.getX(), result.getZ(), grid);
+ short[][] tmp = cg.generateExtBlockSections(w, r, cx, cz, grid);
if (tmp != null) {
for (int i = 0; i < tmp.length; i++) {
short[] section = tmp[i];
@@ -170,11 +182,11 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
}
}
for (BlockPopulator populator : cg.getDefaultPopulators(w)) {
- populator.populate(w, r, (Chunk) result.getChunk());
+ populator.populate(w, r, w.getChunkAt(cx, cz));
}
}
};
- this.chunkSetter = new GenChunk(null, SetQueue.IMP.new ChunkWrapper(world, 0, 0));
+ this.chunkSetter = new GenChunk(null, new ChunkWrapper(world, 0, 0));
if (cg != null) {
this.populators.addAll(cg.getDefaultPopulators(BukkitUtil.getWorld(world)));
}
@@ -245,7 +257,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
public ChunkData generateChunkData(World world, Random random, int cx, int cz, BiomeGrid grid) {
GenChunk result = (GenChunk) this.chunkSetter;
// Set the chunk location
- result.setChunkWrapper(SetQueue.IMP.new ChunkWrapper(world.getName(), cx, cz));
+ result.setChunk(new ChunkWrapper(world.getName(), cx, cz));
// Set the result data
result.cd = createChunkData(world);
result.grid = grid;
@@ -266,7 +278,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
return result.cd;
}
- public void generate(World world, int cx, int cz, PlotChunk> result) {
+ public void generate(World world, int cx, int cz, ScopedLocalBlockQueue result) {
// Load if improperly loaded
if (!this.loaded) {
String name = world.getName();
@@ -293,7 +305,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
public short[][] generateExtBlockSections(World world, Random r, int cx, int cz, BiomeGrid grid) {
GenChunk result = (GenChunk) this.chunkSetter;
// Set the chunk location
- result.setChunkWrapper(SetQueue.IMP.new ChunkWrapper(world.getName(), cx, cz));
+ result.setChunk(new ChunkWrapper(world.getName(), cx, cz));
// Set the result data
result.result = new short[16][];
result.result_data = new byte[16][];
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java
index 7673dcf21..3e7c226f5 100644
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java
@@ -1,6 +1,7 @@
package com.plotsquared.bukkit.util;
import com.intellectualcrafters.plot.config.C;
+import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.PlotMessage;
import com.intellectualcrafters.plot.object.PlotPlayer;
@@ -45,7 +46,7 @@ public class BukkitChatManager extends ChatManager {
@Override
public void send(PlotMessage plotMessage, PlotPlayer player) {
- if (player instanceof ConsolePlayer) {
+ if (player instanceof ConsolePlayer || !Settings.Chat.INTERACTIVE) {
player.sendMessage(plotMessage.$(this).toOldMessageFormat());
} else {
plotMessage.$(this).send(((BukkitPlayer) player).player);
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java
index d4e71f680..d20b0174a 100644
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java
@@ -9,17 +9,22 @@ import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.PlotLoc;
-import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.ChunkManager;
-import com.intellectualcrafters.plot.util.PlotChunk;
-import com.intellectualcrafters.plot.util.SetQueue;
-import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
-import com.intellectualcrafters.plot.util.UUIDHandler;
-import com.intellectualcrafters.plot.util.WorldUtil;
+import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
+import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
+import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue;
import com.plotsquared.bukkit.object.entity.EntityWrapper;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.DyeColor;
@@ -52,16 +57,6 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
public class BukkitChunkManager extends ChunkManager {
public static boolean isIn(RegionWrapper region, int x, int z) {
@@ -91,6 +86,9 @@ public class BukkitChunkManager extends ChunkManager {
String worldName1 = world1.getName();
String worldName2 = world2.getName();
+ LocalBlockQueue queue1 = GlobalBlockQueue.IMP.getNewQueue(worldName1, false);
+ LocalBlockQueue queue2 = GlobalBlockQueue.IMP.getNewQueue(worldName2, false);
+
for (int x = Math.max(r1.minX, sx); x <= Math.min(r1.maxX, sx + 15); x++) {
for (int z = Math.max(r1.minZ, sz); z <= Math.min(r1.maxZ, sz + 15); z++) {
map.saveBlocks(world1, 256, sx, sz, relX, relZ, false);
@@ -105,24 +103,26 @@ public class BukkitChunkManager extends ChunkManager {
byte data2 = block2.getData();
if (id1 == 0) {
if (id2 != 0) {
- SetQueue.IMP.setBlock(worldName1, x, y, z, (short) id2, data2);
- SetQueue.IMP.setBlock(worldName2, xx, y, zz, (short) 0, (byte) 0);
+ queue1.setBlock(x, y, z, (short) id2, data2);
+ queue2.setBlock(xx, y, zz, (short) 0, (byte) 0);
}
} else if (id2 == 0) {
- SetQueue.IMP.setBlock(worldName1, x, y, z, (short) 0, (byte) 0);
- SetQueue.IMP.setBlock(worldName2, xx, y, zz, (short) id1, data1);
+ queue1.setBlock(x, y, z, (short) 0, (byte) 0);
+ queue2.setBlock(xx, y, zz, (short) id1, data1);
} else if (id1 == id2) {
if (data1 != data2) {
block1.setData(data2);
block2.setData(data1);
}
} else {
- SetQueue.IMP.setBlock(worldName1, x, y, z, (short) id2, data2);
- SetQueue.IMP.setBlock(worldName2, xx, y, zz, (short) id1, data1);
+ queue1.setBlock(x, y, z, (short) id2, data2);
+ queue2.setBlock(xx, y, zz, (short) id1, data1);
}
}
}
}
+ queue1.enqueue();
+ queue2.enqueue();
return map;
}
@@ -138,22 +138,6 @@ public class BukkitChunkManager extends ChunkManager {
return chunks;
}
- @Override
- public void regenerateChunk(String world, ChunkLoc loc) {
- World worldObj = Bukkit.getWorld(world);
- worldObj.regenerateChunk(loc.x, loc.z);
- SetQueue.IMP.queue.sendChunk(world, Collections.singletonList(loc));
- for (Entry entry : UUIDHandler.getPlayers().entrySet()) {
- PlotPlayer pp = entry.getValue();
- Location pLoc = pp.getLocation();
- if (!StringMan.isEqual(world, pLoc.getWorld()) || !pLoc.getChunkLoc().equals(loc)) {
- continue;
- }
- pLoc.setY(WorldUtil.IMP.getHighestBlock(world, pLoc.getX(), pLoc.getZ()));
- pp.teleport(pLoc);
- }
- }
-
@Override
public boolean copyRegion(Location pos1, Location pos2, Location newPos, final Runnable whenDone) {
final int relX = newPos.getX() - pos1.getX();
@@ -166,6 +150,7 @@ public class BukkitChunkManager extends ChunkManager {
final String newWorldName = newWorld.getName();
List chunks = new ArrayList<>();
final ContentMap map = new ContentMap();
+ final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(newWorldName, false);
ChunkManager.chunkTask(pos1, pos2, new RunnableVal() {
@Override
public void run(int[] value) {
@@ -193,11 +178,12 @@ public class BukkitChunkManager extends ChunkManager {
for (int y = 0; y < blocks.length; y++) {
PlotBlock block = blocks[y];
if (block != null) {
- SetQueue.IMP.setBlock(newWorldName, loc.x, y, loc.z, block);
+ queue.setBlock(loc.x, y, loc.z, block);
}
}
}
- SetQueue.IMP.addTask(new Runnable() {
+ queue.enqueue();
+ GlobalBlockQueue.IMP.addTask(new Runnable() {
@Override
public void run() {
map.restoreBlocks(newWorld, 0, 0);
@@ -247,12 +233,13 @@ public class BukkitChunkManager extends ChunkManager {
if (!chunkObj.load(false)) {
continue;
}
+ final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false);
RegionWrapper currentPlotClear = new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) {
AugmentedUtils.bypass(ignoreAugment, new Runnable() {
@Override
public void run() {
- regenerateChunk(world, chunk);
+ queue.regenChunkSafe(chunk.x, chunk.z);
}
});
continue;
@@ -320,13 +307,12 @@ public class BukkitChunkManager extends ChunkManager {
AugmentedUtils.bypass(ignoreAugment, new Runnable() {
@Override
public void run() {
- setChunkInPlotArea(null, new RunnableVal>() {
+ setChunkInPlotArea(null, new RunnableVal() {
@Override
- public void run(PlotChunk> value) {
- int cx = value.getX();
- int cz = value.getZ();
- int bx = cx << 4;
- int bz = cz << 4;
+ public void run(ScopedLocalBlockQueue value) {
+ Location min = value.getMin();
+ int bx = min.getX();
+ int bz = min.getZ();
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
PlotLoc loc = new PlotLoc(bx + x, bz + z);
@@ -424,7 +410,7 @@ public class BukkitChunkManager extends ChunkManager {
maps.add(swapChunk(world1, world2, chunk1, chunk2, region1, region2));
}
}
- SetQueue.IMP.addTask(new Runnable() {
+ GlobalBlockQueue.IMP.addTask(new Runnable() {
@Override
public void run() {
for (ContentMap map : maps) {
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java
index c336347b1..c3f2dd26c 100644
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java
@@ -2,7 +2,6 @@ package com.plotsquared.bukkit.util;
import com.intellectualcrafters.plot.generator.HybridUtils;
import com.intellectualcrafters.plot.object.Location;
-import com.intellectualcrafters.plot.util.expiry.PlotAnalysis;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.object.RunnableVal;
@@ -10,19 +9,20 @@ import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.TaskManager;
+import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
+import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
+import com.intellectualcrafters.plot.util.expiry.PlotAnalysis;
+import java.util.HashSet;
+import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Biome;
-import org.bukkit.block.Block;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.generator.ChunkGenerator.BiomeGrid;
import org.bukkit.material.Directional;
import org.bukkit.material.MaterialData;
-import java.util.HashSet;
-import java.util.Random;
-
public class BukkitHybridUtils extends HybridUtils {
@Override
@@ -42,6 +42,7 @@ public class BukkitHybridUtils extends HybridUtils {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
+ final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false);
final World worldObj = Bukkit.getWorld(world);
final ChunkGenerator gen = worldObj.getGenerator();
if (gen == null) {
@@ -254,10 +255,10 @@ public class BukkitHybridUtils extends HybridUtils {
for (int z = minZ; z <= maxZ; z++) {
int zz = cbz + z;
for (int y = 0; y < 256; y++) {
- Block block = worldObj.getBlockAt(xx, y, zz);
+ PlotBlock block = queue.getBlock(xx, y, zz);
int xr = xb + x;
int zr = zb + z;
- newBlocks[y][xr][zr] = (short) block.getTypeId();
+ newBlocks[y][xr][zr] = block.id;
}
}
}
@@ -272,50 +273,4 @@ public class BukkitHybridUtils extends HybridUtils {
}
});
}
-
- @Override
- public int checkModified(String worldName, int x1, int x2, int y1, int y2, int z1, int z2,
- PlotBlock[] blocks) {
- World world = BukkitUtil.getWorld(worldName);
- int count = 0;
- for (int y = y1; y <= y2; y++) {
- for (int x = x1; x <= x2; x++) {
- for (int z = z1; z <= z2; z++) {
- Block block = world.getBlockAt(x, y, z);
- int id = block.getTypeId();
- boolean same = false;
- for (PlotBlock p : blocks) {
- if (id == p.id) {
- same = true;
- break;
- }
- }
- if (!same) {
- count++;
- }
- }
- }
- }
- return count;
- }
-
- @Override
- public int get_ey(String worldName, int sx, int ex, int sz, int ez, int sy) {
- World world = BukkitUtil.getWorld(worldName);
- int maxY = world.getMaxHeight();
- int ey = sy;
- for (int x = sx; x <= ex; x++) {
- for (int z = sz; z <= ez; z++) {
- for (int y = sy; y < maxY; y++) {
- if (y > ey) {
- Block block = world.getBlockAt(x, y, z);
- if (!block.getType().equals(Material.AIR)) {
- ey = y;
- }
- }
- }
- }
- }
- return ey;
- }
}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue.java
new file mode 100644
index 000000000..4d1086956
--- /dev/null
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue.java
@@ -0,0 +1,127 @@
+package com.plotsquared.bukkit.util.block;
+
+import com.intellectualcrafters.plot.object.PlotBlock;
+import com.intellectualcrafters.plot.util.MainUtil;
+import com.intellectualcrafters.plot.util.StringMan;
+import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue;
+import org.bukkit.Bukkit;
+import org.bukkit.Chunk;
+import org.bukkit.World;
+import org.bukkit.block.Biome;
+import org.bukkit.block.Block;
+
+public class BukkitLocalQueue extends BasicLocalBlockQueue {
+
+ public BukkitLocalQueue(String world) {
+ super(world);
+ }
+
+ @Override
+ public LocalChunk getLocalChunk(int x, int z) {
+ return (LocalChunk) new BasicLocalChunk(this, x, z) {
+ // Custom stuff?
+ };
+ }
+
+ @Override
+ public void optimize() {
+
+ }
+
+ @Override
+ public PlotBlock getBlock(int x, int y, int z) {
+ World worldObj = Bukkit.getWorld(getWorld());
+ Block block = worldObj.getBlockAt(x, y, z);
+ if (block == null) {
+ return PlotBlock.get(0, 0);
+ }
+ int id = block.getTypeId();
+ if (id == 0) {
+ return PlotBlock.get(0, 0);
+ }
+ return PlotBlock.get(id, block.getData());
+ }
+
+ @Override
+ public void refreshChunk(int x, int z) {
+ World worldObj = Bukkit.getWorld(getWorld());
+ worldObj.refreshChunk(x, z);
+ }
+
+ @Override
+ public void fixChunkLighting(int x, int z) {
+ // Do nothing
+ }
+
+ @Override
+ public final void regenChunk(int x, int z) {
+ World worldObj = Bukkit.getWorld(getWorld());
+ worldObj.regenerateChunk(x, z);
+ }
+
+ @Override
+ public final void setComponents(LocalChunk lc) {
+ setBlocks(lc);
+ setBiomes(lc);
+ }
+
+ public World getBukkitWorld() {
+ return Bukkit.getWorld(getWorld());
+ }
+
+ public Chunk getChunk(int x, int z) {
+ return getBukkitWorld().getChunkAt(x, z);
+ }
+
+ public void setBlocks(LocalChunk lc) {
+ World worldObj = Bukkit.getWorld(getWorld());
+ Chunk chunk = worldObj.getChunkAt(lc.getX(), lc.getZ());
+ chunk.load(true);
+ for (int layer = 0; layer < lc.blocks.length; layer++) {
+ PlotBlock[] blocksLayer = (PlotBlock[]) lc.blocks[layer];
+ if (blocksLayer != null) {
+ for (int j = 0; j < blocksLayer.length; j++) {
+ PlotBlock block = blocksLayer[j];
+ int x = MainUtil.x_loc[layer][j];
+ int y = MainUtil.y_loc[layer][j];
+ int z = MainUtil.y_loc[layer][j];
+ Block existing = chunk.getBlock(x, y, z);
+ int existingId = existing.getTypeId();
+ if (existingId == block.id) {
+ if (existingId == 0) {
+ continue;
+ }
+ if (existing.getData() == block.data) {
+ continue;
+ }
+ }
+ existing.setTypeIdAndData(block.id, block.data, false);
+ }
+ }
+ }
+ }
+
+ public void setBiomes(LocalChunk lc) {
+ if (lc.biomes != null) {
+ World worldObj = Bukkit.getWorld(getWorld());
+ int bx = lc.getX() << 4;
+ int bz = lc.getX() << 4;
+ String last = null;
+ Biome biome = null;
+ for (int x = 0; x < lc.biomes.length; x++) {
+ String[] biomes2 = lc.biomes[x];
+ if (biomes2 != null) {
+ for (int y = 0; y < biomes2.length; y++) {
+ String biomeStr = biomes2[y];
+ if (biomeStr != null) {
+ if (last == null || !StringMan.isEqual(last, biomeStr)) {
+ biome = Biome.valueOf(biomeStr.toUpperCase());
+ }
+ worldObj.setBiome(bx, bz, biome);
+ }
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_7.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_7.java
new file mode 100644
index 000000000..05b611e7c
--- /dev/null
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_7.java
@@ -0,0 +1,130 @@
+package com.plotsquared.bukkit.util.block;
+
+import com.intellectualcrafters.plot.object.ChunkWrapper;
+import com.intellectualcrafters.plot.object.PlotBlock;
+import com.intellectualcrafters.plot.util.MainUtil;
+import com.intellectualcrafters.plot.util.ReflectionUtils;
+import com.intellectualcrafters.plot.util.TaskManager;
+import com.plotsquared.bukkit.util.SendChunk;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import org.bukkit.Bukkit;
+import org.bukkit.Chunk;
+import org.bukkit.World;
+
+
+import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
+
+public class BukkitLocalQueue_1_7 extends BukkitLocalQueue {
+
+ private final ReflectionUtils.RefClass classBlock = getRefClass("{nms}.Block");
+ private final ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
+ private final ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World");
+ private final ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
+ private final ReflectionUtils.RefMethod methodGetHandle;
+ private final ReflectionUtils.RefMethod methodGetChunkAt;
+ private final ReflectionUtils.RefMethod methodA;
+ private final ReflectionUtils.RefMethod methodGetById;
+ private final ReflectionUtils.RefMethod methodInitLighting;
+ private final SendChunk sendChunk;
+
+ private final HashMap toUpdate = new HashMap<>();
+
+ public BukkitLocalQueue_1_7(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
+ super(world);
+ this.methodGetHandle = this.classCraftWorld.getMethod("getHandle");
+ this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class);
+ this.methodA = this.classChunk.getMethod("a", int.class, int.class, int.class, this.classBlock, int.class);
+ this.methodGetById = this.classBlock.getMethod("getById", int.class);
+ this.methodInitLighting = this.classChunk.getMethod("initLighting");
+ this.sendChunk = new SendChunk();
+ TaskManager.runTaskRepeat(new Runnable() {
+ @Override
+ public void run() {
+ if (BukkitLocalQueue_1_7.this.toUpdate.isEmpty()) {
+ return;
+ }
+ int count = 0;
+ ArrayList chunks = new ArrayList<>();
+ Iterator> i = BukkitLocalQueue_1_7.this.toUpdate.entrySet().iterator();
+ while (i.hasNext() && (count < 128)) {
+ chunks.add(i.next().getValue());
+ i.remove();
+ count++;
+ }
+ if (count == 0) {
+ return;
+ }
+ update(chunks);
+ }
+ }, 1);
+ MainUtil.initCache();
+ }
+
+ public void update(Collection chunks) {
+ if (chunks.isEmpty()) {
+ return;
+ }
+ if (!MainUtil.canSendChunk) {
+ for (Chunk chunk : chunks) {
+ chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
+ chunk.unload(true, false);
+ chunk.load();
+ }
+ return;
+ }
+ try {
+ this.sendChunk.sendChunk(chunks);
+ } catch (Throwable e) {
+ e.printStackTrace();
+ MainUtil.canSendChunk = false;
+ }
+ }
+
+ @Override
+ public void fixChunkLighting(int x, int z) {
+ Object c = this.methodGetHandle.of(getChunk(x, z)).call();
+ this.methodInitLighting.of(c).call();
+ }
+
+ @Override
+ public void setBlocks(LocalChunk lc) {
+ Chunk chunk = getChunk(lc.getX(), lc.getZ());
+ chunk.load(true);
+ World world = chunk.getWorld();
+ ChunkWrapper wrapper = new ChunkWrapper(getWorld(), lc.getX(), lc.getZ());
+ if (!this.toUpdate.containsKey(wrapper)) {
+ this.toUpdate.put(wrapper, chunk);
+ }
+ Object w = this.methodGetHandle.of(world).call();
+ Object c = this.methodGetChunkAt.of(w).call(lc.getX(), lc.getZ());
+ for (int i = 0; i < lc.blocks.length; i++) {
+ PlotBlock[] result2 = lc.blocks[i];
+ if (result2 == null) {
+ continue;
+ }
+ for (int j = 0; j < 4096; j++) {
+ int x = MainUtil.x_loc[i][j];
+ int y = MainUtil.y_loc[i][j];
+ int z = MainUtil.z_loc[i][j];
+ PlotBlock newBlock = result2[j];
+ if (newBlock.id == -1) {
+ chunk.getBlock(x, y, z).setData(newBlock.data, false);
+ continue;
+ }
+ Object block = this.methodGetById.call(newBlock.id);
+ this.methodA.of(c).call(x, y, z, block, newBlock.data);
+ }
+ }
+ fixChunkLighting(lc.getX(), lc.getZ());
+ }
+
+ @Override
+ public void refreshChunk(int x, int z) {
+ update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z)));
+ }
+}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8.java
similarity index 74%
rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8.java
rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8.java
index b5cc3cc7d..ed0234e38 100644
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8.java
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8.java
@@ -1,47 +1,44 @@
package com.plotsquared.bukkit.util.block;
-import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
-
-import com.intellectualcrafters.plot.object.ChunkLoc;
+import com.intellectualcrafters.plot.object.ChunkWrapper;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
-import com.intellectualcrafters.plot.util.PlotChunk;
-import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
-import com.intellectualcrafters.plot.util.ReflectionUtils.RefConstructor;
-import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
-import com.intellectualcrafters.plot.util.SetQueue;
-import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
+import com.intellectualcrafters.plot.util.ReflectionUtils;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.util.SendChunk;
-import org.bukkit.Chunk;
-import org.bukkit.World;
-import org.bukkit.block.Biome;
-import org.bukkit.block.Block;
-
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
-import java.util.Map.Entry;
+import java.util.Map;
+import org.bukkit.Bukkit;
+import org.bukkit.Chunk;
+import org.bukkit.World;
+import org.bukkit.block.Block;
-public class FastQueue_1_8 extends SlowQueue {
- private final RefMethod methodInitLighting;
- private final RefClass classBlock = getRefClass("{nms}.Block");
- private final RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
- private final RefClass classIBlockData = getRefClass("{nms}.IBlockData");
- private final RefClass classChunk = getRefClass("{nms}.Chunk");
- private final RefClass classWorld = getRefClass("{nms}.World");
- private final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
+import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
+
+public class BukkitLocalQueue_1_8 extends BukkitLocalQueue {
+
+ private final ReflectionUtils.RefMethod methodInitLighting;
+ private final ReflectionUtils.RefClass classBlock = getRefClass("{nms}.Block");
+ private final ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
+ private final ReflectionUtils.RefClass classIBlockData = getRefClass("{nms}.IBlockData");
+ private final ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
+ private final ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World");
+ private final ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
private final HashMap toUpdate = new HashMap<>();
- private final RefMethod methodGetHandle;
- private final RefMethod methodGetChunkAt;
- private final RefMethod methodA;
- private final RefMethod methodGetByCombinedId;
- private final RefConstructor constructorBlockPosition;
+ private final ReflectionUtils.RefMethod methodGetHandle;
+ private final ReflectionUtils.RefMethod methodGetChunkAt;
+ private final ReflectionUtils.RefMethod methodA;
+ private final ReflectionUtils.RefMethod methodGetByCombinedId;
+ private final ReflectionUtils.RefConstructor constructorBlockPosition;
private final SendChunk sendChunk;
- public FastQueue_1_8() throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
+ public BukkitLocalQueue_1_8(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
+ super(world);
this.methodInitLighting = this.classChunk.getMethod("initLighting");
this.constructorBlockPosition = this.classBlockPosition.getConstructor(int.class, int.class, int.class);
this.methodGetByCombinedId = this.classBlock.getMethod("getByCombinedId", int.class);
@@ -52,12 +49,12 @@ public class FastQueue_1_8 extends SlowQueue {
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
- if (FastQueue_1_8.this.toUpdate.isEmpty()) {
+ if (BukkitLocalQueue_1_8.this.toUpdate.isEmpty()) {
return;
}
int count = 0;
ArrayList chunks = new ArrayList<>();
- Iterator> i = FastQueue_1_8.this.toUpdate.entrySet().iterator();
+ Iterator> i = BukkitLocalQueue_1_8.this.toUpdate.entrySet().iterator();
while (i.hasNext() && count < 128) {
chunks.add(i.next().getValue());
i.remove();
@@ -72,44 +69,25 @@ public class FastQueue_1_8 extends SlowQueue {
MainUtil.initCache();
}
- public void update(Collection chunks) {
- if (chunks.isEmpty()) {
- return;
- }
- if (!MainUtil.canSendChunk) {
- for (Chunk chunk : chunks) {
- chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
- chunk.unload(true, false);
- chunk.load();
- }
- return;
- }
- try {
- this.sendChunk.sendChunk(chunks);
- } catch (Throwable e) {
- e.printStackTrace();
- MainUtil.canSendChunk = false;
- }
+ @Override
+ public void fixChunkLighting(int x, int z) {
+ Object c = this.methodGetHandle.of(getChunk(x, z)).call();
+ this.methodInitLighting.of(c).call();
}
- /**
- * This should be overridden by any specialized queues.
- * @param plotChunk
- */
@Override
- public void execute(PlotChunk plotChunk) {
- SlowChunk sc = (SlowChunk) plotChunk;
- Chunk chunk = plotChunk.getChunk();
- ChunkWrapper wrapper = plotChunk.getChunkWrapper();
+ public void setBlocks(LocalChunk lc) {
+ Chunk chunk = getChunk(lc.getX(), lc.getZ());
+ chunk.load(true);
+ World world = chunk.getWorld();
+ ChunkWrapper wrapper = new ChunkWrapper(getWorld(), lc.getX(), lc.getZ());
if (!this.toUpdate.containsKey(wrapper)) {
this.toUpdate.put(wrapper, chunk);
}
- chunk.load(true);
- World world = chunk.getWorld();
Object w = this.methodGetHandle.of(world).call();
- Object c = this.methodGetChunkAt.of(w).call(wrapper.x, wrapper.z);
- for (int i = 0; i < sc.result.length; i++) {
- PlotBlock[] result2 = sc.result[i];
+ Object c = this.methodGetChunkAt.of(w).call(lc.getX(), lc.getZ());
+ for (int i = 0; i < lc.blocks.length; i++) {
+ PlotBlock[] result2 = lc.blocks[i];
if (result2 == null) {
continue;
}
@@ -329,55 +307,31 @@ public class FastQueue_1_8 extends SlowQueue {
this.methodA.of(chunk).call(pos, combined);
}
}
- int[][] biomes = sc.biomes;
- Biome[] values = Biome.values();
- if (biomes != null) {
- for (int x = 0; x < 16; x++) {
- int[] array = biomes[x];
- if (array == null) {
- continue;
- }
- for (int z = 0; z < 16; z++) {
- int biome = array[z];
- if (biome == 0) {
- continue;
- }
- chunk.getBlock(x, 0, z).setBiome(values[biome]);
- }
+ fixChunkLighting(lc.getX(), lc.getZ());
+ }
+
+ public void update(Collection chunks) {
+ if (chunks.isEmpty()) {
+ return;
+ }
+ if (!MainUtil.canSendChunk) {
+ for (Chunk chunk : chunks) {
+ chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
+ chunk.unload(true, false);
+ chunk.load();
}
+ return;
+ }
+ try {
+ this.sendChunk.sendChunk(chunks);
+ } catch (Throwable e) {
+ e.printStackTrace();
+ MainUtil.canSendChunk = false;
}
}
- /**
- * This should be overridden by any specialized queues.
- * @param wrap
- */
@Override
- public PlotChunk getChunk(ChunkWrapper wrap) {
- return new SlowChunk(wrap);
- }
-
- /**
- * This should be overridden by any specialized queues.
- * @param fixAll
- */
- @Override
- public boolean fixLighting(PlotChunk chunk, boolean fixAll) {
- Object c = this.methodGetHandle.of(chunk.getChunk()).call();
- this.methodInitLighting.of(c).call();
- return true;
- }
-
- /**
- * This should be overridden by any specialized queues.
- * @param locations
- */
- @Override
- public void sendChunk(String world, Collection locations) {
- for (ChunkLoc loc : locations) {
- ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z);
- this.toUpdate.remove(wrapper);
- }
- this.sendChunk.sendChunk(world, locations);
+ public void refreshChunk(int x, int z) {
+ update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z)));
}
}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8_3.java
similarity index 61%
rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java
rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8_3.java
index e04449c35..342d289c8 100644
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8_3.java
@@ -1,66 +1,62 @@
package com.plotsquared.bukkit.util.block;
-import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
-
import com.intellectualcrafters.plot.object.ChunkLoc;
+import com.intellectualcrafters.plot.object.ChunkWrapper;
import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil;
-import com.intellectualcrafters.plot.util.PlotChunk;
-import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
-import com.intellectualcrafters.plot.util.ReflectionUtils.RefConstructor;
-import com.intellectualcrafters.plot.util.ReflectionUtils.RefField;
-import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
-import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod.RefExecutor;
-import com.intellectualcrafters.plot.util.SetQueue;
-import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
+import com.intellectualcrafters.plot.util.ReflectionUtils;
import com.intellectualcrafters.plot.util.TaskManager;
+import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue;
import com.plotsquared.bukkit.util.SendChunk;
-import org.bukkit.Chunk;
-import org.bukkit.Material;
-import org.bukkit.World;
-import org.bukkit.World.Environment;
-import org.bukkit.block.Biome;
-
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
-import java.util.Map.Entry;
+import java.util.Map;
import java.util.Set;
+import org.bukkit.Bukkit;
+import org.bukkit.Chunk;
+import org.bukkit.Material;
+import org.bukkit.World;
-public class FastQueue_1_8_3 extends SlowQueue {
+
+import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
+
+public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue {
private final SendChunk sendChunk;
private final HashMap toUpdate = new HashMap<>();
- private final RefMethod methodGetHandleChunk;
- private final RefMethod methodGetHandleWorld;
- private final RefMethod methodInitLighting;
- private final RefConstructor classBlockPositionConstructor;
- private final RefConstructor classChunkSectionConstructor;
- private final RefMethod methodX;
- private final RefMethod methodAreNeighborsLoaded;
- private final RefField fieldSections;
- private final RefField fieldWorld;
- private final RefMethod methodGetIdArray;
- private final RefMethod methodGetWorld;
- private final RefField tileEntityListTick;
+ private final ReflectionUtils.RefMethod methodGetHandleChunk;
+ private final ReflectionUtils.RefMethod methodGetHandleWorld;
+ private final ReflectionUtils.RefMethod methodInitLighting;
+ private final ReflectionUtils.RefConstructor classBlockPositionConstructor;
+ private final ReflectionUtils.RefConstructor classChunkSectionConstructor;
+ private final ReflectionUtils.RefMethod methodX;
+ private final ReflectionUtils.RefMethod methodAreNeighborsLoaded;
+ private final ReflectionUtils.RefField fieldSections;
+ private final ReflectionUtils.RefField fieldWorld;
+ private final ReflectionUtils.RefMethod methodGetIdArray;
+ private final ReflectionUtils.RefMethod methodGetWorld;
+ private final ReflectionUtils.RefField tileEntityListTick;
- public FastQueue_1_8_3() throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
- RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
- RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
+ public BukkitLocalQueue_1_8_3(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
+ super(world);
+ ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
+ ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
- RefClass classChunk = getRefClass("{nms}.Chunk");
+ ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
this.methodInitLighting = classChunk.getMethod("initLighting");
- RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
+ ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class);
- RefClass classWorld = getRefClass("{nms}.World");
+ ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World");
this.methodX = classWorld.getMethod("x", classBlockPosition.getRealClass());
this.fieldSections = classChunk.getField("sections");
this.fieldWorld = classChunk.getField("world");
- RefClass classChunkSection = getRefClass("{nms}.ChunkSection");
+ ReflectionUtils.RefClass classChunkSection = getRefClass("{nms}.ChunkSection");
this.methodGetIdArray = classChunkSection.getMethod("getIdArray");
this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class);
this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class);
@@ -71,12 +67,12 @@ public class FastQueue_1_8_3 extends SlowQueue {
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
- if (FastQueue_1_8_3.this.toUpdate.isEmpty()) {
+ if (BukkitLocalQueue_1_8_3.this.toUpdate.isEmpty()) {
return;
}
int count = 0;
ArrayList chunks = new ArrayList<>();
- Iterator> i = FastQueue_1_8_3.this.toUpdate.entrySet().iterator();
+ Iterator> i = BukkitLocalQueue_1_8_3.this.toUpdate.entrySet().iterator();
while (i.hasNext() && count < 128) {
chunks.add(i.next().getValue());
i.remove();
@@ -91,42 +87,184 @@ public class FastQueue_1_8_3 extends SlowQueue {
MainUtil.initCache();
}
- public void update(Collection chunks) {
- if (chunks.isEmpty()) {
- return;
+ @Override
+ public LocalChunk getLocalChunk(int x, int z) {
+ return new CharLocalChunk_1_8_3(this, x, z);
+ }
+
+ public class CharLocalChunk_1_8_3 extends CharLocalChunk {
+ public short[] count;
+ public short[] air;
+ public short[] relight;
+
+ public CharLocalChunk_1_8_3(BasicLocalBlockQueue parent, int x, int z) {
+ super(parent, x, z);
+ this.count = new short[16];
+ this.air = new short[16];
+ this.relight = new short[16];
}
- if (!MainUtil.canSendChunk) {
- for (Chunk chunk : chunks) {
- chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
- chunk.unload(true, false);
- chunk.load();
+
+ @Override
+ public void setBlock(int x, int y, int z, int id, int data) {
+ int i = MainUtil.CACHE_I[y][x][z];
+ int j = MainUtil.CACHE_J[y][x][z];
+ char[] vs = this.blocks[i];
+ if (vs == null) {
+ vs = this.blocks[i] = new char[4096];
+ this.count[i]++;
+ } else if (vs[j] == 0) {
+ this.count[i]++;
+ }
+ switch (id) {
+ case 0:
+ this.air[i]++;
+ vs[j] = (char) 1;
+ return;
+ case 10:
+ case 11:
+ case 39:
+ case 40:
+ case 51:
+ case 74:
+ case 89:
+ case 122:
+ case 124:
+ case 138:
+ case 169:
+ this.relight[i]++;
+ case 2:
+ case 4:
+ case 13:
+ case 14:
+ case 15:
+ case 20:
+ case 21:
+ case 22:
+ case 30:
+ case 32:
+ case 37:
+ case 41:
+ case 42:
+ case 45:
+ case 46:
+ case 47:
+ case 48:
+ case 49:
+ case 55:
+ case 56:
+ case 57:
+ case 58:
+ case 60:
+ case 7:
+ case 8:
+ case 9:
+ case 73:
+ case 78:
+ case 79:
+ case 80:
+ case 81:
+ case 82:
+ case 83:
+ case 85:
+ case 87:
+ case 88:
+ case 101:
+ case 102:
+ case 103:
+ case 110:
+ case 112:
+ case 113:
+ case 121:
+ case 129:
+ case 133:
+ case 165:
+ case 166:
+ case 170:
+ case 172:
+ case 173:
+ case 174:
+ case 181:
+ case 182:
+ case 188:
+ case 189:
+ case 190:
+ case 191:
+ case 192:
+ vs[j] = (char) (id << 4);
+ return;
+ case 130:
+ case 76:
+ case 62:
+ this.relight[i]++;
+ case 54:
+ case 146:
+ case 61:
+ case 65:
+ case 68:
+ case 50:
+ if (data < 2) {
+ data = 2;
+ }
+ default:
+ vs[j] = (char) ((id << 4) + data);
+ return;
}
- return;
}
- try {
- this.sendChunk.sendChunk(chunks);
- } catch (Throwable e) {
- e.printStackTrace();
- MainUtil.canSendChunk = false;
+
+ public char[] getIdArray(int i) {
+ return this.blocks[i];
+ }
+
+ public int getCount(int i) {
+ return this.count[i];
+ }
+
+ public int getAir(int i) {
+ return this.air[i];
+ }
+
+ public void setCount(int i, short value) {
+ this.count[i] = value;
+ }
+
+ public int getRelight(int i) {
+ return this.relight[i];
+ }
+
+ public int getTotalCount() {
+ int total = 0;
+ for (int i = 0; i < 16; i++) {
+ total += this.count[i];
+ }
+ return total;
+ }
+
+ public int getTotalRelight() {
+ if (getTotalCount() == 0) {
+ Arrays.fill(this.count, (short) 1);
+ Arrays.fill(this.relight, Short.MAX_VALUE);
+ return Short.MAX_VALUE;
+ }
+ int total = 0;
+ for (int i = 0; i < 16; i++) {
+ total += this.relight[i];
+ }
+ return total;
}
}
- /**
- * This should be overridden by any specialized queues.
- * @param plotChunk
- */
@Override
- public void execute(PlotChunk plotChunk) {
- FastChunk_1_8_3 fs = (FastChunk_1_8_3) plotChunk;
- Chunk chunk = plotChunk.getChunk();
+ public void setBlocks(LocalChunk lc) {
+ CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc;
+ Chunk chunk = getChunk(lc.getX(), lc.getZ());
+ chunk.load(true);
World world = chunk.getWorld();
- ChunkWrapper wrapper = plotChunk.getChunkWrapper();
+ ChunkWrapper wrapper = new ChunkWrapper(getWorld(), lc.getX(), lc.getZ());
if (!this.toUpdate.containsKey(wrapper)) {
this.toUpdate.put(wrapper, chunk);
}
- chunk.load(true);
try {
- boolean flag = world.getEnvironment() == Environment.NORMAL;
+ boolean flag = world.getEnvironment() == World.Environment.NORMAL;
// Sections
Method getHandle = chunk.getClass().getDeclaredMethod("getHandle");
@@ -147,10 +285,10 @@ public class FastQueue_1_8_3 extends SlowQueue {
// Trim tiles
boolean removed = false;
- Set> entrySet = (Set>) (Set>) tiles.entrySet();
- Iterator> iterator = entrySet.iterator();
+ Set> entrySet = (Set>) (Set>) tiles.entrySet();
+ Iterator> iterator = entrySet.iterator();
while (iterator.hasNext()) {
- Entry, ?> tile = iterator.next();
+ Map.Entry, ?> tile = iterator.next();
Object pos = tile.getKey();
if (getX == null) {
Class extends Object> clazz2 = pos.getClass().getSuperclass();
@@ -222,23 +360,7 @@ public class FastQueue_1_8_3 extends SlowQueue {
} catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) {
e.printStackTrace();
}
- int[][] biomes = fs.biomes;
- Biome[] values = Biome.values();
- if (biomes != null) {
- for (int x = 0; x < 16; x++) {
- int[] array = biomes[x];
- if (array == null) {
- continue;
- }
- for (int z = 0; z < 16; z++) {
- int biome = array[z];
- if (biome == 0) {
- continue;
- }
- chunk.getBlock(x, 0, z).setBiome(values[biome]);
- }
- }
- }
+ fixLighting(chunk, fs, true);
}
public Object newChunkSection(int i, boolean flag, char[] ids) throws ReflectiveOperationException {
@@ -249,24 +371,14 @@ public class FastQueue_1_8_3 extends SlowQueue {
return (char[]) this.methodGetIdArray.of(obj).call();
}
- /**
- * This should be overridden by any specialized queues.
- * @param wrap
- */
@Override
- public PlotChunk getChunk(ChunkWrapper wrap) {
- return new FastChunk_1_8_3(wrap);
+ public void fixChunkLighting(int x, int z) {
+ Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
+ this.methodInitLighting.of(c).call();
}
- /**
- * This should be overridden by any specialized queues
- * @param plotChunk
- */
- @Override
- public boolean fixLighting(PlotChunk plotChunk, boolean fixAll) {
+ public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) {
try {
- FastChunk_1_8_3 bc = (FastChunk_1_8_3) plotChunk;
- Chunk chunk = bc.getChunk();
if (!chunk.isLoaded()) {
chunk.load(false);
} else {
@@ -279,7 +391,7 @@ public class FastQueue_1_8_3 extends SlowQueue {
if (fixAll && !(boolean) this.methodAreNeighborsLoaded.of(c).call(1)) {
World world = chunk.getWorld();
- ChunkWrapper wrapper = bc.getChunkWrapper();
+ ChunkWrapper wrapper = new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ());
for (int x = wrapper.x - 1; x <= wrapper.x + 1; x++) {
for (int z = wrapper.z - 1; z <= wrapper.z + 1; z++) {
if (x != 0 && z != 0) {
@@ -310,7 +422,7 @@ public class FastQueue_1_8_3 extends SlowQueue {
int X = chunk.getX() << 4;
int Z = chunk.getZ() << 4;
- RefExecutor relight = this.methodX.of(w);
+ ReflectionUtils.RefMethod.RefExecutor relight = this.methodX.of(w);
for (int j = 0; j < sections.length; j++) {
Object section = sections[j];
if (section == null) {
@@ -398,17 +510,28 @@ public class FastQueue_1_8_3 extends SlowQueue {
return array[j] >> 4;
}
- /**
- * This should be overridden by any specialized queues.
- * @param world
- * @param locations
- */
- @Override
- public void sendChunk(String world, Collection locations) {
- for (ChunkLoc loc : locations) {
- ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z);
- this.toUpdate.remove(wrapper);
+ public void update(Collection chunks) {
+ if (chunks.isEmpty()) {
+ return;
}
- this.sendChunk.sendChunk(world, locations);
+ if (!MainUtil.canSendChunk) {
+ for (Chunk chunk : chunks) {
+ chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
+ chunk.unload(true, false);
+ chunk.load();
+ }
+ return;
+ }
+ try {
+ this.sendChunk.sendChunk(chunks);
+ } catch (Throwable e) {
+ e.printStackTrace();
+ MainUtil.canSendChunk = false;
+ }
+ }
+
+ @Override
+ public void refreshChunk(int x, int z) {
+ update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z)));
}
}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_9.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_9.java
similarity index 56%
rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_9.java
rename to Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_9.java
index 6b8885772..03ef49963 100644
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_9.java
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_9.java
@@ -1,73 +1,67 @@
package com.plotsquared.bukkit.util.block;
-import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
-
import com.intellectualcrafters.plot.object.ChunkLoc;
+import com.intellectualcrafters.plot.object.ChunkWrapper;
import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil;
-import com.intellectualcrafters.plot.util.PlotChunk;
-import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
-import com.intellectualcrafters.plot.util.ReflectionUtils.RefConstructor;
-import com.intellectualcrafters.plot.util.ReflectionUtils.RefField;
-import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
-import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod.RefExecutor;
-import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
-import com.plotsquared.bukkit.util.BukkitUtil;
-import org.bukkit.Chunk;
-import org.bukkit.Material;
-import org.bukkit.World;
-import org.bukkit.World.Environment;
-import org.bukkit.block.Biome;
-
+import com.intellectualcrafters.plot.util.ReflectionUtils;
+import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
+import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
-import java.util.Map.Entry;
+import java.util.Map;
import java.util.Set;
+import org.bukkit.Chunk;
+import org.bukkit.Material;
+import org.bukkit.World;
-public class FastQueue_1_9 extends SlowQueue {
+
+import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
+
+public class BukkitLocalQueue_1_9 extends BukkitLocalQueue {
private final Object air;
-// private final HashMap toUpdate = new HashMap<>();
- private final RefMethod methodGetHandleChunk;
- private final RefMethod methodInitLighting;
- private final RefConstructor classBlockPositionConstructor;
- private final RefConstructor classChunkSectionConstructor;
- private final RefMethod methodW;
- private final RefMethod methodAreNeighborsLoaded;
- private final RefField fieldSections;
- private final RefField fieldWorld;
- private final RefMethod methodGetBlocks;
- private final RefMethod methodGetType;
- private final RefMethod methodSetType;
- private final RefMethod methodGetCombinedId;
- private final RefMethod methodGetByCombinedId;
- private final RefMethod methodGetWorld;
+ // private final HashMap toUpdate = new HashMap<>();
+ private final ReflectionUtils.RefMethod methodGetHandleChunk;
+ private final ReflectionUtils.RefMethod methodInitLighting;
+ private final ReflectionUtils.RefConstructor classBlockPositionConstructor;
+ private final ReflectionUtils.RefConstructor classChunkSectionConstructor;
+ private final ReflectionUtils.RefMethod methodW;
+ private final ReflectionUtils.RefMethod methodAreNeighborsLoaded;
+ private final ReflectionUtils.RefField fieldSections;
+ private final ReflectionUtils.RefField fieldWorld;
+ private final ReflectionUtils.RefMethod methodGetBlocks;
+ private final ReflectionUtils.RefMethod methodGetType;
+ private final ReflectionUtils.RefMethod methodSetType;
+ private final ReflectionUtils.RefMethod methodGetCombinedId;
+ private final ReflectionUtils.RefMethod methodGetByCombinedId;
+ private final ReflectionUtils.RefMethod methodGetWorld;
- private final RefField tileEntityListTick;
+ private final ReflectionUtils.RefField tileEntityListTick;
-
- public FastQueue_1_9() throws NoSuchFieldException, NoSuchMethodException, ClassNotFoundException {
- RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
+ public BukkitLocalQueue_1_9(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
+ super(world);
+ ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
- RefClass classChunk = getRefClass("{nms}.Chunk");
+ ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
this.methodInitLighting = classChunk.getMethod("initLighting");
- RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
+ ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class);
- RefClass classWorld = getRefClass("{nms}.World");
+ ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World");
this.tileEntityListTick = classWorld.getField("tileEntityListTick");
this.methodGetWorld = classChunk.getMethod("getWorld");
this.methodW = classWorld.getMethod("w", classBlockPosition.getRealClass());
this.fieldSections = classChunk.getField("sections");
this.fieldWorld = classChunk.getField("world");
- RefClass classBlock = getRefClass("{nms}.Block");
- RefClass classIBlockData = getRefClass("{nms}.IBlockData");
+ ReflectionUtils.RefClass classBlock = getRefClass("{nms}.Block");
+ ReflectionUtils.RefClass classIBlockData = getRefClass("{nms}.IBlockData");
this.methodGetCombinedId = classBlock.getMethod("getCombinedId", classIBlockData.getRealClass());
this.methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class);
- RefClass classChunkSection = getRefClass("{nms}.ChunkSection");
+ ReflectionUtils.RefClass classChunkSection = getRefClass("{nms}.ChunkSection");
this.methodGetBlocks = classChunkSection.getMethod("getBlocks");
this.methodGetType = classChunkSection.getMethod("getType", int.class, int.class, int.class);
this.methodSetType = classChunkSection.getMethod("setType", int.class, int.class, int.class, classIBlockData.getRealClass());
@@ -77,19 +71,180 @@ public class FastQueue_1_9 extends SlowQueue {
MainUtil.initCache();
}
- /**
- * This should be overridden by any specialized queues.
- * @param plotChunk
- */
@Override
- public void execute(PlotChunk plotChunk) {
- final FastChunk_1_9 fs = (FastChunk_1_9) plotChunk;
- Chunk chunk = plotChunk.getChunk();
- World world = chunk.getWorld();
- ChunkWrapper wrapper = plotChunk.getChunkWrapper();
+ public LocalChunk getLocalChunk(int x, int z) {
+ return new CharLocalChunk_1_8_3(this, x, z);
+ }
+
+ public class CharLocalChunk_1_8_3 extends CharLocalChunk {
+ public short[] count;
+ public short[] air;
+ public short[] relight;
+
+ public CharLocalChunk_1_8_3(BasicLocalBlockQueue parent, int x, int z) {
+ super(parent, x, z);
+ this.count = new short[16];
+ this.air = new short[16];
+ this.relight = new short[16];
+ }
+
+ @Override
+ public void setBlock(int x, int y, int z, int id, int data) {
+ int i = MainUtil.CACHE_I[y][x][z];
+ int j = MainUtil.CACHE_J[y][x][z];
+ char[] vs = this.blocks[i];
+ if (vs == null) {
+ vs = this.blocks[i] = new char[4096];
+ this.count[i]++;
+ } else if (vs[j] == 0) {
+ this.count[i]++;
+ }
+ switch (id) {
+ case 0:
+ this.air[i]++;
+ vs[j] = (char) 1;
+ return;
+ case 10:
+ case 11:
+ case 39:
+ case 40:
+ case 51:
+ case 74:
+ case 89:
+ case 122:
+ case 124:
+ case 138:
+ case 169:
+ this.relight[i]++;
+ case 2:
+ case 4:
+ case 13:
+ case 14:
+ case 15:
+ case 20:
+ case 21:
+ case 22:
+ case 30:
+ case 32:
+ case 37:
+ case 41:
+ case 42:
+ case 45:
+ case 46:
+ case 47:
+ case 48:
+ case 49:
+ case 55:
+ case 56:
+ case 57:
+ case 58:
+ case 60:
+ case 7:
+ case 8:
+ case 9:
+ case 73:
+ case 78:
+ case 79:
+ case 80:
+ case 81:
+ case 82:
+ case 83:
+ case 85:
+ case 87:
+ case 88:
+ case 101:
+ case 102:
+ case 103:
+ case 110:
+ case 112:
+ case 113:
+ case 121:
+ case 129:
+ case 133:
+ case 165:
+ case 166:
+ case 170:
+ case 172:
+ case 173:
+ case 174:
+ case 181:
+ case 182:
+ case 188:
+ case 189:
+ case 190:
+ case 191:
+ case 192:
+ vs[j] = (char) (id << 4);
+ return;
+ case 130:
+ case 76:
+ case 62:
+ this.relight[i]++;
+ case 54:
+ case 146:
+ case 61:
+ case 65:
+ case 68:
+ case 50:
+ if (data < 2) {
+ data = 2;
+ }
+ default:
+ vs[j] = (char) ((id << 4) + data);
+ return;
+ }
+ }
+
+ public char[] getIdArray(int i) {
+ return this.blocks[i];
+ }
+
+ public int getCount(int i) {
+ return this.count[i];
+ }
+
+ public int getAir(int i) {
+ return this.air[i];
+ }
+
+ public void setCount(int i, short value) {
+ this.count[i] = value;
+ }
+
+ public int getRelight(int i) {
+ return this.relight[i];
+ }
+
+ public int getTotalCount() {
+ int total = 0;
+ for (int i = 0; i < 16; i++) {
+ total += this.count[i];
+ }
+ return total;
+ }
+
+ public int getTotalRelight() {
+ if (getTotalCount() == 0) {
+ Arrays.fill(this.count, (short) 1);
+ Arrays.fill(this.relight, Short.MAX_VALUE);
+ return Short.MAX_VALUE;
+ }
+ int total = 0;
+ for (int i = 0; i < 16; i++) {
+ total += this.relight[i];
+ }
+ return total;
+ }
+ }
+
+ @Override
+ public void setBlocks(LocalChunk lc) {
+ CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc;
+ Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
+ World world = chunk.getWorld();
try {
- boolean flag = world.getEnvironment() == Environment.NORMAL;
+ boolean flag = world.getEnvironment() == World.Environment.NORMAL;
// Sections
Method getHandle = chunk.getClass().getDeclaredMethod("getHandle");
@@ -109,10 +264,10 @@ public class FastQueue_1_9 extends SlowQueue {
Method zm = null;
// Trim tiles
boolean removed = false;
- Set> entrySet = (Set>) (Set>) tiles.entrySet();
- Iterator> iterator = entrySet.iterator();
+ Set> entrySet = (Set>) (Set>) tiles.entrySet();
+ Iterator> iterator = entrySet.iterator();
while (iterator.hasNext()) {
- Entry, ?> tile = iterator.next();
+ Map.Entry, ?> tile = iterator.next();
Object pos = tile.getKey();
if (xm == null) {
Class> clazz2 = pos.getClass().getSuperclass();
@@ -125,7 +280,7 @@ public class FastQueue_1_9 extends SlowQueue {
int lz = (int) zm.invoke(pos) & 15;
int j = MainUtil.CACHE_I[ly][lx][lz];
int k = MainUtil.CACHE_J[ly][lx][lz];
- int[] array = fs.getIdArray(j);
+ char[] array = fs.getIdArray(j);
if (array == null) {
continue;
}
@@ -150,32 +305,25 @@ public class FastQueue_1_9 extends SlowQueue {
if (fs.getCount(j) == 0) {
continue;
}
- int[] newArray = fs.getIdArray(j);
+ char[] newArray = fs.getIdArray(j);
if (newArray == null) {
continue;
}
Object section = sections[j];
if (section == null || fs.getCount(j) >= 4096) {
- char[] array = new char[4096];
- for (int i = 0; i < newArray.length; i++) {
- int combined = newArray[i];
- int id = combined & 4095;
- int data = combined >> 12;
- array[i] = (char) ((id << 4) + data);
- }
- section = sections[j] = newChunkSection(j << 4, flag, array);
+ section = sections[j] = newChunkSection(j << 4, flag, fs.getIdArray(j));
continue;
}
Object currentArray = getBlocks(section);
- RefExecutor setType = this.methodSetType.of(section);
+ ReflectionUtils.RefMethod.RefExecutor setType = this.methodSetType.of(section);
boolean fill = true;
for (int k = 0; k < newArray.length; k++) {
- int n = newArray[k];
+ char n = newArray[k];
switch (n) {
case 0:
fill = false;
continue;
- case -1: {
+ case 1: {
fill = false;
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
@@ -187,7 +335,9 @@ public class FastQueue_1_9 extends SlowQueue {
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
- Object iBlock = this.methodGetByCombinedId.call((int) n);
+ int id = n >> 4;
+ int data = n & 15;
+ Object iBlock = this.methodGetByCombinedId.call((int) (id & 0xFFF) + (data << 12));
setType.call(x, y & 15, z, iBlock);
}
}
@@ -199,24 +349,8 @@ public class FastQueue_1_9 extends SlowQueue {
} catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) {
e.printStackTrace();
}
- int[][] biomes = fs.biomes;
- Biome[] values = Biome.values();
- if (biomes != null) {
- for (int x = 0; x < 16; x++) {
- int[] array = biomes[x];
- if (array == null) {
- continue;
- }
- for (int z = 0; z < 16; z++) {
- int biome = array[z];
- if (biome == 0) {
- continue;
- }
- chunk.getBlock(x, 0, z).setBiome(values[biome]);
- }
- }
- }
- world.refreshChunk(fs.getX(), fs.getZ());
+ fixLighting(chunk, fs, true);
+ refreshChunk(fs.getX(), fs.getZ());
}
public Object newChunkSection(int i, boolean flag, char[] ids) throws ReflectiveOperationException {
@@ -227,38 +361,27 @@ public class FastQueue_1_9 extends SlowQueue {
return this.methodGetBlocks.of(obj).call();
}
- /**
- * This should be overridden by any specialized queues
- * @param wrap
- */
@Override
- public PlotChunk getChunk(ChunkWrapper wrap) {
- return new FastChunk_1_9(wrap);
+ public void fixChunkLighting(int x, int z) {
+ Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
+ this.methodInitLighting.of(c).call();
}
- /**
- * This should be overridden by any specialized queues
- * @param pc
- */
- @Override
- public boolean fixLighting(PlotChunk pc, boolean fixAll) {
+ public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) {
try {
- FastChunk_1_9 bc = (FastChunk_1_9) pc;
- Chunk chunk = bc.getChunk();
if (!chunk.isLoaded()) {
chunk.load(false);
} else {
- chunk.unload(true, true);
+ chunk.unload(true, false);
chunk.load(false);
}
// Initialize lighting
Object c = this.methodGetHandleChunk.of(chunk).call();
+ ChunkWrapper wrapper = new ChunkWrapper(getWorld(), bc.getX(), bc.getZ());
if (fixAll && !(boolean) this.methodAreNeighborsLoaded.of(c).call(1)) {
World world = chunk.getWorld();
- ChunkWrapper wrapper = bc.getChunkWrapper();
- String worldName = wrapper.world;
for (int x = wrapper.x - 1; x <= wrapper.x + 1; x++) {
for (int z = wrapper.z - 1; z <= wrapper.z + 1; z++) {
if (x != 0 && z != 0) {
@@ -266,7 +389,7 @@ public class FastQueue_1_9 extends SlowQueue {
while (!other.isLoaded()) {
other.load(true);
}
- ChunkManager.manager.loadChunk(worldName, new ChunkLoc(x, z), true);
+ ChunkManager.manager.loadChunk(getWorld(), new ChunkLoc(x, z), true);
}
}
}
@@ -284,7 +407,7 @@ public class FastQueue_1_9 extends SlowQueue {
int X = chunk.getX() << 4;
int Z = chunk.getZ() << 4;
- RefExecutor relight = this.methodW.of(w);
+ ReflectionUtils.RefMethod.RefExecutor relight = this.methodW.of(w);
for (int j = 0; j < sections.length; j++) {
Object section = sections[j];
if (section == null) {
@@ -293,7 +416,7 @@ public class FastQueue_1_9 extends SlowQueue {
if (bc.getRelight(j) == 0 && !fixAll || bc.getCount(j) == 0 || bc.getCount(j) >= 4096 && bc.getAir(j) == 0) {
continue;
}
- int[] array = bc.getIdArray(j);
+ char[] array = bc.getIdArray(j);
if (array != null) {
int l = PseudoRandom.random.random(2);
for (int k = 0; k < array.length; k++) {
@@ -329,7 +452,7 @@ public class FastQueue_1_9 extends SlowQueue {
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
- if (isSurrounded(bc.getIdArrays(), x, y, z)) {
+ if (isSurrounded(bc.blocks, x, y, z)) {
continue;
}
Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z);
@@ -345,7 +468,12 @@ public class FastQueue_1_9 extends SlowQueue {
return false;
}
- public boolean isSurrounded(int[][] sections, int x, int y, int z) {
+ @Override
+ public void refreshChunk(int x, int z) {
+ getBukkitWorld().refreshChunk(x, z);
+ }
+
+ public boolean isSurrounded(char[][] sections, int x, int y, int z) {
return isSolid(getId(sections, x, y + 1, z))
&& isSolid(getId(sections, x + 1, y - 1, z))
&& isSolid(getId(sections, x - 1, y, z))
@@ -361,29 +489,15 @@ public class FastQueue_1_9 extends SlowQueue {
return false;
}
- public int getId(int[][] sections, int x, int y, int z) {
- if (x < 0 || x > 15 || z < 0 || z > 15) {
- return 1;
- }
- if (y < 0 || y > 255) {
- return 1;
- }
- int i = MainUtil.CACHE_I[y][x][z];
- int[] section = sections[i];
+ public int getId(char[] section, int x, int y, int z) {
if (section == null) {
return 0;
}
int j = MainUtil.CACHE_J[y][x][z];
- return section[j];
+ return section[j] >> 4;
}
- public int getId(Object section, int x, int y, int z) {
- int j = MainUtil.CACHE_J[y][x][z];
- Object iBlock = this.methodGetType.of(section).call(x, y & 15, z);
- return (int) this.methodGetCombinedId.call(iBlock);
- }
-
- public int getId(Object[] sections, int x, int y, int z) {
+ public int getId(char[][] sections, int x, int y, int z) {
if (x < 0 || x > 15 || z < 0 || z > 15) {
return 1;
}
@@ -391,23 +505,10 @@ public class FastQueue_1_9 extends SlowQueue {
return 1;
}
int i = MainUtil.CACHE_I[y][x][z];
- Object section = sections[i];
+ char[] section = sections[i];
if (section == null) {
return 0;
}
return getId(section, x, y, z);
}
-
- /**
- * This should be overridden by any specialized queues
- * @param world
- * @param locations
- */
- @Override
- public void sendChunk(String world, Collection locations) {
- World worldObj = BukkitUtil.getWorld(world);
- for (ChunkLoc loc : locations) {
- worldObj.refreshChunk(loc.x, loc.z);
- }
- }
}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_8_3.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_8_3.java
deleted file mode 100644
index 0ccb98fd0..000000000
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_8_3.java
+++ /dev/null
@@ -1,247 +0,0 @@
-package com.plotsquared.bukkit.util.block;
-
-import com.intellectualcrafters.plot.util.MainUtil;
-import com.intellectualcrafters.plot.util.PlotChunk;
-import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
-import com.plotsquared.bukkit.util.BukkitUtil;
-import org.bukkit.Bukkit;
-import org.bukkit.Chunk;
-
-import java.util.Arrays;
-
-public class FastChunk_1_8_3 extends PlotChunk {
-
- public char[][] ids;
- public short[] count;
- public short[] air;
- public short[] relight;
- public int[][] biomes;
- public Chunk chunk;
-
- public FastChunk_1_8_3(ChunkWrapper chunk) {
- super(chunk);
- this.ids = new char[16][];
- this.count = new short[16];
- this.air = new short[16];
- this.relight = new short[16];
- }
-
- @Override
- public Chunk getChunkAbs() {
- ChunkWrapper loc = getChunkWrapper();
- return BukkitUtil.getWorld(loc.world).getChunkAt(loc.x, loc.z);
- }
-
- @Override
- public Chunk getChunk() {
- if (this.chunk == null) {
- ChunkWrapper cl = getChunkWrapper();
- this.chunk = Bukkit.getWorld(cl.world).getChunkAt(cl.x, cl.z);
- }
- return this.chunk;
- }
-
- @Override
- public void setChunkWrapper(ChunkWrapper loc) {
- super.setChunkWrapper(loc);
- this.chunk = null;
- }
-
- /**
- * Get the number of block changes in a specified section.
- * @param i
- * @return
- */
- public int getCount(int i) {
- return this.count[i];
- }
-
- public int getAir(int i) {
- return this.air[i];
- }
-
- public void setCount(int i, short value) {
- this.count[i] = value;
- }
-
- /**
- * Get the number of block changes in a specified section.
- * @param i
- * @return
- */
- public int getRelight(int i) {
- return this.relight[i];
- }
-
- public int getTotalCount() {
- int total = 0;
- for (int i = 0; i < 16; i++) {
- total += this.count[i];
- }
- return total;
- }
-
- public int getTotalRelight() {
- if (getTotalCount() == 0) {
- Arrays.fill(this.count, (short) 1);
- Arrays.fill(this.relight, Short.MAX_VALUE);
- return Short.MAX_VALUE;
- }
- int total = 0;
- for (int i = 0; i < 16; i++) {
- total += this.relight[i];
- }
- return total;
- }
-
- /**
- * Get the raw data for a section.
- * @param i
- * @return
- */
- public char[] getIdArray(int i) {
- return this.ids[i];
- }
-
- @Override
- public void setBlock(int x, int y, int z, int id, byte data) {
- int i = MainUtil.CACHE_I[y][x][z];
- int j = MainUtil.CACHE_J[y][x][z];
- char[] vs = this.ids[i];
- if (vs == null) {
- vs = this.ids[i] = new char[4096];
- this.count[i]++;
- } else if (vs[j] == 0) {
- this.count[i]++;
- }
- switch (id) {
- case 0:
- this.air[i]++;
- vs[j] = (char) 1;
- return;
- case 10:
- case 11:
- case 39:
- case 40:
- case 51:
- case 74:
- case 89:
- case 122:
- case 124:
- case 138:
- case 169:
- this.relight[i]++;
- case 2:
- case 4:
- case 13:
- case 14:
- case 15:
- case 20:
- case 21:
- case 22:
- case 30:
- case 32:
- case 37:
- case 41:
- case 42:
- case 45:
- case 46:
- case 47:
- case 48:
- case 49:
- case 55:
- case 56:
- case 57:
- case 58:
- case 60:
- case 7:
- case 8:
- case 9:
- case 73:
- case 78:
- case 79:
- case 80:
- case 81:
- case 82:
- case 83:
- case 85:
- case 87:
- case 88:
- case 101:
- case 102:
- case 103:
- case 110:
- case 112:
- case 113:
- case 121:
- case 129:
- case 133:
- case 165:
- case 166:
- case 170:
- case 172:
- case 173:
- case 174:
- case 181:
- case 182:
- case 188:
- case 189:
- case 190:
- case 191:
- case 192:
- vs[j] = (char) (id << 4);
- return;
- case 130:
- case 76:
- case 62:
- this.relight[i]++;
- case 54:
- case 146:
- case 61:
- case 65:
- case 68:
- case 50:
- if (data < 2) {
- data = 2;
- }
- default:
- vs[j] = (char) ((id << 4) + data);
- return;
- }
- }
-
- @Override
- public PlotChunk clone() {
- FastChunk_1_8_3 toReturn = new FastChunk_1_8_3(getChunkWrapper());
- toReturn.air = this.air.clone();
- toReturn.count = this.count.clone();
- toReturn.relight = this.relight.clone();
- toReturn.ids = new char[this.ids.length][];
- for (int i = 0; i < this.ids.length; i++) {
- char[] matrix = this.ids[i];
- if (matrix != null) {
- toReturn.ids[i] = new char[matrix.length];
- System.arraycopy(matrix, 0, toReturn.ids[i], 0, matrix.length);
- }
- }
- return toReturn;
- }
-
- @Override
- public PlotChunk shallowClone() {
- FastChunk_1_8_3 toReturn = new FastChunk_1_8_3(getChunkWrapper());
- toReturn.air = this.air;
- toReturn.count = this.count;
- toReturn.relight = this.relight;
- toReturn.ids = this.ids;
- return toReturn;
- }
-
- @Override
- public void setBiome(int x, int z, int biome) {
- if (this.biomes == null) {
- this.biomes = new int[16][16];
- }
- this.biomes[x][z] = biome;
- }
-}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_9.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_9.java
deleted file mode 100644
index ef6fcca73..000000000
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastChunk_1_9.java
+++ /dev/null
@@ -1,251 +0,0 @@
-package com.plotsquared.bukkit.util.block;
-
-import com.intellectualcrafters.plot.util.MainUtil;
-import com.intellectualcrafters.plot.util.PlotChunk;
-import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
-import com.plotsquared.bukkit.util.BukkitUtil;
-import org.bukkit.Bukkit;
-import org.bukkit.Chunk;
-
-import java.util.Arrays;
-
-public class FastChunk_1_9 extends PlotChunk {
-
- public int[][] ids;
- public short[] count;
- public short[] air;
- public short[] relight;
- public int[][] biomes;
- public Chunk chunk;
-
- public FastChunk_1_9(ChunkWrapper chunk) {
- super(chunk);
- this.ids = new int[16][];
- this.count = new short[16];
- this.air = new short[16];
- this.relight = new short[16];
- }
-
- @Override
- public Chunk getChunkAbs() {
- ChunkWrapper loc = getChunkWrapper();
- return BukkitUtil.getWorld(loc.world).getChunkAt(loc.x, loc.z);
- }
-
- @Override
- public Chunk getChunk() {
- if (this.chunk == null) {
- ChunkWrapper cl = getChunkWrapper();
- this.chunk = Bukkit.getWorld(cl.world).getChunkAt(cl.x, cl.z);
- }
- return this.chunk;
- }
-
- @Override
- public void setChunkWrapper(ChunkWrapper loc) {
- super.setChunkWrapper(loc);
- this.chunk = null;
- }
-
- /**
- * Get the number of block changes in a specified section.
- * @param i
- * @return
- */
- public int getCount(int i) {
- return this.count[i];
- }
-
- public int getAir(int i) {
- return this.air[i];
- }
-
- public void setCount(int i, short value) {
- this.count[i] = value;
- }
-
- /**
- * Get the number of block changes in a specified section.
- * @param i
- * @return
- */
- public int getRelight(int i) {
- return this.relight[i];
- }
-
- public int getTotalCount() {
- int total = 0;
- for (int i = 0; i < 16; i++) {
- total += this.count[i];
- }
- return total;
- }
-
- public int getTotalRelight() {
- if (getTotalCount() == 0) {
- Arrays.fill(this.count, (short) 1);
- Arrays.fill(this.relight, Short.MAX_VALUE);
- return Short.MAX_VALUE;
- }
- int total = 0;
- for (int i = 0; i < 16; i++) {
- total += this.relight[i];
- }
- return total;
- }
-
- /**
- * Get the raw data for a section.
- * @param i
- * @return
- */
- public int[] getIdArray(int i) {
- return this.ids[i];
- }
-
- public int[][] getIdArrays() {
- return this.ids;
- }
-
- @Override
- public void setBlock(int x, int y, int z, int id, byte data) {
- int i = MainUtil.CACHE_I[y][x][z];
- int j = MainUtil.CACHE_J[y][x][z];
- int[] vs = this.ids[i];
- if (vs == null) {
- vs = this.ids[i] = new int[4096];
- this.count[i]++;
- } else if (vs[j] == 0) {
- this.count[i]++;
- }
- switch (id) {
- case 0:
- this.air[i]++;
- vs[j] = -1;
- return;
- case 10:
- case 11:
- case 39:
- case 40:
- case 51:
- case 74:
- case 89:
- case 122:
- case 124:
- case 138:
- case 169:
- this.relight[i]++;
- case 2:
- case 4:
- case 13:
- case 14:
- case 15:
- case 20:
- case 21:
- case 22:
- case 30:
- case 32:
- case 37:
- case 41:
- case 42:
- case 45:
- case 46:
- case 47:
- case 48:
- case 49:
- case 55:
- case 56:
- case 57:
- case 58:
- case 60:
- case 7:
- case 8:
- case 9:
- case 73:
- case 78:
- case 79:
- case 80:
- case 81:
- case 82:
- case 83:
- case 85:
- case 87:
- case 88:
- case 101:
- case 102:
- case 103:
- case 110:
- case 112:
- case 113:
- case 121:
- case 129:
- case 133:
- case 165:
- case 166:
- case 170:
- case 172:
- case 173:
- case 174:
- case 181:
- case 182:
- case 188:
- case 189:
- case 190:
- case 191:
- case 192:
- vs[j] = id;
- return;
- case 130:
- case 76:
- case 62:
- this.relight[i]++;
- case 54:
- case 146:
- case 61:
- case 65:
- case 68:
- case 50:
- if (data < 2) {
- data = 2;
- }
- default:
- vs[j] = id + (data << 12);
- return;
- }
- }
-
- @Override
- public PlotChunk clone() {
- FastChunk_1_9 toReturn = new FastChunk_1_9(getChunkWrapper());
- toReturn.air = this.air.clone();
- toReturn.count = this.count.clone();
- toReturn.relight = this.relight.clone();
- toReturn.ids = new int[this.ids.length][];
- for (int i = 0; i < this.ids.length; i++) {
- int[] matrix = this.ids[i];
- if (matrix != null) {
- toReturn.ids[i] = new int[matrix.length];
- System.arraycopy(matrix, 0, toReturn.ids[i], 0, matrix.length);
- }
- }
- return toReturn;
- }
-
- @Override
- public PlotChunk shallowClone() {
- FastChunk_1_9 toReturn = new FastChunk_1_9(getChunkWrapper());
- toReturn.air = this.air;
- toReturn.count = this.count;
- toReturn.relight = this.relight;
- toReturn.ids = this.ids;
- return toReturn;
- }
-
- @Override
- public void setBiome(int x, int z, int biome) {
- if (this.biomes == null) {
- this.biomes = new int[16][16];
- }
- this.biomes[x][z] = biome;
- }
-}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_7.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_7.java
deleted file mode 100644
index b29f5826f..000000000
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_7.java
+++ /dev/null
@@ -1,179 +0,0 @@
-package com.plotsquared.bukkit.util.block;
-
-import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
-
-import com.intellectualcrafters.plot.object.ChunkLoc;
-import com.intellectualcrafters.plot.object.PlotBlock;
-import com.intellectualcrafters.plot.util.MainUtil;
-import com.intellectualcrafters.plot.util.PlotChunk;
-import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
-import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
-import com.intellectualcrafters.plot.util.SetQueue;
-import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
-import com.intellectualcrafters.plot.util.TaskManager;
-import com.plotsquared.bukkit.util.BukkitUtil;
-import com.plotsquared.bukkit.util.SendChunk;
-import org.bukkit.Chunk;
-import org.bukkit.World;
-import org.bukkit.block.Biome;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map.Entry;
-
-public class FastQueue_1_7 extends SlowQueue {
-
- private final RefClass classBlock = getRefClass("{nms}.Block");
- private final RefClass classChunk = getRefClass("{nms}.Chunk");
- private final RefClass classWorld = getRefClass("{nms}.World");
- private final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
- private final RefMethod methodGetHandle;
- private final RefMethod methodGetChunkAt;
- private final RefMethod methodA;
- private final RefMethod methodGetById;
- private final RefMethod methodInitLighting;
- private final SendChunk sendChunk;
-
- private final HashMap toUpdate = new HashMap<>();
-
- public FastQueue_1_7() throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
- this.methodGetHandle = this.classCraftWorld.getMethod("getHandle");
- this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class);
- this.methodA = this.classChunk.getMethod("a", int.class, int.class, int.class, this.classBlock, int.class);
- this.methodGetById = this.classBlock.getMethod("getById", int.class);
- this.methodInitLighting = this.classChunk.getMethod("initLighting");
- this.sendChunk = new SendChunk();
- TaskManager.runTaskRepeat(new Runnable() {
- @Override
- public void run() {
- if (FastQueue_1_7.this.toUpdate.isEmpty()) {
- return;
- }
- int count = 0;
- ArrayList chunks = new ArrayList<>();
- Iterator> i = FastQueue_1_7.this.toUpdate.entrySet().iterator();
- while (i.hasNext() && (count < 128)) {
- chunks.add(i.next().getValue());
- i.remove();
- count++;
- }
- if (count == 0) {
- return;
- }
- update(chunks);
- }
- }, 1);
- MainUtil.initCache();
- }
-
- public void update(Collection chunks) {
- if (chunks.isEmpty()) {
- return;
- }
- if (!MainUtil.canSendChunk) {
- for (Chunk chunk : chunks) {
- chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
- chunk.unload(true, false);
- chunk.load();
- }
- return;
- }
- try {
- this.sendChunk.sendChunk(chunks);
- } catch (Throwable e) {
- e.printStackTrace();
- MainUtil.canSendChunk = false;
- }
- }
-
- /**
- * This should be overridden by any specialized queues
- * @param plotChunk
- */
- @Override
- public void execute(PlotChunk plotChunk) {
- SlowChunk sc = (SlowChunk) plotChunk;
- Chunk chunk = plotChunk.getChunk();
- ChunkWrapper wrapper = plotChunk.getChunkWrapper();
- if (!this.toUpdate.containsKey(wrapper)) {
- this.toUpdate.put(wrapper, chunk);
- }
- chunk.load(true);
- World world = chunk.getWorld();
- Object w = this.methodGetHandle.of(world).call();
- Object c = this.methodGetChunkAt.of(w).call(wrapper.x, wrapper.z);
- for (int i = 0; i < sc.result.length; i++) {
- PlotBlock[] result2 = sc.result[i];
- if (result2 == null) {
- continue;
- }
- for (int j = 0; j < 4096; j++) {
- int x = MainUtil.x_loc[i][j];
- int y = MainUtil.y_loc[i][j];
- int z = MainUtil.z_loc[i][j];
- PlotBlock newBlock = result2[j];
- if (newBlock.id == -1) {
- chunk.getBlock(x, y, z).setData(newBlock.data, false);
- continue;
- }
- Object block = this.methodGetById.call(newBlock.id);
- this.methodA.of(c).call(x, y, z, block, newBlock.data);
- }
- }
- int[][] biomes = sc.biomes;
- Biome[] values = Biome.values();
- if (biomes != null) {
- for (int x = 0; x < 16; x++) {
- int[] array = biomes[x];
- if (array == null) {
- continue;
- }
- for (int z = 0; z < 16; z++) {
- int biome = array[z];
- if (biome == 0) {
- continue;
- }
- chunk.getBlock(x, 0, z).setBiome(values[biome]);
- }
- }
- }
- }
-
- /**
- * This should be overridden by any specialized queues
- * @param wrap
- */
- @Override
- public PlotChunk getChunk(ChunkWrapper wrap) {
- return new SlowChunk(wrap);
- }
-
- /**
- * This should be overridden by any specialized queues
- * @param chunk
- * @param fixAll
- */
- @Override
- public boolean fixLighting(PlotChunk chunk, boolean fixAll) {
- Object c = this.methodGetHandle.of(chunk.getChunk()).call();
- this.methodInitLighting.of(c).call();
- return true;
- }
-
- /**
- * This should be overridden by any specialized queues
- * @param world
- * @param locations
- */
- @Override
- public void sendChunk(String world, Collection locations) {
- World worldObj = BukkitUtil.getWorld(world);
- for (ChunkLoc loc : locations) {
- ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z);
- this.toUpdate.remove(wrapper);
- }
- this.sendChunk.sendChunk(world, locations);
- }
-}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java
index 286f63aee..51446d309 100644
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java
+++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java
@@ -1,62 +1,109 @@
package com.plotsquared.bukkit.util.block;
+import com.intellectualcrafters.plot.object.ChunkWrapper;
+import com.intellectualcrafters.plot.object.Location;
+import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
-import com.intellectualcrafters.plot.util.PlotChunk;
-import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
+import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.ChunkGenerator.BiomeGrid;
import org.bukkit.generator.ChunkGenerator.ChunkData;
+import org.bukkit.material.MaterialData;
-public class GenChunk extends PlotChunk {
+public class GenChunk extends ScopedLocalBlockQueue {
public final Biome[] biomes;
- public Chunk chunk;
public short[][] result;
public byte[][] result_data;
public ChunkData cd;
public BiomeGrid grid;
+ public Chunk chunk;
+ public String world;
+ public int cx;
+ public int cz;
+
public GenChunk(Chunk chunk, ChunkWrapper wrap) {
- super(wrap);
- if ((this.chunk = chunk) == null && wrap != null) {
+ super(null, new Location(null, 0, 0, 0), new Location(null, 15, 255, 15));
+ if ((this.chunk = chunk) == null && (wrap) != null) {
World world = BukkitUtil.getWorld(wrap.world);
if (world != null) {
- chunk = world.getChunkAt(wrap.x, wrap.z);
+ this.chunk = world.getChunkAt(wrap.x, wrap.z);
}
}
this.biomes = Biome.values();
}
- @Override
- public Chunk getChunkAbs() {
- ChunkWrapper wrap = getChunkWrapper();
- if (this.chunk == null || wrap.x != this.chunk.getX() || wrap.z != this.chunk.getZ()) {
- this.chunk = BukkitUtil.getWorld(wrap.world).getChunkAt(wrap.x, wrap.z);
+ public void setChunk(Chunk chunk) {
+ this.chunk = chunk;
+ }
+
+ public void setChunk(ChunkWrapper wrap) {
+ chunk = null;
+ world = wrap.world;
+ cx = wrap.x;
+ cz = wrap.z;
+ }
+
+ public Chunk getChunk() {
+ if (chunk == null) {
+ World worldObj = BukkitUtil.getWorld(world);
+ if (worldObj != null) {
+ this.chunk = worldObj.getChunkAt(cx, cz);
+ }
}
- return this.chunk;
+ return chunk;
+ }
+
+ public ChunkWrapper getChunkWrapper() {
+ if (chunk == null) {
+ return new ChunkWrapper(world, cx, cz);
+ }
+ return new ChunkWrapper(chunk.getWorld().getName(), chunk.getX(), chunk.getZ());
}
@Override
- public void setBiome(int x, int z, int biome) {
+ public void fillBiome(String biomeName) {
+ if (grid == null) {
+ return;
+ }
+ Biome biome = Biome.valueOf(biomeName.toUpperCase());
+ for (int x = 0; x <= 15; x++) {
+ for (int z = 0; z < 15; z++) {
+ this.grid.setBiome(x, z, biome);
+ }
+ }
+ }
+
+ @Override
+ public boolean setBiome(int x, int z, String biome) {
+ return setBiome(x, z, Biome.valueOf(biome.toUpperCase()));
+ }
+
+ public boolean setBiome(int x, int z, int biome) {
if (this.grid != null) {
this.grid.setBiome(x, z, this.biomes[biome]);
+ return true;
}
+ return false;
}
- public void setBiome(int x, int z, Biome biome) {
+ public boolean setBiome(int x, int z, Biome biome) {
if (this.grid != null) {
this.grid.setBiome(x, z, biome);
+ return true;
}
+ return false;
}
@Override
- public void setBlock(int x, int y, int z, int id, byte data) {
+ public boolean setBlock(int x, int y, int z, int id, int data) {
if (this.result == null) {
- this.cd.setBlock(x, y, z, id, data);
- return;
+ this.cd.setBlock(x, y, z, id, (byte) data);
+ return true;
}
int i = MainUtil.CACHE_I[y][x][z];
short[] v = this.result[i];
@@ -70,13 +117,61 @@ public class GenChunk extends PlotChunk {
if (vd == null) {
this.result_data[i] = vd = new byte[4096];
}
- vd[j] = data;
+ vd[j] = (byte) data;
}
+ return true;
}
@Override
- public PlotChunk clone() {
- GenChunk toReturn = new GenChunk(getChunkAbs(), getChunkWrapper());
+ public PlotBlock getBlock(int x, int y, int z) {
+ int i = MainUtil.CACHE_I[y][x][z];
+ if (result == null) {
+ MaterialData md = cd.getTypeAndData(x, y, z);
+ return PlotBlock.get(md.getItemTypeId(), md.getData());
+ }
+ short[] array = result[i];
+ if (array == null) {
+ return PlotBlock.get(0, 0);
+ }
+ int j = MainUtil.CACHE_J[y][x][z];
+ short id = array[j];
+ if (id == 0) {
+ return PlotBlock.get(id, 0);
+ }
+ byte[] dataArray = result_data[i];
+ if (dataArray == null) {
+ return PlotBlock.get(id, 0);
+ }
+ return PlotBlock.get(id, dataArray[j]);
+ }
+
+ public int getX() {
+ return chunk == null ? cx : chunk.getX();
+ }
+
+ public int getZ() {
+ return chunk == null ? cz : chunk.getZ();
+ }
+
+ @Override
+ public String getWorld() {
+ return chunk == null ? world : chunk.getWorld().getName();
+ }
+
+ @Override
+ public Location getMax() {
+ return new Location(getWorld(), 15 + (getX() << 4), 255, 15 + (getZ() << 4));
+ }
+
+ @Override
+ public Location getMin() {
+ return new Location(getWorld(), getX() << 4, 0, getZ() << 4);
+ }
+
+
+
+ public GenChunk clone() {
+ GenChunk toReturn = new GenChunk(chunk, new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ()));
if (this.result != null) {
for (int i = 0; i < this.result.length; i++) {
short[] matrix = this.result[i];
@@ -97,9 +192,8 @@ public class GenChunk extends PlotChunk {
return toReturn;
}
- @Override
- public PlotChunk shallowClone() {
- GenChunk toReturn = new GenChunk(getChunkAbs(), getChunkWrapper());
+ public GenChunk shallowClone() {
+ GenChunk toReturn = new GenChunk(chunk, new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ()));
toReturn.result = this.result;
toReturn.result_data = this.result_data;
toReturn.cd = this.cd;
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowChunk.java
deleted file mode 100644
index a87b4cdea..000000000
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowChunk.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package com.plotsquared.bukkit.util.block;
-
-import com.intellectualcrafters.plot.object.PlotBlock;
-import com.intellectualcrafters.plot.util.MainUtil;
-import com.intellectualcrafters.plot.util.PlotChunk;
-import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
-import com.plotsquared.bukkit.util.BukkitUtil;
-import org.bukkit.Chunk;
-
-public class SlowChunk extends PlotChunk {
-
- public PlotBlock[][] result = new PlotBlock[16][];
- public int[][] biomes;
-
- public SlowChunk(ChunkWrapper chunk) {
- super(chunk);
- }
-
- @Override
- public Chunk getChunkAbs() {
- ChunkWrapper loc = getChunkWrapper();
- return BukkitUtil.getWorld(loc.world).getChunkAt(loc.x, loc.z);
- }
-
- @Override
- public void setBiome(int x, int z, int biome) {
- if (this.biomes == null) {
- this.biomes = new int[16][16];
- }
- this.biomes[x][z] = biome;
- }
-
- @Override
- public void setBlock(int x, int y, int z, int id, byte data) {
- if (this.result[y >> 4] == null) {
- this.result[y >> 4] = new PlotBlock[4096];
- }
- this.result[MainUtil.CACHE_I[y][x][z]][MainUtil.CACHE_J[y][x][z]] = PlotBlock.get((short) id, data);
- }
-
- @Override
- public PlotChunk clone() {
- SlowChunk toReturn = new SlowChunk(getChunkWrapper());
- for (int i = 0; i < this.result.length; i++) {
- PlotBlock[] matrix = this.result[i];
- if (matrix != null) {
- toReturn.result[i] = new PlotBlock[matrix.length];
- System.arraycopy(matrix, 0, toReturn.result[i], 0, matrix.length);
- }
- }
- return toReturn;
- }
-
- @Override
- public PlotChunk shallowClone() {
- SlowChunk toReturn = new SlowChunk(getChunkWrapper());
- toReturn.result = this.result;
- return toReturn;
- }
-}
diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowQueue.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowQueue.java
deleted file mode 100644
index 222269f75..000000000
--- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/SlowQueue.java
+++ /dev/null
@@ -1,287 +0,0 @@
-package com.plotsquared.bukkit.util.block;
-
-import com.intellectualcrafters.plot.PS;
-import com.intellectualcrafters.plot.object.ChunkLoc;
-import com.intellectualcrafters.plot.object.PlotBlock;
-import com.intellectualcrafters.plot.util.MainUtil;
-import com.intellectualcrafters.plot.util.PlotChunk;
-import com.intellectualcrafters.plot.util.PlotQueue;
-import com.intellectualcrafters.plot.util.SetQueue;
-import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
-import com.plotsquared.bukkit.util.BukkitUtil;
-import org.bukkit.Chunk;
-import org.bukkit.block.Biome;
-import org.bukkit.block.Block;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Map.Entry;
-import java.util.concurrent.ConcurrentHashMap;
-
-public class SlowQueue implements PlotQueue {
-
- private final ConcurrentHashMap> blocks = new ConcurrentHashMap<>();
-
- public SlowQueue() {
- MainUtil.initCache();
- }
-
- @Override
- public boolean setBlock(String world, int x, int y, int z, short id, byte data) {
- if (y > 255 || y < 0) {
- return false;
- }
- ChunkWrapper wrap = SetQueue.IMP.new ChunkWrapper(world, x >> 4, z >> 4);
- x = x & 15;
- z = z & 15;
- PlotChunk result = this.blocks.get(wrap);
- if (result == null) {
- result = getChunk(wrap);
- result.setBlock(x, y, z, id, data);
- PlotChunk previous = this.blocks.put(wrap, result);
- if (previous == null) {
- return true;
- }
- this.blocks.put(wrap, previous);
- result = previous;
- }
- result.setBlock(x, y, z, id, data);
- return true;
- }
-
- @Override
- public void setChunk(PlotChunk chunk) {
- this.blocks.put(chunk.getChunkWrapper(), chunk);
- }
-
- @Override
- public PlotChunk next() {
- if (!PS.get().isMainThread(Thread.currentThread())) {
- throw new IllegalStateException("Must be called from main thread!");
- }
- try {
- if (this.blocks.isEmpty()) {
- return null;
- }
- Iterator>> iterator = this.blocks.entrySet().iterator();
- PlotChunk toReturn = iterator.next().getValue();
- if (SetQueue.IMP.isWaiting()) {
- return null;
- }
- iterator.remove();
- execute(toReturn);
- fixLighting(toReturn, true);
- return toReturn;
- } catch (Throwable e) {
- e.printStackTrace();
- return null;
- }
- }
-
- @Override
- public PlotChunk next(ChunkWrapper wrap, boolean fixLighting) {
- if (!PS.get().isMainThread(Thread.currentThread())) {
- throw new IllegalStateException("Must be called from main thread!");
- }
- try {
- if (this.blocks.isEmpty()) {
- return null;
- }
- PlotChunk toReturn = this.blocks.remove(wrap);
- if (toReturn == null) {
- return null;
- }
- execute(toReturn);
- fixLighting(toReturn, fixLighting);
- return toReturn;
- } catch (Throwable e) {
- e.printStackTrace();
- return null;
- }
- }
-
- @Override
- public void clear() {
- this.blocks.clear();
- }
-
- @Override
- public void regenerateChunk(String world, ChunkLoc loc) {
- BukkitUtil.getWorld(world).regenerateChunk(loc.x, loc.z);
- }
-
- /**
- * This should be overridden by any specialized queues.
- * @param plotChunk
- */
- public void execute(PlotChunk plotChunk) {
- SlowChunk sc = (SlowChunk) plotChunk;
- Chunk chunk = plotChunk.getChunk();
- chunk.load(true);
- for (int i = 0; i < sc.result.length; i++) {
- PlotBlock[] result2 = sc.result[i];
- if (result2 == null) {
- continue;
- }
- for (int j = 0; j < 4096; j++) {
- int x = MainUtil.x_loc[i][j];
- int y = MainUtil.y_loc[i][j];
- int z = MainUtil.z_loc[i][j];
- Block block = chunk.getBlock(x, y, z);
- PlotBlock newBlock = result2[j];
- if (newBlock == null) {
- continue;
- }
- switch (newBlock.id) {
- case -1:
- if (block.getData() == newBlock.data) {
- continue;
- }
- block.setData(newBlock.data);
- continue;
- case 0:
- case 2:
- case 4:
- case 13:
- case 14:
- case 15:
- case 20:
- case 21:
- case 22:
- case 25:
- case 30:
- case 32:
- case 37:
- case 39:
- case 40:
- case 41:
- case 42:
- case 45:
- case 46:
- case 47:
- case 48:
- case 49:
- case 51:
- case 52:
- case 54:
- case 55:
- case 56:
- case 57:
- case 58:
- case 60:
- case 61:
- case 62:
- case 7:
- case 8:
- case 9:
- case 10:
- case 11:
- case 73:
- case 74:
- case 78:
- case 79:
- case 80:
- case 81:
- case 82:
- case 83:
- case 84:
- case 85:
- case 87:
- case 88:
- case 101:
- case 102:
- case 103:
- case 110:
- case 112:
- case 113:
- case 117:
- case 121:
- case 122:
- case 123:
- case 124:
- case 129:
- case 133:
- case 138:
- case 137:
- case 140:
- case 165:
- case 166:
- case 169:
- case 170:
- case 172:
- case 173:
- case 174:
- case 176:
- case 177:
- case 181:
- case 182:
- case 188:
- case 189:
- case 190:
- case 191:
- case 192:
- if (block.getTypeId() == newBlock.id) {
- continue;
- }
- block.setTypeId(newBlock.id, false);
- continue;
- default:
- if (block.getTypeId() == newBlock.id && block.getData() == newBlock.data) {
- continue;
- }
- if (newBlock.data == 0) {
- block.setTypeId(newBlock.id, false);
- } else {
- block.setTypeIdAndData(newBlock.id, newBlock.data, false);
- }
- continue;
- }
- }
- }
- int[][] biomes = sc.biomes;
- Biome[] values = Biome.values();
- if (biomes != null) {
- for (int x = 0; x < 16; x++) {
- int[] array = biomes[x];
- if (array == null) {
- continue;
- }
- for (int z = 0; z < 16; z++) {
- int biome = array[z];
- if (biome == 0) {
- continue;
- }
- chunk.getBlock(x, 0, z).setBiome(values[biome]);
- }
- }
- }
- }
-
- /**
- * This should be overridden by any specialized queues.
- * @param wrap
- */
- @Override
- public PlotChunk getChunk(ChunkWrapper wrap) {
- return new SlowChunk(wrap);
- }
-
- /**
- * This should be overridden by any specialized queues.
- * @param fixAll
- */
- @Override
- public boolean fixLighting(PlotChunk chunk, boolean fixAll) {
- // Do nothing
- return true;
- }
-
- /**
- * This should be overridden by any specialized queues.
- * @param locations
- */
- @Override
- public void sendChunk(String world, Collection locations) {
- // Do nothing
- }
-}
diff --git a/Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java b/Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java
index 68901d2f1..aeacc6a88 100644
--- a/Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java
+++ b/Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java
@@ -11,13 +11,12 @@ import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.InventoryUtil;
-import com.intellectualcrafters.plot.util.PlotQueue;
import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.SetupUtils;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.util.WorldUtil;
-
+import com.intellectualcrafters.plot.util.block.QueueProvider;
import java.io.File;
import java.util.List;
@@ -135,10 +134,10 @@ public interface IPlotMain extends ILogger {
EconHandler getEconomyHandler();
/**
- * Get the {@link PlotQueue} class.
+ * Get the {@link com.intellectualcrafters.plot.util.block.QueueProvider} class.
* @return
*/
- PlotQueue initPlotQueue();
+ QueueProvider initBlockQueue();
/**
* Get the {@link WorldUtil} class.
diff --git a/Core/src/main/java/com/intellectualcrafters/plot/PS.java b/Core/src/main/java/com/intellectualcrafters/plot/PS.java
index 92248870f..ed42d2f9c 100644
--- a/Core/src/main/java/com/intellectualcrafters/plot/PS.java
+++ b/Core/src/main/java/com/intellectualcrafters/plot/PS.java
@@ -39,18 +39,17 @@ import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.ReflectionUtils;
import com.intellectualcrafters.plot.util.SchematicHandler;
-import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.SetupUtils;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.intellectualcrafters.plot.util.area.QuadMap;
+import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.intellectualcrafters.plot.util.expiry.ExpireManager;
import com.intellectualcrafters.plot.util.expiry.ExpiryTask;
import com.plotsquared.listener.WESubscriber;
import com.sk89q.worldedit.WorldEdit;
-
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@@ -112,7 +111,6 @@ public class PS {
public YamlConfiguration worlds;
public YamlConfiguration storage;
public YamlConfiguration commands;
- public TaskManager TASK;
public WorldEdit worldedit;
public URL update;
private ILogger logger;
@@ -153,7 +151,7 @@ public class PS {
if (getJavaVersion() < 1.8) {
PS.log(C.CONSOLE_JAVA_OUTDATED_1_8);
}
- this.TASK = this.IMP.getTaskManager();
+ TaskManager.IMP = this.IMP.getTaskManager();
setupConfigs();
this.translationFile =
MainUtil.getFile(this.IMP.getDirectory(), Settings.Paths.TRANSLATIONS + File.separator + "PlotSquared.use_THIS.yml");
@@ -219,7 +217,8 @@ public class PS {
// World Util
WorldUtil.IMP = this.IMP.initWorldUtil();
// Set block
- SetQueue.IMP.queue = this.IMP.initPlotQueue();
+ GlobalBlockQueue.IMP = new GlobalBlockQueue(IMP.initBlockQueue(), 1);
+ GlobalBlockQueue.IMP.runTask();
// Set chunk
ChunkManager.manager = this.IMP.initChunkManager();
// Schematic handler
@@ -1802,7 +1801,7 @@ public class PS {
*/
public void disable() {
try {
- this.TASK = null;
+ TaskManager.IMP = null;
this.database = null;
// Validate that all data in the db is correct
final HashSet plots = new HashSet<>();
diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Clear.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Clear.java
index 925438343..e19aba3b4 100644
--- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Clear.java
+++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Clear.java
@@ -10,7 +10,7 @@ import com.intellectualcrafters.plot.object.RunnableVal2;
import com.intellectualcrafters.plot.object.RunnableVal3;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
-import com.intellectualcrafters.plot.util.SetQueue;
+import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.plotsquared.general.commands.Command;
import com.plotsquared.general.commands.CommandDeclaration;
@@ -45,7 +45,7 @@ public class Clear extends Command {
@Override
public void run() {
plot.unlink();
- SetQueue.IMP.addTask(new Runnable() {
+ GlobalBlockQueue.IMP.addTask(new Runnable() {
@Override
public void run() {
plot.removeRunning();
diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java
index 9d1346b6d..9e58bc6f3 100644
--- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java
+++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java
@@ -27,18 +27,17 @@ import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.SchematicHandler;
-import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.SetupUtils;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil;
+import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.intellectualcrafters.plot.util.expiry.ExpireManager;
import com.intellectualcrafters.plot.util.expiry.PlotAnalysis;
import com.plotsquared.general.commands.Command;
import com.plotsquared.general.commands.CommandDeclaration;
import com.plotsquared.listener.WEManager;
-
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -48,7 +47,6 @@ import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
-
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
@@ -119,12 +117,12 @@ public class DebugExec extends SubCommand {
// Instances
this.scope.put("PS", PS.get());
- this.scope.put("SetQueue", SetQueue.IMP);
+ this.scope.put("GlobalBlockQueue", GlobalBlockQueue.IMP);
this.scope.put("ExpireManager", ExpireManager.IMP);
if (PS.get().worldedit != null) {
this.scope.put("WEManager", new WEManager());
}
- this.scope.put("TaskManager", PS.get().TASK);
+ this.scope.put("TaskManager", TaskManager.IMP);
this.scope.put("TitleManager", AbstractTitle.TITLE_CLASS);
this.scope.put("ConsolePlayer", ConsolePlayer.getConsole());
this.scope.put("SchematicHandler", SchematicHandler.manager);
diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Relight.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Relight.java
index 21bcfb646..4b20ca2c6 100644
--- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Relight.java
+++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Relight.java
@@ -8,8 +8,7 @@ import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.RunnableVal2;
import com.intellectualcrafters.plot.object.RunnableVal3;
import com.intellectualcrafters.plot.util.ChunkManager;
-import com.intellectualcrafters.plot.util.PlotChunk;
-import com.intellectualcrafters.plot.util.SetQueue;
+import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
import com.plotsquared.general.commands.Command;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.HashSet;
@@ -28,12 +27,11 @@ public class Relight extends Command {
return;
}
HashSet regions = plot.getRegions();
+ final LocalBlockQueue queue = plot.getArea().getQueue(false);
ChunkManager.chunkTask(plot, new RunnableVal() {
@Override
public void run(int[] value) {
- SetQueue.ChunkWrapper cw = SetQueue.IMP.new ChunkWrapper(plot.getArea().worldname, value[0], value[1]);
- PlotChunk> pc = SetQueue.IMP.queue.getChunk(cw);
- pc.fixLighting();
+ queue.fixChunkLighting(value[0], value[1]);
}
}, new Runnable() {
@Override
diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Set.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Set.java
index 893e2a33d..07de4b379 100644
--- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Set.java
+++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Set.java
@@ -12,10 +12,10 @@ import com.intellectualcrafters.plot.object.PlotManager;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
-import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.StringComparison;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.WorldUtil;
+import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.plotsquared.general.commands.Command;
import com.plotsquared.general.commands.CommandDeclaration;
@@ -114,7 +114,7 @@ public class Set extends SubCommand {
current.setComponent(component, blocks);
}
MainUtil.sendMessage(player, C.GENERATING_COMPONENT);
- SetQueue.IMP.addTask(new Runnable() {
+ GlobalBlockQueue.IMP.addTask(new Runnable() {
@Override
public void run() {
plot.removeRunning();
diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java
index 2ff6d7ac0..e564cc961 100644
--- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java
+++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java
@@ -13,12 +13,11 @@ import com.intellectualcrafters.plot.object.PlotManager;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.SetupObject;
import com.intellectualcrafters.plot.util.MainUtil;
-import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.SetupUtils;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.WorldUtil;
+import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.plotsquared.general.commands.CommandDeclaration;
-
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@@ -156,7 +155,7 @@ public class Template extends SubCommand {
setup.step = new ConfigurationNode[0];
setup.world = world;
SetupUtils.manager.setupWorld(setup);
- SetQueue.IMP.addTask(new Runnable() {
+ GlobalBlockQueue.IMP.addTask(new Runnable() {
@Override
public void run() {
MainUtil.sendMessage(player, "Done!");
diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Trim.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Trim.java
index 1aeb53454..674c0cc3d 100644
--- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Trim.java
+++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Trim.java
@@ -13,6 +13,8 @@ import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.WorldUtil;
+import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
+import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
import com.plotsquared.general.commands.CommandDeclaration;
import java.io.File;
@@ -189,10 +191,11 @@ public class Trim extends SubCommand {
}
}
}
+ final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false);
TaskManager.objectTask(chunks, new RunnableVal() {
@Override
public void run(ChunkLoc value) {
- ChunkManager.manager.regenerateChunk(world, value);
+ queue.regenChunk(value.x, value.z);
}
}, this);
}
diff --git a/Core/src/main/java/com/intellectualcrafters/plot/generator/AugmentedUtils.java b/Core/src/main/java/com/intellectualcrafters/plot/generator/AugmentedUtils.java
index 21322cfa9..baa6d93df 100644
--- a/Core/src/main/java/com/intellectualcrafters/plot/generator/AugmentedUtils.java
+++ b/Core/src/main/java/com/intellectualcrafters/plot/generator/AugmentedUtils.java
@@ -1,16 +1,16 @@
package com.intellectualcrafters.plot.generator;
import com.intellectualcrafters.plot.PS;
-import com.intellectualcrafters.plot.object.LazyResult;
+import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.PlotManager;
import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.object.RegionWrapper;
-import com.intellectualcrafters.plot.util.PlotChunk;
-import com.intellectualcrafters.plot.util.SetQueue;
-import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
-
+import com.intellectualcrafters.plot.util.block.DelegateLocalBlockQueue;
+import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
+import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
+import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue;
import java.util.Set;
public class AugmentedUtils {
@@ -23,18 +23,10 @@ public class AugmentedUtils {
enabled = true;
}
- public static boolean generate(final String world, final int cx, final int cz, LazyResult> lazyChunk) {
+ public static boolean generate(final String world, final int cx, final int cz, LocalBlockQueue queue) {
if (!enabled) {
return false;
}
- if (lazyChunk == null) {
- lazyChunk = new LazyResult>() {
- @Override
- public PlotChunk> create() {
- return SetQueue.IMP.queue.getChunk(SetQueue.IMP.new ChunkWrapper(world, cx, cz));
- }
- };
- }
final int bx = cx << 4;
final int bz = cz << 4;
RegionWrapper region = new RegionWrapper(bx, bx + 15, bz, bz + 15);
@@ -44,7 +36,6 @@ public class AugmentedUtils {
}
PseudoRandom r = new PseudoRandom();
r.state = (cx << 16) | (cz & 0xFFFF);
- ChunkWrapper wrap = SetQueue.IMP.new ChunkWrapper(world, cx, cz);
boolean toReturn = false;
for (final PlotArea area : areas) {
if (area.TYPE == 0) {
@@ -57,8 +48,11 @@ public class AugmentedUtils {
if (generator == null) {
continue;
}
- final PlotChunk> result = lazyChunk.getOrCreate();
- final PlotChunk> primaryMask;
+ // Mask
+ if (queue == null) {
+ queue = GlobalBlockQueue.IMP.getNewQueue(world, false);
+ }
+ LocalBlockQueue primaryMask;
// coords
int bxx;
int bzz;
@@ -70,42 +64,29 @@ public class AugmentedUtils {
bzz = Math.max(0, area.getRegion().minZ - bz);
txx = Math.min(15, area.getRegion().maxX - bx);
tzz = Math.min(15, area.getRegion().maxZ - bz);
- primaryMask = new PlotChunk