Remove Nukkit and Sponge files from v5

We don't need these because they already exist in our git history and in the legacy branch.
This commit is contained in:
MattBDev 2020-04-09 19:38:10 -04:00
parent 0d26111fa7
commit bdba2b33fb
93 changed files with 0 additions and 11081 deletions

View file

@ -1,51 +0,0 @@
repositories {
maven { url = "https://oss.sonatype.org/content/repositories/snapshots/" }
maven { url "http://nexus.hc.to/content/repositories/pub_releases" }
maven { url "https://repo.potestas.xyz/main/" }
flatDir { dirs 'lib' }
}
dependencies {
compile project(':Core')
compile 'com.google.guava:guava:17.0'
compile 'cn.nukkit:nukkit:1.0-SNAPSHOT'
}
configurations.all {
resolutionStrategy {
force 'com.google.guava:guava:17.0'
}
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
processResources {
from('src/main/resources') {
include 'plugin.yml'
expand(
name: project.parent.name,
version: project.parent.version
)
}
}
// We only want the shadow jar produced
jar.enabled = false
shadowJar {
dependencies {
include(dependency(':Core'))
}
archiveName = "${parent.name}-${project.name}-${parent.version}.jar"
destinationDir = file '../target'
relocate('com.google.gson', 'com.sk89q.worldedit.internal.gson')
relocate 'org.yaml.snakeyaml', 'com.boydti.fawe.yaml'
relocate 'com.google.common', 'com.sk89q.worldedit.internal.common'
}
shadowJar.doLast {
task ->
ant.checksum file: task.archivePath
}
build.dependsOn(shadowJar);

Binary file not shown.

View file

@ -1,450 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit;
import cn.nukkit.Nukkit;
import cn.nukkit.OfflinePlayer;
import cn.nukkit.Player;
import cn.nukkit.entity.Entity;
import cn.nukkit.event.Listener;
import cn.nukkit.level.Level;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.level.generator.Generator;
import cn.nukkit.metadata.MetadataValue;
import cn.nukkit.plugin.Plugin;
import cn.nukkit.plugin.PluginBase;
import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection;
import com.github.intellectualsites.plotsquared.nukkit.generator.NukkitPlotGenerator;
import com.github.intellectualsites.plotsquared.nukkit.listeners.PlayerEvents;
import com.github.intellectualsites.plotsquared.nukkit.listeners.WorldEvents;
import com.github.intellectualsites.plotsquared.nukkit.util.*;
import com.github.intellectualsites.plotsquared.nukkit.util.block.NukkitHybridGen;
import com.github.intellectualsites.plotsquared.nukkit.util.block.NukkitLocalQueue;
import com.github.intellectualsites.plotsquared.nukkit.uuid.FileUUIDHandler;
import com.github.intellectualsites.plotsquared.nukkit.uuid.LowerOfflineUUIDWrapper;
import com.github.intellectualsites.plotsquared.plot.IPlotMain;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.object.chat.PlainChatManager;
import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager;
import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea;
import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager;
import com.github.intellectualsites.plotsquared.plot.util.block.QueueProvider;
import com.sk89q.worldedit.WorldEdit;
import java.io.File;
import java.lang.reflect.Field;
public final class NukkitMain extends PluginBase implements Listener, IPlotMain {
public static WorldEdit worldEdit;
private int[] version;
private String name;
@Override public int[] getServerVersion() {
if (this.version == null) {
try {
this.version = new int[3];
String[] split = Nukkit.API_VERSION.split("\\.");
this.version[0] = Integer.parseInt(split[0]);
this.version[1] = Integer.parseInt(split[1]);
if (split.length == 3) {
this.version[2] = Integer.parseInt(split[2]);
}
} catch (NumberFormatException e) {
return new int[] {1, 0, 0};
}
}
return this.version;
}
@Override public void onEnable() {
try {
this.name = getDescription().getName();
getServer().getName();
new PlotSquared(this, "Nukkit");
if (Settings.Enabled_Components.METRICS) {
new Metrics(this).start();
PlotSquared.log(C.PREFIX + "&6Metrics enabled.");
} else {
PlotSquared.log(C.CONSOLE_PLEASE_ENABLE_METRICS.f(getPluginName()));
}
Generator.addGenerator(NukkitHybridGen.class, getPluginName(), 1);
if (Settings.Enabled_Components.WORLDS) {
TaskManager.IMP.taskRepeat(new Runnable() {
@Override public void run() {
unload();
}
}, 20);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
public void unload() {
PlotAreaManager manager = PlotSquared.get().getPlotAreaManager();
if (manager instanceof SinglePlotAreaManager) {
long start = System.currentTimeMillis();
SinglePlotArea area = ((SinglePlotAreaManager) manager).getArea();
Map<Integer, Level> worlds = getServer().getLevels();
Level unload = null;
for (Level world : getServer().getLevels().values()) {
String name = world.getName();
PlotId id = PlotId.fromString(name);
if (id != null) {
Plot plot = area.getOwnedPlot(id);
if (plot != null) {
List<PlotPlayer> players = plot.getPlayersInPlot();
if (players.isEmpty() && PlotPlayer.wrap(plot.owner) == null) {
unload = world;
break;
}
}
}
}
if (unload != null) {
Map<Long, ? extends FullChunk> chunks = unload.getChunks();
FullChunk[] toUnload = chunks.values().toArray(new FullChunk[chunks.size()]);
for (FullChunk chunk : toUnload) {
try {
chunk.unload(true, false);
} catch (Exception e) {
e.printStackTrace();
}
if (System.currentTimeMillis() - start > 20) {
return;
}
}
getServer().unloadLevel(unload, true);
}
}
}
@Override public void onDisable() {
PlotSquared.get().disable();
getServer().getScheduler().cancelAllTasks();
}
@Override public void log(String message) {
try {
message = C.color(message);
if (!Settings.Chat.CONSOLE_COLOR) {
message = message.replaceAll('\u00A7' + "[0-9]", "");
}
this.getServer().getConsoleSender().sendMessage(message);
} catch (Throwable ignored) {
System.out.println(ConsoleColors.fromString(message));
}
}
@Override public void disable() {
onDisable();
}
@Override public int[] getPluginVersion() {
String ver = getDescription().getVersion();
if (ver.contains("-")) {
ver = ver.split("-")[0];
}
String[] split = ver.split("\\.");
return new int[] {Integer.parseInt(split[0]), Integer.parseInt(split[1]),
Integer.parseInt(split[2])};
}
@Override public String getPluginVersionString() {
return getDescription().getVersion();
}
@Override public String getPluginName() {
return name;
}
@Override public void registerCommands() {
NukkitCommand bukkitCommand =
new NukkitCommand("plot", new String[] {"p", "plot", "ps", "plotsquared", "p2", "2"});
getServer().getCommandMap().register("plot", bukkitCommand);
}
@Override public File getDirectory() {
return getDataFolder();
}
@Override public File getWorldContainer() {
return new File("worlds");
}
@Override public TaskManager getTaskManager() {
return new NukkitTaskManager(this);
}
@Override public void runEntityTask() {
PlotSquared.log(C.PREFIX + "KillAllEntities started.");
TaskManager.runTaskRepeat(new Runnable() {
@Override public void run() {
PlotSquared.get().foreachPlotArea(new RunnableVal<PlotArea>() {
@Override public void run(PlotArea plotArea) {
Level world = getServer().getLevelByName(plotArea.getWorldName());
try {
if (world == null) {
return;
}
Entity[] entities = world.getEntities();
for (Entity entity : entities) {
if (entity instanceof Player) {
continue;
}
Location location = NukkitUtil.getLocation(entity.getLocation());
Plot plot = location.getPlot();
if (plot == null) {
if (location.isPlotArea()) {
entity.kill();
}
continue;
}
List<MetadataValue> meta = entity.getMetadata("plot");
if (meta.isEmpty()) {
continue;
}
Plot origin = (Plot) meta.get(0).value();
if (!plot.equals(origin.getBasePlot(false))) {
entity.kill();
}
continue;
}
} catch (Throwable e) {
e.printStackTrace();
}
}
});
}
}, 20);
}
@Override public void registerPlayerEvents() {
getServer().getPluginManager().registerEvents(new PlayerEvents(), this);
}
@Override public void registerInventoryEvents() {
PlotSquared.debug("Not implemented: registerPlotPlusEvents");
}
@Override public void registerPlotPlusEvents() {
PlotSquared.debug("Not implemented: registerPlotPlusEvents");
}
@Override public void registerForceFieldEvents() {
PlotSquared.debug("Not implemented: registerPlotPlusEvents");
}
@Override public boolean initWorldEdit() {
if (getServer().getPluginManager().getPlugin("WorldEdit") != null) {
worldEdit = WorldEdit.getInstance();
return true;
}
return false;
}
@Override public EconHandler getEconomyHandler() {
return null;
}
@Override public QueueProvider initBlockQueue() {
return QueueProvider.of(NukkitLocalQueue.class, null);
}
@Override public WorldUtil initWorldUtil() {
return new NukkitUtil(this);
}
@Override public boolean initPlotMeConverter() {
return false; // No PlotMe for MCPE
}
@Override public GeneratorWrapper<?> getGenerator(String world, String name) {
if (name == null) {
return null;
}
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("world", world);
Class<? extends Generator> gen = Generator.getGenerator(name);
if (gen != null) {
try {
Generator instance = gen.getConstructor(Map.class).newInstance(map);
if (instance instanceof GeneratorWrapper) {
return (GeneratorWrapper<?>) instance;
}
map.put("generator", instance);
return new NukkitPlotGenerator(map);
} catch (Throwable e) {
System.out.println("Failed to create generator for " + name + " | " + gen);
while (e.getCause() != null) {
e = e.getCause();
}
synchronized (PlotSquared.class) {
e.printStackTrace();
}
}
}
return new NukkitHybridGen(map);
}
@Override public HybridUtils initHybridUtils() {
return new NukkitHybridUtils();
}
@Override public SetupUtils initSetupUtils() {
return new NukkitSetupUtils(this);
}
@Override public UUIDHandlerImplementation initUUIDHandler() {
Settings.UUID.FORCE_LOWERCASE = true;
Settings.UUID.OFFLINE = true;
LowerOfflineUUIDWrapper wrapper = new LowerOfflineUUIDWrapper();
return new FileUUIDHandler(wrapper);
}
@Override public ChunkManager initChunkManager() {
return new NukkitChunkManager();
}
@Override public EventUtil initEventUtil() {
return new NukkitEventUtil(this);
}
@Override public void unregister(PlotPlayer player) {
NukkitUtil.removePlayer(player.getName());
}
@Override public void registerChunkProcessor() {
PlotSquared.debug("Not implemented: registerChunkProcessor");
}
@Override public void registerWorldEvents() {
getServer().getPluginManager().registerEvents(new WorldEvents(), this);
}
@Override public InventoryUtil initInventoryUtil() {
return new NukkitInventoryUtil();
}
@Override public void startMetrics() {
new Metrics(this).start();
PlotSquared.log(C.PREFIX + "&6Metrics enabled.");
}
@Override public void setGenerator(String worldName) {
Level world = getServer().getLevelByName(worldName);
if (world == null) {
// create world
ConfigurationSection worldConfig =
PlotSquared.get().worlds.getConfigurationSection("worlds." + worldName);
String manager = worldConfig.getString("generator.plugin", getPluginName());
SetupObject setup = new SetupObject();
setup.plotManager = manager;
setup.setupGenerator = worldConfig.getString("generator.init", manager);
setup.type = worldConfig.getInt("generator.type");
setup.terrain = worldConfig.getInt("generator.terrain");
setup.step = new ConfigurationNode[0];
setup.world = worldName;
SetupUtils.manager.setupWorld(setup);
world = getServer().getLevelByName(worldName);
} else {
HashMap<String, Object> map = new HashMap<>();
map.put("world", world.getName());
map.put("plot-generator", PlotSquared.get().IMP.getDefaultGenerator());
setGenerator(world, new NukkitPlotGenerator(map));
}
if (world != null) {
try {
Generator gen = world.getGenerator();
if (gen instanceof NukkitPlotGenerator) {
PlotSquared.get().loadWorld(worldName, (NukkitPlotGenerator) gen);
} else if (gen instanceof GeneratorWrapper) {
PlotSquared.get().loadWorld(worldName, (GeneratorWrapper) gen);
} else if (PlotSquared.get().worlds.contains("worlds." + worldName)) {
PlotSquared.get().loadWorld(worldName, null);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
private void setGenerator(Level level, Generator generator) {
try {
Field fieldClass = Level.class.getDeclaredField("generator");
Field fieldInstance = Level.class.getDeclaredField("generatorInstance");
fieldClass.setAccessible(true);
fieldInstance.setAccessible(true);
fieldClass.set(level, generator.getClass());
fieldInstance.set(level, generator);
} catch (Throwable e) {
e.printStackTrace();
}
}
@Override public SchematicHandler initSchematicHandler() {
return new NukkitSchematicHandler(this);
}
@Override public AbstractTitle initTitleManager() {
return new NukkitTitleUtil();
}
@Override public PlotPlayer wrapPlayer(Object player) {
if (player instanceof Player) {
return NukkitUtil.getPlayer((Player) player);
}
if (player instanceof OfflinePlayer) {
return NukkitUtil.getPlayer((OfflinePlayer) player);
}
if (player instanceof String) {
return UUIDHandler.getPlayer((String) player);
}
if (player instanceof UUID) {
return UUIDHandler.getPlayer((UUID) player);
}
return null;
}
@Override public String getNMSPackage() {
return "";
}
@Override public ChatManager<?> initChatManager() {
return new PlainChatManager();
}
@Override
public GeneratorWrapper<?> wrapPlotGenerator(String world, IndependentPlotGenerator generator) {
HashMap<String, Object> settings = new HashMap<>();
settings.put("world", world);
settings.put("plot-generator", generator);
return new NukkitPlotGenerator(settings);
}
@Override public List<String> getPluginIds() {
ArrayList<String> names = new ArrayList<>();
for (Map.Entry<String, Plugin> entry : getServer().getPluginManager().getPlugins()
.entrySet()) {
Plugin plugin = entry.getValue();
names.add(entry.getKey() + ';' + plugin.getDescription().getVersion() + ':' + plugin
.isEnabled());
}
return names;
}
@Override public IndependentPlotGenerator getDefaultGenerator() {
return new HybridGen() {
@Override public PlotManager getNewPlotManager() {
return new HybridPlotManager() {
@Override public int getWorldHeight() {
return 255;
}
};
}
};
}
}

View file

@ -1,59 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.event.Cancellable;
import cn.nukkit.event.Event;
import cn.nukkit.event.HandlerList;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.PlotCluster;
/**
* Called when a flag is removed from a plot.
*/
public class ClusterFlagRemoveEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final PlotCluster cluster;
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot.
*
* @param flag Flag that was removed
* @param cluster PlotCluster from which the flag was removed
*/
public ClusterFlagRemoveEvent(Flag flag, PlotCluster cluster) {
this.cluster = cluster;
this.flag = flag;
}
public static HandlerList getHandlers() {
return handlers;
}
/**
* Get the cluster involved.
*
* @return PlotCluster
*/
public PlotCluster getCluster() {
return this.cluster;
}
/**
* Get the flag involved.
*
* @return Flag
*/
public Flag getFlag() {
return this.flag;
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View file

@ -1,55 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.Player;
import cn.nukkit.event.Cancellable;
import cn.nukkit.event.HandlerList;
import cn.nukkit.event.player.PlayerEvent;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Plot plot;
private final boolean auto;
private boolean cancelled;
/**
* PlayerClaimPlotEvent: Called when a plot is claimed.
*
* @param player Player that claimed the plot
* @param plot Plot that was claimed
*/
public PlayerClaimPlotEvent(Player player, Plot plot, boolean auto) {
this.player = player;
this.plot = plot;
this.auto = auto;
}
public static HandlerList getHandlers() {
return handlers;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
/**
* @return true if it was an automated claim, else false
*/
public boolean wasAuto() {
return this.auto;
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View file

@ -1,37 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.Player;
import cn.nukkit.event.HandlerList;
import cn.nukkit.event.player.PlayerEvent;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
public class PlayerEnterPlotEvent extends PlayerEvent {
private static final HandlerList handlers = new HandlerList();
private final Plot plot;
private final Player player;
/**
* Called when a player leaves a plot.
*
* @param player Player that entered the plot
* @param plot Plot that was entered
*/
public PlayerEnterPlotEvent(Player player, Plot plot) {
this.player = player;
this.plot = plot;
}
public static HandlerList getHandlers() {
return handlers;
}
/**
* Get the plot involved.
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
}

View file

@ -1,41 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.Player;
import cn.nukkit.event.HandlerList;
import cn.nukkit.event.player.PlayerEvent;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
/**
*/
public class PlayerLeavePlotEvent extends PlayerEvent {
private static final HandlerList handlers = new HandlerList();
private final Plot plot;
/**
* PlayerLeavePlotEvent: Called when a player leaves a plot
*
* @param player Player that left the plot
* @param plot Plot that was left
*/
public PlayerLeavePlotEvent(Player player, Plot plot) {
this.player = player;
this.plot = plot;
}
public static HandlerList getHandlers() {
return handlers;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
}

View file

@ -1,62 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.Player;
import cn.nukkit.event.HandlerList;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import java.util.UUID;
public class PlayerPlotDeniedEvent extends PlotEvent {
private static final HandlerList handlers = new HandlerList();
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotDeniedEvent: Called when the denied UUID list is modified for a plot.
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was denied/un-denied
* @param added true of add to deny list, false if removed
*/
public PlayerPlotDeniedEvent(Player initiator, Plot plot, UUID player, boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
public static HandlerList getHandlers() {
return handlers;
}
/**
* If a user was added.
*
* @return boolean
*/
public boolean wasAdded() {
return this.added;
}
/**
* The player added/removed.
*
* @return UUID
*/
public UUID getPlayer() {
return this.player;
}
/**
* The player initiating the action.
*
* @return Player
*/
public Player getInitiator() {
return this.initiator;
}
}

View file

@ -1,65 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.Player;
import cn.nukkit.event.HandlerList;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import java.util.UUID;
/**
*/
public class PlayerPlotHelperEvent extends PlotEvent {
private static final HandlerList handlers = new HandlerList();
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotHelperEvent: Called when a plot helper is added/removed
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was added/removed from the helper list
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotHelperEvent(Player initiator, Plot plot, UUID player, boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
public static HandlerList getHandlers() {
return handlers;
}
/**
* If a player was added
*
* @return boolean
*/
public boolean wasAdded() {
return this.added;
}
/**
* The UUID added/removed
*
* @return UUID
*/
public UUID getPlayer() {
return this.player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator() {
return this.initiator;
}
}

View file

@ -1,65 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.Player;
import cn.nukkit.event.HandlerList;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import java.util.UUID;
/**
*/
public class PlayerPlotTrustedEvent extends PlotEvent {
private static final HandlerList handlers = new HandlerList();
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotTrustedEvent: Called when a plot trusted user is added/removed
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was added/removed from the trusted list
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotTrustedEvent(Player initiator, Plot plot, UUID player, boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
public static HandlerList getHandlers() {
return handlers;
}
/**
* If a player was added
*
* @return boolean
*/
public boolean wasAdded() {
return this.added;
}
/**
* The UUID added/removed
*
* @return UUID
*/
public UUID getPlayer() {
return this.player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator() {
return this.initiator;
}
}

View file

@ -1,59 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.Player;
import cn.nukkit.event.Cancellable;
import cn.nukkit.event.HandlerList;
import cn.nukkit.event.player.PlayerEvent;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
/**
* Called when a player teleports to a plot
*/
public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Location from;
private final Plot plot;
private boolean cancelled;
/**
* PlayerTeleportToPlotEvent: Called when a player teleports to a plot
*
* @param player That was teleported
* @param from Start location
* @param plot Plot to which the player was teleported
*/
public PlayerTeleportToPlotEvent(Player player, Location from, Plot plot) {
this.player = player;
this.from = from;
this.plot = plot;
}
public static HandlerList getHandlers() {
return handlers;
}
/**
* Get the from location
*
* @return Location
*/
public Location getFrom() {
return this.from;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
@Override public boolean isCancelled() {
return this.cancelled;
}
}

View file

@ -1,107 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.Player;
import cn.nukkit.event.Cancellable;
import cn.nukkit.event.HandlerList;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import java.util.UUID;
public class PlotChangeOwnerEvent extends PlotEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Plot plot;
private final Player initiator;
private final UUID newOwner;
private final UUID oldOwner;
private final boolean hasOldOwner;
private boolean cancelled;
/**
* PlotChangeOwnerEvent: Called when a plot's owner is change.
*
* @param newOwner The new owner of the plot
* @param oldOwner The old owner of the plot
* @param plot The plot having its owner changed
*/
public PlotChangeOwnerEvent(Player initiator, Plot plot, UUID oldOwner, UUID newOwner,
boolean hasOldOwner) {
super(plot);
this.plot = plot;
this.initiator = initiator;
this.newOwner = newOwner;
this.hasOldOwner = hasOldOwner;
this.oldOwner = oldOwner;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the PlotId.
*
* @return PlotId
*/
public PlotId getPlotId() {
return getPlot().getId();
}
/**
* Get the world name.
*
* @return String
*/
public String getWorld() {
return getPlot().getWorldName();
}
/**
* Get the change-owner initator
*
* @return Player
*/
public Player getInitiator() {
return this.initiator;
}
/**
* Get the old owner of the plot
*
* @return UUID
*/
public UUID getOldOwner() {
return this.oldOwner;
}
/**
* Get the new owner of the plot
*
* @return UUID
*/
public UUID getNewOwner() {
return this.newOwner;
}
/**
* Get if the plot had an old owner
*
* @return boolean
*/
public boolean hasOldOwner() {
return this.hasOldOwner;
}
public HandlerList getHandlers() {
return handlers;
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View file

@ -1,50 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.event.Cancellable;
import cn.nukkit.event.HandlerList;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
/**
* Called when a plot is cleared
*/
public class PlotClearEvent extends PlotEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled;
public PlotClearEvent(Plot plot) {
super(plot);
}
public static HandlerList getHandlers() {
return handlers;
}
/**
* Get the PlotId.
*
* @return PlotId
*/
public PlotId getPlotId() {
return getPlot().getId();
}
/**
* Get the world name.
*
* @return String
*/
public String getWorld() {
return getPlot().getWorldName();
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View file

@ -1,51 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.event.HandlerList;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
/**
* Called when a plot component is set
*/
public class PlotComponentSetEvent extends PlotEvent {
private static final HandlerList handlers = new HandlerList();
private final String component;
public PlotComponentSetEvent(Plot plot, String component) {
super(plot);
this.component = component;
}
public static HandlerList getHandlers() {
return handlers;
}
/**
* Get the PlotId
*
* @return PlotId
*/
public PlotId getPlotId() {
return getPlot().getId();
}
/**
* Get the world name
*
* @return String
*/
public String getWorld() {
return getPlot().getWorldName();
}
/**
* Get the component which was set
*
* @return Component name
*/
public String getComponent() {
return this.component;
}
}

View file

@ -1,40 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.event.HandlerList;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
/**
* Called when a plot is deleted
*/
public class PlotDeleteEvent extends PlotEvent {
private static final HandlerList handlers = new HandlerList();
public PlotDeleteEvent(Plot plot) {
super(plot);
}
public static HandlerList getHandlers() {
return handlers;
}
/**
* Get the PlotId
*
* @return PlotId
*/
public PlotId getPlotId() {
return getPlot().getId();
}
/**
* Get the world name
*
* @return String
*/
public String getWorld() {
return getPlot().getWorldName();
}
}

View file

@ -1,18 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.event.Event;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
public abstract class PlotEvent extends Event {
private final Plot plot;
public PlotEvent(Plot plot) {
this.plot = plot;
}
public final Plot getPlot() {
return this.plot;
}
}

View file

@ -1,48 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.event.Cancellable;
import cn.nukkit.event.HandlerList;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
/**
* Called when a Flag is added to a plot.
*/
public class PlotFlagAddEvent extends PlotEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagAddEvent: Called when a Flag is added to a plot.
*
* @param flag Flag that was added
* @param plot Plot to which the flag was added
*/
public PlotFlagAddEvent(Flag flag, Plot plot) {
super(plot);
this.flag = flag;
}
public static HandlerList getHandlers() {
return handlers;
}
/**
* Get the flag involved.
*
* @return Flag
*/
public Flag getFlag() {
return this.flag;
}
@Override public final boolean isCancelled() {
return this.cancelled;
}
@Override public final void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}

View file

@ -1,48 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.event.Cancellable;
import cn.nukkit.event.HandlerList;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
/**
* Called when a flag is removed from a plot
*/
public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot
*
* @param flag Flag that was removed
* @param plot Plot from which the flag was removed
*/
public PlotFlagRemoveEvent(Flag flag, Plot plot) {
super(plot);
this.flag = flag;
}
public static HandlerList getHandlers() {
return handlers;
}
/**
* Get the flag involved
*
* @return Flag
*/
public Flag getFlag() {
return this.flag;
}
@Override public final boolean isCancelled() {
return this.cancelled;
}
@Override public final void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}

View file

@ -1,55 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.event.Cancellable;
import cn.nukkit.event.HandlerList;
import cn.nukkit.level.Level;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import java.util.ArrayList;
public class PlotMergeEvent extends PlotEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final ArrayList<PlotId> plots;
private final Level world;
private boolean cancelled;
/**
* PlotMergeEvent: Called when plots are merged
*
* @param world World in which the event occurred
* @param plot Plot that was merged
* @param plots A list of plots involved in the event
*/
public PlotMergeEvent(Level world, Plot plot, ArrayList<PlotId> plots) {
super(plot);
this.world = world;
this.plots = plots;
}
public static HandlerList getHandlers() {
return handlers;
}
/**
* Get the plots being added.
*
* @return Plot
*/
public ArrayList<PlotId> getPlots() {
return this.plots;
}
public Level getLevel() {
return this.world;
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View file

@ -1,45 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.event.Cancellable;
import cn.nukkit.event.HandlerList;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.Rating;
public class PlotRateEvent extends PlotEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final PlotPlayer rater;
private Rating rating;
private boolean cancelled = false;
public PlotRateEvent(PlotPlayer rater, Rating rating, Plot plot) {
super(plot);
this.rater = rater;
this.rating = rating;
}
public static HandlerList getHandlers() {
return handlers;
}
public PlotPlayer getRater() {
return this.rater;
}
public Rating getRating() {
return this.rating;
}
public void setRating(Rating rating) {
this.rating = rating;
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}

View file

@ -1,60 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.events;
import cn.nukkit.event.Cancellable;
import cn.nukkit.event.Event;
import cn.nukkit.event.HandlerList;
import cn.nukkit.level.Level;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import java.util.ArrayList;
public class PlotUnlinkEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final ArrayList<PlotId> plots;
private final Level world;
private final PlotArea area;
private boolean cancelled;
/**
* Called when a mega-plot is unlinked.
*
* @param world World in which the event occurred
* @param plots Plots that are involved in the event
*/
public PlotUnlinkEvent(Level world, PlotArea area, ArrayList<PlotId> plots) {
this.plots = plots;
this.world = world;
this.area = area;
}
public static HandlerList getHandlers() {
return handlers;
}
/**
* Get the plots involved.
*
* @return The {@link PlotId}'s of the plots involved
*/
public ArrayList<PlotId> getPlots() {
return this.plots;
}
public Level getLevel() {
return this.world;
}
public PlotArea getArea() {
return this.area;
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View file

@ -1,48 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.generator;
import cn.nukkit.event.EventHandler;
import cn.nukkit.event.Listener;
import cn.nukkit.event.level.ChunkLoadEvent;
import cn.nukkit.level.Level;
import cn.nukkit.level.format.FullChunk;
import com.github.intellectualsites.plotsquared.nukkit.NukkitMain;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.generator.AugmentedUtils;
import java.util.concurrent.ConcurrentHashMap;
public class NukkitAugmentedGenerator implements Listener {
private static NukkitAugmentedGenerator generator;
private static ConcurrentHashMap<String, NukkitAugmentedGenerator> generators =
new ConcurrentHashMap<>();
private NukkitAugmentedGenerator(NukkitMain plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
public static NukkitAugmentedGenerator get(Level level) {
NukkitAugmentedGenerator current = generators.get(level.getName());
if (current != null) {
return current;
}
if (generator == null) {
NukkitMain plugin = ((NukkitMain) PlotSquared.get().IMP);
generator = new NukkitAugmentedGenerator(plugin);
}
generators.put(level.getName(), generator);
return generator;
}
@EventHandler private void onChunkLoad(ChunkLoadEvent event) {
Level level = event.getLevel();
generator = generators.get(level.getName());
if (generator != null) {
generator.populate(level, event.getChunk());
}
}
private void populate(Level world, FullChunk chunk) {
AugmentedUtils.generate(world.getName(), chunk.getX(), chunk.getZ(), null);
}
}

View file

@ -1,187 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.generator;
import cn.nukkit.level.format.generic.BaseFullChunk;
import cn.nukkit.level.generator.Generator;
import cn.nukkit.math.NukkitRandom;
import cn.nukkit.math.Vector3;
import com.github.intellectualsites.plotsquared.nukkit.util.NukkitUtil;
import com.github.intellectualsites.plotsquared.nukkit.util.block.NukkitWrappedChunk;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator;
import com.github.intellectualsites.plotsquared.plot.util.ChunkManager;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue;
import java.util.Map;
public class NukkitPlotGenerator extends Generator implements GeneratorWrapper<Generator> {
protected final PseudoRandom random = new PseudoRandom();
protected final IndependentPlotGenerator plotGenerator;
protected final Generator platformGenerator;
protected final boolean full;
protected final String world;
protected final Map<String, Object> settings;
protected final NukkitWrappedChunk chunkSetter;
protected boolean loaded = false;
protected cn.nukkit.level.ChunkManager chunkManager;
public NukkitPlotGenerator(Map<String, Object> map) {
if (map == null) {
throw new IllegalArgumentException("options may not be null!");
}
this.settings = map;
MainUtil.initCache();
this.world = map.get("world").toString();
if (map.containsKey("generator")) {
final Generator cg = (Generator) map.get("generator");
if (cg instanceof NukkitPlotGenerator) {
throw new IllegalArgumentException(
"Generator: " + cg.getClass().getName() + " is already a NukkitPlotGenerator!");
}
this.full = false;
PlotSquared.debug("NukkitPlotGenerator does not fully support: " + cg);
this.platformGenerator = cg;
this.plotGenerator = new IndependentPlotGenerator() {
@Override public void processSetup(SetupObject setup) {
}
@Override public void initialize(PlotArea area) {
}
@Override public PlotManager getNewPlotManager() {
return PlotSquared.get().IMP.getDefaultGenerator().getNewPlotManager();
}
@Override public String getName() {
return cg.getClass().getName();
}
@Override
public PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max) {
return PlotSquared.get().IMP.getDefaultGenerator()
.getNewPlotArea(world, id, min, max);
}
@Override
public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings,
PseudoRandom random) {
Location min = result.getMin();
int cx = min.getX() >> 4;
int cz = min.getZ() >> 4;
cg.generateChunk(cx, cz);
cg.populateChunk(cx, cz);
}
};
chunkSetter = new NukkitWrappedChunk(world, null);
MainUtil.initCache();
} else {
this.plotGenerator = (IndependentPlotGenerator) map.get("plot-generator");
this.platformGenerator = this;
this.full = true;
chunkSetter = new NukkitWrappedChunk(world, null);
}
}
@Override public void augment(PlotArea area) {
NukkitAugmentedGenerator.get(NukkitUtil.getWorld(area.getWorldName()));
}
@Override public boolean isFull() {
return this.full;
}
@Override public IndependentPlotGenerator getPlotGenerator() {
return this.plotGenerator;
}
@Override public Generator getPlatformGenerator() {
return this.platformGenerator;
}
@Override public String toString() {
if (this.platformGenerator == this) {
return this.plotGenerator.getName();
}
if (this.platformGenerator == null) {
return "null";
} else {
return this.platformGenerator.getClass().getName();
}
}
@Override public boolean equals(Object obj) {
if (obj == null) {
return false;
}
return toString().equals(obj.toString()) || toString().equals(obj.getClass().getName());
}
@Override public int getId() {
return 1;
}
@Override
public void init(cn.nukkit.level.ChunkManager chunkManager, NukkitRandom nukkitRandom) {
if (this.chunkManager == null) {
PlotSquared.get().loadWorld(world, this);
}
this.chunkManager = chunkManager;
if (getPlatformGenerator() != this) {
getPlatformGenerator().init(chunkManager, nukkitRandom);
}
}
@Override public void generateChunk(int cx, int cz) {
if (getPlatformGenerator() != this) {
getPlatformGenerator().generateChunk(cx, cz);
} else {
BaseFullChunk chunk = this.chunkManager.getChunk(cx, cz);
// Load if improperly loaded
if (!this.loaded) {
PlotSquared.get().loadWorld(world, this);
this.loaded = true;
}
chunkSetter.init(chunk);
// Set random seed
this.random.state = cx << 16 | cz & 0xFFFF;
// Process the chunk
if (ChunkManager.preProcessChunk(chunkSetter)) {
return;
}
PlotArea area = PlotSquared.get().getPlotArea(world, null);
try {
this.plotGenerator.generateChunk(this.chunkSetter, area, this.random);
} catch (Throwable e) {
// Recover from generator error
e.printStackTrace();
}
ChunkManager.postProcessChunk(chunkSetter);
}
}
@Override public void populateChunk(int x, int z) {
if (getPlatformGenerator() != this) {
getPlatformGenerator().populateChunk(x, z);
} else {
// No populating
}
}
@Override public Map<String, Object> getSettings() {
return settings;
}
@Override public String getName() {
return plotGenerator.getName();
}
@Override public Vector3 getSpawn() {
return new Vector3(0, 61, 0);
}
@Override public cn.nukkit.level.ChunkManager getChunkManager() {
return chunkManager;
}
}

View file

@ -1,52 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.listeners;
import cn.nukkit.event.EventHandler;
import cn.nukkit.event.EventPriority;
import cn.nukkit.event.Listener;
import cn.nukkit.event.level.LevelInitEvent;
import cn.nukkit.event.level.LevelLoadEvent;
import cn.nukkit.level.Level;
import cn.nukkit.level.generator.Generator;
import com.github.intellectualsites.plotsquared.nukkit.generator.NukkitPlotGenerator;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import java.util.HashMap;
@SuppressWarnings("unused")
public class WorldEvents implements Listener {
public WorldEvents() {
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onWorldLoad(LevelLoadEvent event) {
handle(event.getLevel());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onWorldInit(LevelInitEvent event) {
handle(event.getLevel());
}
private void handle(Level level) {
String name = level.getName();
try {
Generator gen = level.getGenerator();
if (gen instanceof GeneratorWrapper) {
PlotSquared.get().loadWorld(name, (GeneratorWrapper<?>) gen);
} else {
HashMap<String, Object> settings = new HashMap<>();
settings.put("world", level.getName());
settings.put("generator", gen);
PlotSquared.get().loadWorld(name, new NukkitPlotGenerator(settings));
for (PlotArea area : PlotSquared.get().getPlotAreas(name)) {
area.MAX_BUILD_HEIGHT = Math.min(127, area.MAX_BUILD_HEIGHT);
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}

View file

@ -1,235 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.object;
import cn.nukkit.Player;
import cn.nukkit.Server;
import cn.nukkit.event.player.PlayerTeleportEvent;
import cn.nukkit.network.protocol.LevelEventPacket;
import cn.nukkit.plugin.RegisteredListener;
import cn.nukkit.utils.EventException;
import com.github.intellectualsites.plotsquared.nukkit.util.NukkitUtil;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.TeleportCause;
import java.util.Collections;
import java.util.UUID;
public class NukkitPlayer extends PlotPlayer {
public final Player player;
public boolean offline;
private UUID uuid;
private String name;
/**
* <p>Please do not use this method. Instead use
* NukkitUtil.getPlayer(Player), as it caches player objects.</p>
*
* @param player
*/
public NukkitPlayer(Player player) {
this.player = player;
super.populatePersistentMetaMap();
}
public NukkitPlayer(Player player, boolean offline) {
this.player = player;
this.offline = offline;
super.populatePersistentMetaMap();
}
@Override public Location getLocation() {
Location location = super.getLocation();
return location == null ? NukkitUtil.getLocation(this.player) : location;
}
@Override public UUID getUUID() {
if (this.uuid == null) {
this.uuid = UUIDHandler.getUUID(this);
}
return this.uuid;
}
@Override public long getLastPlayed() {
return this.player.getLastPlayed();
}
@Override public boolean canTeleport(Location loc) {
cn.nukkit.level.Location to = NukkitUtil.getLocation(loc);
cn.nukkit.level.Location from = player.getLocation();
PlayerTeleportEvent event =
new PlayerTeleportEvent(player, from, to, PlayerTeleportEvent.TeleportCause.PLUGIN);
RegisteredListener[] listeners = event.getHandlers().getRegisteredListeners();
for (RegisteredListener listener : listeners) {
if (listener.getPlugin().getName().equals(PlotSquared.imp().getPluginName())) {
continue;
}
try {
listener.callEvent(event);
} catch (EventException e) {
e.printStackTrace();
}
}
if (event.isCancelled() || !event.getTo().equals(to)) {
return false;
}
event = new PlayerTeleportEvent(player, to, from, PlayerTeleportEvent.TeleportCause.PLUGIN);
for (RegisteredListener listener : listeners) {
if (listener.getPlugin().getName().equals(PlotSquared.imp().getPluginName())) {
continue;
}
try {
listener.callEvent(event);
} catch (EventException e) {
e.printStackTrace();
}
}
return true;
}
@Override public boolean hasPermission(String permission) {
if (this.offline && EconHandler.manager != null) {
return EconHandler.manager.hasPermission(getName(), permission);
}
return this.player.hasPermission(permission);
}
@Override public boolean isPermissionSet(String permission) {
return this.player.isPermissionSet(permission);
}
@Override public void sendMessage(String message) {
if (!StringMan.isEqual(this.<String>getMeta("lastMessage"), message) || (
System.currentTimeMillis() - this.<Long>getMeta("lastMessageTime") > 5000)) {
setMeta("lastMessage", message);
setMeta("lastMessageTime", System.currentTimeMillis());
this.player.sendMessage(message);
}
}
@Override public void teleport(Location to, TeleportCause cause) {
if (Math.abs(to.getX()) >= 30000000 || Math.abs(to.getZ()) >= 30000000) {
return;
}
cn.nukkit.level.Location loc =
new cn.nukkit.level.Location(to.getX() + 0.5, to.getY(), to.getZ() + 0.5, to.getYaw(),
to.getPitch(), NukkitUtil.getWorld(to.getWorld()));
this.player.teleport(loc);
}
@Override public String getName() {
if (this.name == null) {
this.name = this.player.getName();
}
return this.name;
}
@Override public boolean isOnline() {
return !this.offline && this.player.isOnline();
}
@Override public void setCompassTarget(Location location) {
throw new UnsupportedOperationException("Not implemented yet: setCompassTarget");
}
@Override public Location getLocationFull() {
return NukkitUtil.getLocationFull(this.player);
}
@Override public void setWeather(PlotWeather weather) {
LevelEventPacket pk;
switch (weather) {
case RAIN: {
pk = new LevelEventPacket();
pk.evid = LevelEventPacket.EVENT_STOP_THUNDER;
pk.data = Integer.MAX_VALUE;
Server.broadcastPacket(Collections.singleton(player), pk);
pk = new LevelEventPacket();
pk.evid = LevelEventPacket.EVENT_START_RAIN;
pk.data = Integer.MAX_VALUE;
Server.broadcastPacket(Collections.singleton(player), pk);
break;
}
case CLEAR: {
pk = new LevelEventPacket();
pk.evid = LevelEventPacket.EVENT_STOP_THUNDER;
pk.data = Integer.MAX_VALUE;
Server.broadcastPacket(Collections.singleton(player), pk);
pk = new LevelEventPacket();
pk.evid = LevelEventPacket.EVENT_STOP_RAIN;
pk.data = Integer.MAX_VALUE;
Server.broadcastPacket(Collections.singleton(player), pk);
break;
}
case RESET:
player.getLevel().sendWeather(player);
break;
}
}
@Override public PlotGameMode getGameMode() {
switch (this.player.getGamemode()) {
case 0:
return PlotGameMode.SURVIVAL;
case 1:
return PlotGameMode.CREATIVE;
case 2:
return PlotGameMode.ADVENTURE;
case 3:
return PlotGameMode.SPECTATOR;
default:
return PlotGameMode.NOT_SET;
}
}
@Override public void setGameMode(PlotGameMode gameMode) {
switch (gameMode) {
case ADVENTURE:
this.player.setGamemode(2);
break;
case CREATIVE:
this.player.setGamemode(1);
break;
case SPECTATOR:
this.player.setGamemode(3);
break;
case SURVIVAL:
this.player.setGamemode(0);
break;
default:
this.player.setGamemode(0);
break;
}
}
@Override public void setTime(long time) {
throw new UnsupportedOperationException("Not implemented yet: setTIme");
}
@Override public boolean getFlight() {
return player.getAllowFlight();
}
@Override public void setFlight(boolean fly) {
this.player.setAllowFlight(fly);
}
@Override public void playMusic(Location location, int id) {
throw new UnsupportedOperationException("Not implemented yet: playMusic");
}
@Override public void kick(String message) {
player.kick(message);
}
@Override public void stopSpectating() {
// Do nothing
}
@Override public boolean isBanned() {
return this.player.isBanned();
}
}

View file

@ -1,563 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.util;
import cn.nukkit.plugin.Plugin;
import cn.nukkit.plugin.PluginDescription;
import cn.nukkit.utils.LogLevel;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.zip.GZIPOutputStream;
public class Metrics {
/**
* The current revision number.
*/
private static final int REVISION = 7;
/**
* The base url of the metrics domain.
*/
private static final String BASE_URL = "http://report.mcstats.org";
/**
* The url used to report a server's status.
*/
private static final String REPORT_URL = "/plugin/%s";
/**
* Interval of time to ping (in minutes).
*/
private static final int PING_INTERVAL = 15;
/**
* The plugin this metrics submits for.
*/
private final Plugin plugin;
/**
* All of the custom graphs to submit to metrics.
*/
private final Set<Graph> graphs = Collections.synchronizedSet(new HashSet<Graph>());
/**
* Unique server id.
*/
private final String guid;
/**
* Debug mode.
*/
private final boolean debug;
/**
* The scheduled task.
*/
private volatile int taskId = -1;
public Metrics(Plugin plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.plugin = plugin;
this.guid = UUID.randomUUID().toString();
this.debug = false;
}
/**
* GZip compress a string of bytes.
*
* @param input
* @return byte[] the file as a byte array
*/
public static byte[] gzip(String input) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) {
try {
gzos.close();
} catch (IOException ignore) {
}
}
}
return baos.toByteArray();
}
/**
* Appends a json encoded key/value pair to the given string builder.
*
* @param json
* @param key
* @param value
*/
private static void appendJSONPair(StringBuilder json, String key, String value) {
boolean isValueNumeric = false;
try {
if (value.equals("0") || !value.endsWith("0")) {
Double.parseDouble(value);
isValueNumeric = true;
}
} catch (NumberFormatException e) {
isValueNumeric = false;
}
if (json.charAt(json.length() - 1) != '{') {
json.append(',');
}
json.append(escapeJSON(key));
json.append(':');
if (isValueNumeric) {
json.append(value);
} else {
json.append(escapeJSON(value));
}
}
/**
* Escape a string to create a valid JSON string
*
* @param text
* @return String
*/
private static String escapeJSON(String text) {
StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
}
/**
* Encode text as UTF-8
*
* @param text the text to encode
* @return the encoded text, as UTF-8
*/
private static String urlEncode(String text) throws UnsupportedEncodingException {
return URLEncoder.encode(text, "UTF-8");
}
/**
* Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics
* website. Plotters can be added to the graph object returned.
*
* @param name The name of the graph
* @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given
*/
public Graph createGraph(String name) {
if (name == null) {
throw new IllegalArgumentException("Graph name cannot be null");
}
// Construct the graph object
Graph graph = new Graph(name);
// Now we can add our graph
this.graphs.add(graph);
// and return back
return graph;
}
/**
* Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend
*
* @param graph The name of the graph
*/
public void addGraph(Graph graph) {
if (graph == null) {
throw new IllegalArgumentException("Graph cannot be null");
}
this.graphs.add(graph);
}
/**
* Start measuring statistics. This will immediately create an async repeating task as the plugin and send the
* initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200
* ticks.
*
* @return True if statistics measuring is running, otherwise false.
*/
public boolean start() {
// Is metrics already running?
if (this.taskId != -1) {
return true;
}
// Begin hitting the server with glorious data
this.taskId = TaskManager.IMP.taskRepeatAsync(new Runnable() {
private boolean firstPost = true;
@Override public void run() {
try {
postPlugin(!this.firstPost);
// After the first post we set firstPost to
// false
// Each post thereafter will be a ping
this.firstPost = false;
} catch (IOException e) {
e.printStackTrace();
if (Metrics.this.debug) {
plugin.getLogger().log(LogLevel.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, PING_INTERVAL * 1200);
return true;
}
/**
* Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task.
*
* @throws java.io.IOException
*/
public void enable() {
// Enable Task, if it is not running
if (this.taskId == -1) {
start();
}
}
/**
* Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task.
*/
public void disable() {
// Disable Task, if it is running
if (this.taskId != -1) {
TaskManager.IMP.cancelTask(this.taskId);
this.taskId = -1;
}
}
/**
* Gets the File object of the config file that should be used to store
* data such as the GUID and opt-out status.
*
* @return the File object for the config file
*/
public File getConfigFile() {
// I believe the easiest way to get the base folder (e.g craftbukkit set
// via -P) for plugins to use
// is to abuse the plugin object we already have
// plugin.getDataFolder() => base/plugins/PluginA/
// pluginsFolder => base/plugins/
// The base is not necessarily relative to the startup directory.
File pluginsFolder = this.plugin.getDataFolder().getParentFile();
// return => base/plugins/PluginMetrics/config.yml
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
}
/**
* Generic method that posts a plugin to the metrics website.
*/
private void postPlugin(boolean isPing) throws IOException {
// Server software specific section
PluginDescription description = this.plugin.getDescription();
String pluginName = description.getName();
boolean onlineMode = false;
String pluginVersion = description.getVersion();
String serverVersion = plugin.getServer().getNukkitVersion();
int playersOnline = plugin.getServer().getOnlinePlayers().size();
// END server software specific section -- all code below does not use
// any code outside of this class / Java
// Construct the post data
StringBuilder json = new StringBuilder(1024);
json.append('{');
// The plugin's description file containing all of the plugin data such as name, version, author, etc
appendJSONPair(json, "guid", this.guid);
appendJSONPair(json, "plugin_version", pluginVersion);
appendJSONPair(json, "server_version", serverVersion);
appendJSONPair(json, "players_online", Integer.toString(playersOnline));
// New data as of R6
String osname = System.getProperty("os.name");
String osarch = System.getProperty("os.arch");
String osversion = System.getProperty("os.version");
String java_version = System.getProperty("java.version");
int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64")) {
osarch = "x86_64";
}
appendJSONPair(json, "osname", osname);
appendJSONPair(json, "osarch", osarch);
appendJSONPair(json, "osversion", osversion);
appendJSONPair(json, "cores", Integer.toString(coreCount));
appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0");
appendJSONPair(json, "java_version", java_version);
// If we're pinging, append it
if (isPing) {
appendJSONPair(json, "ping", "1");
}
if (!this.graphs.isEmpty()) {
synchronized (this.graphs) {
json.append(',');
json.append('"');
json.append("graphs");
json.append('"');
json.append(':');
json.append('{');
boolean firstGraph = true;
for (Graph graph : this.graphs) {
StringBuilder graphJson = new StringBuilder();
graphJson.append('{');
for (Plotter plotter : graph.getPlotters()) {
appendJSONPair(graphJson, plotter.getColumnName(),
Integer.toString(plotter.getValue()));
}
graphJson.append('}');
if (!firstGraph) {
json.append(',');
}
json.append(escapeJSON(graph.getName()));
json.append(':');
json.append(graphJson);
firstGraph = false;
}
json.append('}');
}
}
// close json
json.append('}');
// Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName)));
// Connect to the website
URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY);
} else {
connection = url.openConnection();
}
byte[] uncompressed = json.toString().getBytes();
byte[] compressed = gzip(json.toString());
// Headers
connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Content-Encoding", "gzip");
connection.addRequestProperty("Content-Length", Integer.toString(compressed.length));
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true);
if (this.debug) {
PlotSquared.debug("[Metrics] Prepared request for " + pluginName + " uncompressed="
+ uncompressed.length + " compressed=" + compressed.length);
}
try {
try (OutputStream os = connection.getOutputStream()) {
os.write(compressed);
os.flush();
}
String response;
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()))) {
response = reader.readLine();
if (this.debug) {
PlotSquared.debug("[Metrics] Response for " + pluginName + ": " + response);
}
}
if (response == null || response.startsWith("ERR") || response.startsWith("7")) {
if (response == null) {
response = "null";
} else if (response.startsWith("7")) {
response = response.substring(response.startsWith("7,") ? 2 : 1);
}
throw new IOException(response);
} else {
// Is this the first update this hour?
if ("1".equals(response) || response
.contains("This is your first update this hour")) {
synchronized (this.graphs) {
for (Graph graph : this.graphs) {
for (Plotter plotter : graph.getPlotters()) {
plotter.reset();
}
}
}
}
}
} catch (Exception e) {
if (this.debug) {
e.printStackTrace();
}
}
}
/**
* Check if mineshafter is present. If it is, we need to bypass it to send POST requests
*
* @return true if mineshafter is installed on the server
*/
private boolean isMineshafterPresent() {
try {
Class.forName("mineshafter.MineServer");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
/**
* Represents a custom graph on the website
*/
public static class Graph {
/**
* The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is
* rejected
*/
private final String name;
/**
* The set of plotters that are contained within this graph
*/
private final Set<Plotter> plotters = new LinkedHashSet<>();
private Graph(String name) {
this.name = name;
}
/**
* Gets the graph's name
*
* @return the Graph's name
*/
public String getName() {
return this.name;
}
/**
* Add a plotter to the graph, which will be used to plot entries
*
* @param plotter the plotter to add to the graph
*/
public void addPlotter(Plotter plotter) {
this.plotters.add(plotter);
}
/**
* Remove a plotter from the graph
*
* @param plotter the plotter to remove from the graph
*/
public void removePlotter(Plotter plotter) {
this.plotters.remove(plotter);
}
/**
* Gets an <b>unmodifiable</b> set of the plotter objects in the graph
*
* @return an unmodifiable {@link java.util.Set} of the plotter objects
*/
public Set<Plotter> getPlotters() {
return Collections.unmodifiableSet(this.plotters);
}
@Override public int hashCode() {
return this.name.hashCode();
}
@Override public boolean equals(Object object) {
if (!(object instanceof Graph)) {
return false;
}
Graph graph = (Graph) object;
return graph.name.equals(this.name);
}
/**
* Called when the server owner decides to opt-out of BukkitMetrics while the server is running.
*/
protected void onOptOut() {
}
}
/**
* Interface used to collect custom data for a plugin
*/
public abstract static class Plotter {
/**
* The plot's name
*/
private final String name;
/**
* Construct a plotter with the default plot name
*/
public Plotter() {
this("Default");
}
/**
* Construct a plotter with a specific plot name
*
* @param name the name of the plotter to use, which will show up on the website
*/
public Plotter(String name) {
this.name = name;
}
/**
* Get the current value for the plotted point. Since this function defers to an external function it may or may
* not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called
* from any thread so care should be taken when accessing resources that need to be synchronized.
*
* @return the current value for the point to be plotted.
*/
public abstract int getValue();
/**
* Get the column name for the plotted point
*
* @return the plotted point's column name
*/
public String getColumnName() {
return this.name;
}
/**
* Called after the website graphs have been updated
*/
public void reset() {
}
@Override public int hashCode() {
return getColumnName().hashCode();
}
@Override public boolean equals(Object object) {
if (!(object instanceof Plotter)) {
return false;
}
Plotter plotter = (Plotter) object;
return plotter.name.equals(this.name) && plotter.getValue() == getValue();
}
}
}

View file

@ -1,44 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.util;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.object.BlockVector2;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.util.ChunkManager;
public class NukkitChunkManager extends ChunkManager {
public NukkitChunkManager() {
PlotSquared.debug("Not implemented: NukkitChunkManager");
}
@Override public int[] countEntities(Plot plot) {
return new int[0];
}
@Override public boolean loadChunk(String world, BlockVector2 loc, boolean force) {
return true;
}
@Override public void unloadChunk(String world, BlockVector2 loc, boolean save, boolean safe) {
}
@Override
public boolean copyRegion(Location pos1, Location pos2, Location newPos, Runnable whenDone) {
return false;
}
@Override public boolean regenerateRegion(Location pos1, Location pos2, boolean ignoreAugment,
Runnable whenDone) {
return false;
}
@Override public void clearAllEntities(Location pos1, Location pos2) {
}
@Override public void swap(Location bot1, Location top1, Location bot2, Location top2,
Runnable whenDone) {
whenDone.run();
}
}

View file

@ -1,29 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.util;
import cn.nukkit.Player;
import cn.nukkit.command.Command;
import cn.nukkit.command.CommandSender;
import cn.nukkit.command.ConsoleCommandSender;
import cn.nukkit.command.RemoteConsoleCommandSender;
import com.github.intellectualsites.plotsquared.plot.commands.MainCommand;
import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer;
public class NukkitCommand extends Command {
public NukkitCommand(String cmd, String[] aliases) {
super(cmd, "Plot command", "/plot", aliases);
}
@Override
public boolean execute(CommandSender commandSender, String commandLabel, String[] args) {
if (commandSender instanceof Player) {
return MainCommand.onCommand(NukkitUtil.getPlayer((Player) commandSender), args);
}
if (commandSender instanceof ConsoleCommandSender
|| commandSender instanceof RemoteConsoleCommandSender) {
return MainCommand.onCommand(ConsolePlayer.getConsole(), args);
}
return false;
}
}

View file

@ -1,112 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.util;
import cn.nukkit.Player;
import cn.nukkit.event.Cancellable;
import cn.nukkit.event.Event;
import com.github.intellectualsites.plotsquared.nukkit.NukkitMain;
import com.github.intellectualsites.plotsquared.nukkit.events.*;
import com.github.intellectualsites.plotsquared.nukkit.object.NukkitPlayer;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.util.EventUtil;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.UUID;
public class NukkitEventUtil extends EventUtil {
private final NukkitMain plugin;
public NukkitEventUtil(NukkitMain plugin) {
this.plugin = plugin;
}
public Player getPlayer(PlotPlayer player) {
if (player instanceof NukkitPlayer) {
return ((NukkitPlayer) player).player;
}
return null;
}
public boolean callEvent(Event event) {
plugin.getServer().getPluginManager().callEvent(event);
return !(event instanceof Cancellable) || !event.isCancelled();
}
@Override public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) {
return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, auto));
}
@Override public boolean callTeleport(PlotPlayer player, Location from, Plot plot) {
return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot));
}
@Override public boolean callComponentSet(Plot plot, String component) {
return callEvent(new PlotComponentSetEvent(plot, component));
}
@Override public boolean callClear(Plot plot) {
return callEvent(new PlotClearEvent(plot));
}
@Override public void callDelete(Plot plot) {
callEvent(new PlotDeleteEvent(plot));
}
@Override public boolean callFlagAdd(Flag flag, Plot plot) {
return callEvent(new PlotFlagAddEvent(flag, plot));
}
@Override public boolean callFlagRemove(Flag<?> flag, Plot plot, Object value) {
return callEvent(new PlotFlagRemoveEvent(flag, plot));
}
@Override public boolean callMerge(Plot plot, ArrayList<PlotId> plots) {
return callEvent(new PlotMergeEvent(NukkitUtil.getWorld(plot.getWorldName()), plot, plots));
}
@Override public boolean callUnlink(PlotArea area, ArrayList<PlotId> plots) {
return callEvent(new PlotUnlinkEvent(NukkitUtil.getWorld(area.getWorldName()), area, plots));
}
@Override public void callEntry(PlotPlayer player, Plot plot) {
callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot));
}
@Override public void callLeave(PlotPlayer player, Plot plot) {
callEvent(new PlayerLeavePlotEvent(getPlayer(player), plot));
}
@Override public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, added));
}
@Override public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added));
}
@Override public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added));
}
@Override
public boolean callOwnerChange(PlotPlayer initiator, Plot plot, UUID oldOwner, UUID newOwner,
boolean hasOldOwner) {
return callEvent(
new PlotChangeOwnerEvent(getPlayer(initiator), plot, oldOwner, newOwner, hasOldOwner));
}
@Override public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) {
return callEvent(new ClusterFlagRemoveEvent(flag, cluster));
}
@Override @Nullable public Rating callRating(PlotPlayer player, Plot plot, Rating rating) {
PlotRateEvent event = new PlotRateEvent(player, rating, plot);
plugin.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return null;
}
return event.getRating();
}
}

View file

@ -1,19 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.util;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils;
import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper;
import com.github.intellectualsites.plotsquared.plot.object.RunnableVal;
import com.github.intellectualsites.plotsquared.plot.util.expiry.PlotAnalysis;
public class NukkitHybridUtils extends HybridUtils {
public NukkitHybridUtils() {
PlotSquared.debug("Not implemented: NukkitHybridUtils");
}
@Override public void analyzeRegion(final String world, final RegionWrapper region,
final RunnableVal<PlotAnalysis> whenDone) {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
}

View file

@ -1,72 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.util;
import cn.nukkit.inventory.PlayerInventory;
import cn.nukkit.item.Item;
import com.github.intellectualsites.plotsquared.nukkit.object.NukkitPlayer;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.object.PlotInventory;
import com.github.intellectualsites.plotsquared.plot.object.PlotItemStack;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.InventoryUtil;
public class NukkitInventoryUtil extends InventoryUtil {
public NukkitInventoryUtil() {
PlotSquared.debug("Not implemented: NukkitInventoryUtil");
}
public static Item getItem(PlotItemStack item) {
if (item == null) {
return null;
}
Item stack = new Item(item.id, item.amount, item.data);
if (item.name != null) {
stack.setCustomName(C.color(item.name));
}
if (item.lore != null) {
// TODO not implemented
}
return stack;
}
@Override public void open(PlotInventory inv) {
return; // TODO
}
@Override public void close(PlotInventory inv) {
return; // TODO
}
@Override public void setItem(PlotInventory inv, int index, PlotItemStack item) {
return; // TODO
}
public PlotItemStack getItem(Item item) {
if (item == null) {
return null;
}
int id = item.getId();
int data = item.getDamage();
int amount = item.count;
String name = item.getCustomName();
if (name.length() == 0) {
name = null;
}
return new PlotItemStack(id, (short) data, amount, name);
}
@Override public PlotItemStack[] getItems(PlotPlayer player) {
NukkitPlayer bp = (NukkitPlayer) player;
PlayerInventory inv = bp.player.getInventory();
PlotItemStack[] items = new PlotItemStack[36];
for (int i = 0; i < 36; i++) {
items[i] = getItem(inv.getItem(i));
}
return items;
}
@Override public boolean isOpen(PlotInventory inv) {
return false; // TODO
}
}

View file

@ -1,177 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.util;
import cn.nukkit.block.Block;
import cn.nukkit.level.Level;
import cn.nukkit.level.format.generic.BaseFullChunk;
import cn.nukkit.math.Vector3;
import com.github.intellectualsites.plotsquared.jnbt.*;
import com.github.intellectualsites.plotsquared.nukkit.NukkitMain;
import com.github.intellectualsites.plotsquared.plot.object.BlockVector2;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper;
import com.github.intellectualsites.plotsquared.plot.object.RunnableVal;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue;
import java.io.IOException;
/**
* Schematic Handler.
*/
public class NukkitSchematicHandler extends SchematicHandler {
private final NukkitMain plugin;
public NukkitSchematicHandler(NukkitMain plugin) {
this.plugin = plugin;
}
@Override public void getCompoundTag(final String world, final Set<RegionWrapper> regions,
final RunnableVal<CompoundTag> whenDone) {
// async
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
// Main positions
Location[] corners = MainUtil.getCorners(world, regions);
final Location bot = corners[0];
Location top = corners[1];
final int width = top.getX() - bot.getX() + 1;
int height = top.getY() - bot.getY() + 1;
final int length = top.getZ() - bot.getZ() + 1;
// Main Schematic tag
final HashMap<String, Tag> schematic = new HashMap<>();
schematic.put("Width", new ShortTag("Width", (short) width));
schematic.put("Length", new ShortTag("Length", (short) length));
schematic.put("Height", new ShortTag("Height", (short) height));
schematic.put("Materials", new StringTag("Materials", "Alpha"));
schematic.put("WEOriginX", new IntTag("WEOriginX", 0));
schematic.put("WEOriginY", new IntTag("WEOriginY", 0));
schematic.put("WEOriginZ", new IntTag("WEOriginZ", 0));
schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0));
schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0));
schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0));
// Arrays of data types
final List<CompoundTag> tileEntities = new ArrayList<>();
final byte[] blocks = new byte[width * height * length];
final byte[] blockData = new byte[width * height * length];
// Queue
final ArrayDeque<RegionWrapper> queue = new ArrayDeque<>(regions);
TaskManager.runTask(new Runnable() {
@Override public void run() {
if (queue.isEmpty()) {
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
schematic.put("Blocks", new ByteArrayTag("Blocks", blocks));
schematic.put("Data", new ByteArrayTag("Data", blockData));
schematic.put("Entities",
new ListTag("Entities", CompoundTag.class,
new ArrayList<>()));
schematic.put("TileEntities",
new ListTag("TileEntities", CompoundTag.class,
tileEntities));
whenDone.value = new CompoundTag("Schematic", schematic);
TaskManager.runTask(whenDone);
System.gc();
System.gc();
}
});
return;
}
final Runnable regionTask = this;
RegionWrapper region = queue.poll();
Location pos1 = new Location(world, region.minX, region.minY, region.minZ);
Location pos2 = new Location(world, region.maxX, region.maxY, region.maxZ);
final int bx = bot.getX();
final int bz = bot.getZ();
final int p1x = pos1.getX();
final int p1z = pos1.getZ();
final int p2x = pos2.getX();
final int p2z = pos2.getZ();
final int bcx = p1x >> 4;
final int bcz = p1z >> 4;
final int tcx = p2x >> 4;
final int tcz = p2z >> 4;
final int sy = pos1.getY();
final int ey = pos2.getY();
// Generate list of chunks
final ArrayList<BlockVector2> chunks = new ArrayList<>();
for (int x = bcx; x <= tcx; x++) {
for (int z = bcz; z <= tcz; z++) {
chunks.add(BlockVector2.at(x, z));
}
}
final Level worldObj = plugin.getServer().getLevelByName(world);
// Main thread
final Vector3 mutable = new Vector3();
TaskManager.runTask(new Runnable() {
@Override public void run() {
long start = System.currentTimeMillis();
while (!chunks.isEmpty()
&& System.currentTimeMillis() - start < 20) {
// save schematics
BlockVector2 chunk = chunks.remove(0);
BaseFullChunk bc = worldObj.getChunk(chunk.x, chunk.z);
try {
bc.load(false);
} catch (IOException e) {
continue;
}
int X = chunk.x;
int Z = chunk.z;
int xxb = X << 4;
int zzb = Z << 4;
int xxt = xxb + 15;
int zzt = zzb + 15;
if (X == bcx) {
xxb = p1x;
}
if (X == tcx) {
xxt = p2x;
}
if (Z == bcz) {
zzb = p1z;
}
if (Z == tcz) {
zzt = p2z;
}
for (int y = sy; y <= Math.min(255, ey); y++) {
int ry = y - sy;
int i1 = ry * width * length;
for (int z = zzb; z <= zzt; z++) {
int rz = z - bz;
int i2 = i1 + rz * width;
for (int x = xxb; x <= xxt; x++) {
int rx = x - bx;
int index = i2 + rx;
mutable.x = x;
mutable.y = y;
mutable.z = z;
Block block = worldObj.getBlock(mutable);
blocks[index] = (byte) block.getId();
blockData[index] = (byte) block.getDamage();
}
}
}
}
if (!chunks.isEmpty()) {
TaskManager.runTaskLater(this, 1);
} else {
regionTask.run();
}
}
});
}
});
}
});
}
@Override
public boolean restoreTile(LocalBlockQueue queue, CompoundTag ct, int x, int y, int z) {
return false;
}
}

View file

@ -1,181 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.util;
import cn.nukkit.level.Level;
import cn.nukkit.level.generator.Generator;
import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection;
import com.github.intellectualsites.plotsquared.nukkit.NukkitMain;
import com.github.intellectualsites.plotsquared.nukkit.generator.NukkitPlotGenerator;
import com.github.intellectualsites.plotsquared.nukkit.util.block.NukkitHybridGen;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.SetupObject;
import com.github.intellectualsites.plotsquared.plot.util.SetupUtils;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Objects;
public class NukkitSetupUtils extends SetupUtils {
private final NukkitMain plugin;
public NukkitSetupUtils(NukkitMain plugin) {
this.plugin = plugin;
Generator.addGenerator(NukkitHybridGen.class, "PlotSquared", 1);
}
@Override public void unload(String world, boolean save) {
plugin.getServer().unloadLevel(plugin.getServer().getLevelByName(world), save);
}
@Override public void updateGenerators() {
if (!SetupUtils.generators.isEmpty()) {
return;
}
String testWorld = "CheckingPlotSquaredGenerator";
HashMap<String, Object> map = new HashMap<>();
map.put("world", testWorld);
map.put("plot-generator", PlotSquared.get().IMP.getDefaultGenerator());
NukkitPlotGenerator gen = new NukkitPlotGenerator(map);
SetupUtils.generators.put(PlotSquared.imp().getPluginName(), gen);
}
@Override public String setupWorld(SetupObject object) {
SetupUtils.manager.updateGenerators();
ConfigurationNode[] steps = object.step == null ? new ConfigurationNode[0] : object.step;
String world = object.world;
int type = object.type;
String worldPath = "worlds." + object.world;
if (!PlotSquared.get().worlds.contains(worldPath)) {
PlotSquared.get().worlds.createSection(worldPath);
}
ConfigurationSection worldSection =
PlotSquared.get().worlds.getConfigurationSection(worldPath);
switch (type) {
case 2: {
if (object.id != null) {
String areaName = object.id + "-" + object.min + "-" + object.max;
String areaPath = "areas." + areaName;
if (!worldSection.contains(areaPath)) {
worldSection.createSection(areaPath);
}
ConfigurationSection areaSection =
worldSection.getConfigurationSection(areaPath);
HashMap<String, Object> options = new HashMap<>();
for (ConfigurationNode step : steps) {
options.put(step.getConstant(), step.getValue());
}
options.put("generator.type", object.type);
options.put("generator.terrain", object.terrain);
options.put("generator.plugin", object.plotManager);
if (object.setupGenerator != null && !object.setupGenerator
.equals(object.plotManager)) {
options.put("generator.init", object.setupGenerator);
}
for (Entry<String, Object> entry : options.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (worldSection.contains(key)) {
Object current = worldSection.get(key);
if (!Objects.equals(value, current)) {
areaSection.set(key, value);
}
} else {
worldSection.set(key, value);
}
}
}
GeneratorWrapper<?> gen = SetupUtils.generators.get(object.setupGenerator);
if (gen != null && gen.isFull()) {
object.setupGenerator = null;
}
break;
}
case 1:
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
PlotSquared.get().worlds.set("worlds." + world + ".generator.type", object.type);
PlotSquared.get().worlds
.set("worlds." + world + ".generator.terrain", object.terrain);
PlotSquared.get().worlds
.set("worlds." + world + ".generator.plugin", object.plotManager);
if (object.setupGenerator != null && !object.setupGenerator
.equals(object.plotManager)) {
PlotSquared.get().worlds
.set("worlds." + world + ".generator.init", object.setupGenerator);
}
GeneratorWrapper<?> gen = SetupUtils.generators.get(object.setupGenerator);
if (gen != null && gen.isFull()) {
object.setupGenerator = null;
}
break;
case 0:
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
break;
}
try {
PlotSquared.get().worlds.save(PlotSquared.get().worldsFile);
} catch (IOException e) {
e.printStackTrace();
}
if (object.setupGenerator != null) {
HashMap<String, Object> map = new HashMap<>();
map.put("world", object.world);
map.put("plot-generator", PlotSquared.get().IMP.getDefaultGenerator());
if (!plugin.getServer()
.generateLevel(object.world, object.world.hashCode(), NukkitHybridGen.class, map)) {
plugin.getServer().loadLevel(object.world);
}
try {
// File nukkitFile = new File("nukkit.yml");
// YamlConfiguration nukkitYml = YamlConfiguration.loadConfiguration(nukkitFile);
// if (!nukkitYml.contains("worlds." + object.world + ".generator")) {
// nukkitYml.set("worlds." + object.world + ".generator", object.setupGenerator);
// nukkitYml.save(nukkitFile);
// }
} catch (Throwable e) {
e.printStackTrace();
}
} else {
if (!plugin.getServer().generateLevel(object.world, object.world.hashCode())) {
plugin.getServer().loadLevel(object.world);
}
}
return object.world;
}
@Override public String getGenerator(PlotArea plotArea) {
if (SetupUtils.generators.isEmpty()) {
updateGenerators();
}
Level world = NukkitUtil.getWorld(plotArea.getWorldName());
if (world == null) {
return null;
}
try {
Field field = Level.class.getDeclaredField("generatorInstance");
field.setAccessible(true);
Generator generator = (Generator) field.get(world);
if (!(generator instanceof NukkitPlotGenerator)) {
return null;
}
for (Entry<String, GeneratorWrapper<?>> entry : SetupUtils.generators.entrySet()) {
GeneratorWrapper<?> current = entry.getValue();
if (current.equals(generator)) {
return entry.getKey();
}
}
return PlotSquared.imp().getPluginName();
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
}

View file

@ -1,63 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.util;
import cn.nukkit.scheduler.TaskHandler;
import com.github.intellectualsites.plotsquared.nukkit.NukkitMain;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class NukkitTaskManager extends TaskManager {
private final NukkitMain plugin;
private AtomicInteger index = new AtomicInteger(0);
private HashMap<Integer, Integer> tasks = new HashMap<>();
public NukkitTaskManager(NukkitMain bukkitMain) {
this.plugin = bukkitMain;
}
@Override public int taskRepeat(Runnable r, int interval) {
TaskHandler task =
this.plugin.getServer().getScheduler().scheduleRepeatingTask(r, interval, false);
return task.getTaskId();
}
@SuppressWarnings("deprecation") @Override
public int taskRepeatAsync(Runnable r, int interval) {
TaskHandler task =
this.plugin.getServer().getScheduler().scheduleRepeatingTask(r, interval, true);
return task.getTaskId();
}
@Override public void taskAsync(Runnable r) {
if (r == null) {
return;
}
this.plugin.getServer().getScheduler().scheduleTask(r, true);
}
@Override public void task(Runnable r) {
if (r == null) {
return;
}
this.plugin.getServer().getScheduler().scheduleTask(r, false);
}
@Override public void taskLater(Runnable r, int delay) {
if (r == null) {
return;
}
this.plugin.getServer().getScheduler().scheduleDelayedTask(r, delay);
}
@Override public void taskLaterAsync(Runnable r, int delay) {
this.plugin.getServer().getScheduler().scheduleDelayedTask(r, delay, true);
}
@Override public void cancelTask(int task) {
if (task != -1) {
this.plugin.getServer().getScheduler().cancelTask(task);
}
}
}

View file

@ -1,14 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.util;
import cn.nukkit.Player;
import com.github.intellectualsites.plotsquared.nukkit.object.NukkitPlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.AbstractTitle;
public class NukkitTitleUtil extends AbstractTitle {
@Override
public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) {
Player plr = ((NukkitPlayer) player).player;
plr.sendTitle(head, sub, in, delay, out);
}
}

View file

@ -1,279 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.util;
import cn.nukkit.OfflinePlayer;
import cn.nukkit.Player;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockWallSign;
import cn.nukkit.blockentity.BlockEntity;
import cn.nukkit.blockentity.BlockEntitySign;
import cn.nukkit.entity.Entity;
import cn.nukkit.item.Item;
import cn.nukkit.level.Level;
import cn.nukkit.level.Position;
import cn.nukkit.level.biome.Biome;
import cn.nukkit.level.biome.EnumBiome;
import cn.nukkit.math.Vector3;
import com.github.intellectualsites.plotsquared.nukkit.NukkitMain;
import com.github.intellectualsites.plotsquared.nukkit.object.NukkitPlayer;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.PlotBlock;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper;
import com.github.intellectualsites.plotsquared.plot.object.schematic.PlotItem;
import java.lang.reflect.Field;
import java.util.ArrayList;
public class NukkitUtil extends WorldUtil {
private static String lastString = null;
private static Level lastWorld = null;
private static Player lastPlayer = null;
private static PlotPlayer lastPlotPlayer = null;
private static NukkitMain plugin;
public NukkitUtil(NukkitMain plugin) {
this.plugin = plugin;
}
public static void removePlayer(String player) {
lastPlayer = null;
lastPlotPlayer = null;
}
public static PlotPlayer getPlayer(OfflinePlayer op) {
if (op.isOnline()) {
return getPlayer(op.getPlayer());
}
return null;
}
public static PlotPlayer getPlayer(Player player) {
if (player == lastPlayer) {
return lastPlotPlayer;
}
String name = player.getName();
PlotPlayer plotPlayer = UUIDHandler.getPlayer(name);
if (plotPlayer != null) {
return plotPlayer;
}
lastPlotPlayer = new NukkitPlayer(player);
UUIDHandler.getPlayers().put(name, lastPlotPlayer);
lastPlayer = player;
return lastPlotPlayer;
}
public static Location getLocation(cn.nukkit.level.Location location) {
return new Location(location.getLevel().getName(), MathMan.roundInt(location.getX()),
MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()));
}
public static Location getLocation(cn.nukkit.level.Position location) {
return new Location(location.getLevel().getName(), MathMan.roundInt(location.getX()),
MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()));
}
public static cn.nukkit.level.Location getLocation(Location location) {
return new cn.nukkit.level.Location(location.getX(), location.getY(), location.getZ(), 0, 0,
getWorld(location.getWorld()));
}
public static Level getWorld(String string) {
if (StringMan.isEqual(string, lastString)) {
if (lastWorld != null) {
return lastWorld;
}
}
Level world = plugin.getServer().getLevelByName(string);
lastString = string;
lastWorld = world;
return world;
}
public static String getWorld(Entity entity) {
return entity.getLevel().getName();
}
public static Entity[] getEntities(String worldName) {
return getWorld(worldName).getEntities();
}
public static Location getLocation(Entity entity) {
cn.nukkit.level.Location location = entity.getLocation();
String world = location.getLevel().getName();
return new Location(world, location.getFloorX(), location.getFloorY(),
location.getFloorZ());
}
public static Location getLocationFull(Entity entity) {
cn.nukkit.level.Location location = entity.getLocation();
return new Location(location.getLevel().getName(), MathMan.roundInt(location.getX()),
MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()),
(float) location.getYaw(), (float) location.getPitch());
}
@Override public boolean isWorld(String worldName) {
return getWorld(worldName) != null;
}
@Override public String getBiome(String world, int x, int z) {
int id = getWorld(world).getBiomeId(x, z);
return EnumBiome.getBiome(id).getName();
}
@Override public void setSign(String worldName, int x, int y, int z, String[] lines) {
Level world = getWorld(worldName);
BlockWallSign sign = new BlockWallSign(0);
Vector3 pos = new Vector3(x, y, z);
world.setBlock(pos, sign);
BlockEntity tile = world.getBlockEntity(pos);
if (tile instanceof BlockEntitySign) {
((BlockEntitySign) tile).setText(lines[0], lines[1], lines[2], lines[3]);
tile.scheduleUpdate();
}
}
@Override public String[] getSign(Location location) {
Level world = getWorld(location.getWorld());
Vector3 pos = new Vector3(location.getX(), location.getY(), location.getZ());
BlockEntity tile = world.getBlockEntity(pos);
if (tile instanceof BlockEntitySign) {
return ((BlockEntitySign) tile).getText();
}
return null;
}
@Override public Location getSpawn(PlotPlayer player) {
return getLocation(((NukkitPlayer) player).player.getSpawn());
}
@Override public Location getSpawn(String world) {
Position loc = getWorld(world).getSpawnLocation();
return new Location(world, loc.getFloorX(), loc.getFloorY(), loc.getFloorZ(), 0, 0);
}
@Override public void setSpawn(Location location) {
Level world = getWorld(location.getWorld());
if (world != null) {
world.setSpawnLocation(new Vector3(location.getX(), location.getY(), location.getZ()));
}
}
@Override public void saveWorld(String worldName) {
Level world = getWorld(worldName);
if (world != null) {
world.save();
}
}
@Override public int getHighestBlock(String world, int x, int z) {
return getWorld(world).getHeightMap(x, z);
}
@Override public int getBiomeFromString(String biomeString) {
try {
Biome biome = EnumBiome.getBiome(biomeString.toUpperCase());
return biome.getId();
} catch (Throwable ignored) {
return -1;
}
}
@Override public String[] getBiomeList() {
ArrayList<String> biomes = new ArrayList<>();
for (Field field : Biome.class.getDeclaredFields()) {
if (field.getName().equals(field.getName().toUpperCase())) {
biomes.add(field.getName());
}
}
return biomes.toArray(new String[biomes.size()]);
}
@Override public boolean addItems(String worldName, PlotItem items) {
return false;
}
@Override public boolean isBlockSolid(PlotBlock block) {
try {
Item item = Item.get(block.id, (int) block.data);
return (item != null && item.canBePlaced() && !Block.transparent[item.getId()]
&& Block.solid[item.getId()]);
} catch (Exception ignored) {
ignored.printStackTrace();
return false;
}
}
@Override public String getClosestMatchingName(PlotBlock block) {
try {
return Item.get(block.id, (int) block.data).getName();
} catch (Exception ignored) {
return null;
}
}
@Override public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) {
try {
Item item = Item.fromString(name);
return new StringComparison<PlotBlock>().new ComparisonResult(0,
PlotBlock.get(item.getId(), item.getDamage()));
} catch (IllegalArgumentException ignored) {
}
try {
byte data;
String[] split = name.split(":");
if (split.length == 2) {
data = Byte.parseByte(split[1]);
name = split[0];
} else {
data = 0;
}
double match;
short id;
if (MathMan.isInteger(split[0])) {
id = Short.parseShort(split[0]);
match = 0;
} else {
StringComparison<Item>.ComparisonResult comparison =
new StringComparison<>(name, Item.getCreativeItems()).getBestMatchAdvanced();
match = comparison.match;
id = (short) comparison.best.getId();
}
PlotBlock block = PlotBlock.get(id, data);
StringComparison<PlotBlock> outer = new StringComparison<>();
return outer.new ComparisonResult(match, block);
} catch (NumberFormatException ignored) {
}
return null;
}
@Override public void setBiomes(String worldName, RegionWrapper region, String biomeString) {
Level world = getWorld(worldName);
try {
int biome = (int) Biome.class.getDeclaredField(biomeString.toUpperCase()).get(null);
for (int x = region.minX; x <= region.maxX; x++) {
for (int z = region.minZ; z <= region.maxZ; z++) {
world.setBiomeId(x, z, (byte) biome);
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
@Override public PlotBlock getBlock(Location location) {
Level world = getWorld(location.getWorld());
int id = world.getBlockIdAt(location.getX(), location.getY(), location.getZ());
if (id == 0) {
return PlotBlock.get(0, 0);
}
int data = world.getBlockDataAt(location.getX(), location.getY(), location.getZ());
return PlotBlock.get(id, data);
}
@Override public String getMainWorld() {
return plugin.getServer().getDefaultLevel().getName();
}
}

View file

@ -1,33 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.util.block;
import com.sk89q.worldedit.math.BlockVector2;
import cn.nukkit.level.Level;
import com.github.intellectualsites.plotsquared.nukkit.NukkitMain;
import com.github.intellectualsites.plotsquared.nukkit.generator.NukkitPlotGenerator;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import java.util.Map;
public class NukkitHybridGen extends NukkitPlotGenerator {
public NukkitHybridGen(Map<String, Object> settings) {
super(defaultSettings(settings));
}
private static Map<String, Object> defaultSettings(Map<String, Object> existing) {
if (!existing.containsKey("world")) {
Map<Integer, Level> levels =
((NukkitMain) PlotSquared.get().IMP).getServer().getLevels();
int max = -1;
for (Map.Entry<Integer, Level> entry : levels.entrySet()) {
int id = entry.getKey();
if (id > max) {
max = id;
existing.put("world", entry.getValue().getName());
}
}
}
existing.put("plot-generator", PlotSquared.get().IMP.getDefaultGenerator());
return existing;
}
}

View file

@ -1,117 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.util.block;
import com.sk89q.worldedit.math.BlockVector2;
import cn.nukkit.block.Block;
import cn.nukkit.level.Level;
import cn.nukkit.level.biome.EnumBiome;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.level.format.generic.BaseFullChunk;
import cn.nukkit.math.Vector3;
import com.github.intellectualsites.plotsquared.nukkit.NukkitMain;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.object.PlotBlock;
import com.github.intellectualsites.plotsquared.plot.util.block.BasicLocalBlockQueue;
public class NukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
private final Level level;
private Vector3 mutable;
public NukkitLocalQueue(String world) {
super(world);
this.level = ((NukkitMain) PlotSquared.get().IMP).getServer().getLevelByName(world);
}
@Override public LocalChunk<T> getLocalChunk(int x, int z) {
return (LocalChunk<T>) new BasicLocalChunk(this, x, z) {
// Custom stuff?
};
}
@Override public void optimize() {
}
@Override public PlotBlock getBlock(int x, int y, int z) {
Block block = level.getBlock(getMut(x, y, z));
if (block == null) {
return PlotBlock.get(0, 0);
}
int id = block.getId();
if (id == 0) {
return PlotBlock.get(0, 0);
}
return PlotBlock.get(id, block.getDamage());
}
@Override public void refreshChunk(int x, int z) {
}
@Override public void fixChunkLighting(int x, int z) {
// Do nothing
}
@Override public final void regenChunk(int x, int z) {
level.regenerateChunk(x, z);
}
@Override public final void setComponents(LocalChunk<T> lc) {
setBlocks(lc);
setBiomes(lc);
}
public BaseFullChunk getChunk(int x, int z) {
return level.getChunk(x, z);
}
private Vector3 getMut(int x, int y, int z) {
mutable.x = x;
mutable.y = y;
mutable.z = z;
return mutable;
}
public void setBlocks(LocalChunk<T> lc) {
FullChunk chunk = level.getChunk(lc.getX(), lc.getZ(), true);
for (int layer = 0; layer < lc.blocks.length; layer++) {
PlotBlock[] blocksLayer = (PlotBlock[]) lc.blocks[layer];
if (blocksLayer != null) {
int by = layer << 4;
int j = 0;
for (int y = by; y < by + 16; y++) {
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++, j++) {
PlotBlock block = blocksLayer[j];
if (block != null) {
chunk.setBlock(x, y, z, (int) block.id, (int) block.data);
}
}
}
}
}
}
}
public void setBiomes(LocalChunk<T> lc) {
if (lc.biomes != null) {
int bx = lc.getX() << 4;
int bz = lc.getX() << 4;
String last = null;
int biome = -1;
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) {
biome = EnumBiome.getBiome(biomeStr.toUpperCase()).getId();
level.setBiomeId(bx + x, bz + y, (byte) biome);
}
}
}
}
}
}
}

View file

@ -1,84 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.util.block;
import com.sk89q.worldedit.math.BlockVector2;
import cn.nukkit.level.biome.Biome;
import cn.nukkit.level.biome.EnumBiome;
import cn.nukkit.level.format.generic.BaseFullChunk;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.PlotBlock;
import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue;
public class NukkitWrappedChunk extends ScopedLocalBlockQueue {
private final String world;
private BaseFullChunk chunk;
public NukkitWrappedChunk(String world, BaseFullChunk chunk) {
super(null, new Location(null, 0, 0, 0), new Location(null, 15, 127, 15));
this.world = world;
init(chunk);
}
public void init(BaseFullChunk chunk) {
this.chunk = chunk;
}
@Override public boolean setBlock(int x, int y, int z, int id, int data) {
chunk.setBlock(x, y, z, id, data);
return true;
}
@Override public PlotBlock getBlock(int x, int y, int z) {
int id = chunk.getBlockId(x, y, z);
if (id == 0) {
return PlotBlock.get(0, 0);
}
int data = chunk.getBlockData(x, y, z);
return PlotBlock.get(id, data);
}
@Override public boolean setBiome(int x, int z, String biome) {
Biome b = EnumBiome.getBiome(biome);
int id = b.getId();
chunk.setBiomeId(x, z, id);
return true;
}
@Override public void fillBiome(String biome) {
Biome b = EnumBiome.getBiome(biome);
int id = b.getId();
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
chunk.setBiomeId(x, z, id);
}
}
}
@Override public String getWorld() {
return world;
}
public int getX() {
return chunk.getX();
}
public int getZ() {
return chunk.getZ();
}
@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 NukkitWrappedChunk clone() {
return new NukkitWrappedChunk(world, chunk);
}
public NukkitWrappedChunk shallowClone() {
return new NukkitWrappedChunk(world, chunk);
}
}

View file

@ -1,11 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.uuid;
import java.io.File;
import java.io.FilenameFilter;
public class DatFileFilter implements FilenameFilter {
@Override public boolean accept(File dir, String name) {
return name.endsWith(".dat");
}
}

View file

@ -1,61 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.uuid;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.object.RunnableVal;
import com.github.intellectualsites.plotsquared.plot.object.StringWrapper;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.util.UUIDHandlerImplementation;
import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager;
import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper;
import com.google.common.collect.HashBiMap;
import java.io.File;
import java.util.HashMap;
import java.util.UUID;
public class FileUUIDHandler extends UUIDHandlerImplementation {
public FileUUIDHandler(UUIDWrapper wrapper) {
super(wrapper);
}
@Override public boolean startCaching(Runnable whenDone) {
return super.startCaching(whenDone) && cache(whenDone);
}
public boolean cache(final Runnable whenDone) {
final File container = new File("players");
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
PlotSquared.debug(C.PREFIX + "&6Starting player data caching for: " + container);
HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>());
for (File file : container.listFiles(new DatFileFilter())) {
String fileName = file.getName();
String name = fileName.substring(0, fileName.length() - 4);
UUID uuid = uuidWrapper.getUUID(name);
toAdd.put(new StringWrapper(name), uuid);
long last = file.lastModified();
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
}
}
add(toAdd);
if (whenDone != null) {
whenDone.run();
}
}
});
return true;
}
@Override public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name);
TaskManager.runTask(ifFetch);
}
});
}
}

View file

@ -1,39 +0,0 @@
package com.github.intellectualsites.plotsquared.nukkit.uuid;
import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper;
import com.google.common.base.Charsets;
import java.util.UUID;
public class LowerOfflineUUIDWrapper extends UUIDWrapper {
@Override public UUID getUUID(PlotPlayer player) {
return UUID.nameUUIDFromBytes(
("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override public UUID getUUID(OfflinePlotPlayer player) {
return UUID.nameUUIDFromBytes(
("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override public UUID getUUID(String name) {
return UUID
.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override public OfflinePlotPlayer getOfflinePlayer(UUID uuid) {
return null;
}
@Override public OfflinePlotPlayer getOfflinePlayer(String name) {
return null;
}
@Override public OfflinePlotPlayer[] getOfflinePlayers() {
return new OfflinePlotPlayer[0];
}
}

View file

@ -1,153 +0,0 @@
name: "${name}"
version: "${version}"
author: Empire92
api: ["1.0.0"]
main: NukkitMain
load: STARTUP
permissions:
plots.use:
default: true
plots.permpack.basicflags:
default: op
children:
plots.set.flag: true
plots.flag: true
plots.flag.add: true
plots.flag.remove: true
plots.flag.list: true
plots.flag.info: true
plots.set.flag.titles.*: true
plots.set.flag.greeting.*: true
plots.set.flag.farewell.*: true
plots.set.flag.notify-enter.*: true
plots.set.flag.notify-leave.*: true
plots.set.flag.feed.*: true
plots.set.flag.heal.*: true
plots.set.flag.invincible.*: true
plots.set.flag.instabreak.*: true
plots.set.flag.fly.*: true
plots.set.flag.gamemode: true
plots.set.flag.gamemode.creative: true
plots.set.flag.gamemode.survival: true
plots.set.flag.gamemode.adventure: true
plots.set.flag.time.*: true
plots.set.flag.weather.*: true
plots.set.flag.music.*: true
plots.set.flag.disable-physics.*: true
plots.set.flag.pve.*: true
plots.set.flag.pvp.*: true
plots.set.flag.explosion.*: true
plots.set.flag.hostile-interact.*: true
plots.set.flag.hostile-attack.*: true
plots.set.flag.player-interact.*: true
plots.set.flag.animal-interact.*: true
plots.set.flag.animal-attack.*: true
plots.set.flag.tamed-interact.*: true
plots.set.flag.tamed-attack.*: true
plots.set.flag.misc-interact.*: true
plots.set.flag.hanging-place.*: true
plots.set.flag.hanging-break.*: true
plots.set.flag.vehicle-use.*: true
plots.set.flag.vehicle-place.*: true
plots.set.flag.vehicle-break.*: true
plots.set.flag.player-interact.*: true
plots.set.flag.place.*: true
plots.set.flag.break.*: true
plots.set.flag.use.*: true
plots.set.flag.forcefield.*: true
plots.set.flag.price.*: true
plots.set.flag.no-worldedit.*: true
plots.permpack.basicinbox:
default: op
children:
comments.notifications.enabled : true
plots.inbox.read.public: true
plots.inbox.modify.public: true
plots.inbox.modify.public: true
plots.inbox.write.public: true
plots.inbox.read.public: true
plots.inbox.read.report: true
plots.inbox.write.report: true
plots.inbox.read.report: true
plots.inbox.read.owner: true
plots.inbox.modify.owner: true
plots.inbox.write.owner: true
plots.inbox.read.owner: true
plots.comment: true
plots.inbox: true
plots.permpack.wilderness:
default: op
children:
plots.admin.interact.unowned: true
plots.admin.destroy.unowned: true
plots.admin.build.unowned: true
plots.projectile.unowned: true
plots.admin.vehicle.break.unowned: true
plots.admin.pve.unowned: true
plots.permpack.basic:
default: op
children:
plots.use: true
plots.info: true
plots.claim: true
plots.auto: true
plots.home: true
plots.clear: true
plots.delete: true
plots.music: true
plots.list: true
plots.list.mine: true
plots.list.shared: true
plots.list.world: true
plots.list.all: true
plots.list.forsale: true
plots.list.unowned: true
plots.list.unknown: true
plots.set: true
plots.visit: true
plots.visit.owned: true
plots.visit.shared: true
plots.set.flag: true
plots.flag.add: true
plots.flag.remove: true
plots.flag.list: true
plots.flag.info: true
plots.flag: true
plots.buy: true
plots.chat: true
plots.confirm: true
plots.toggle: true
plots.toggle.titles: true
plots.toggle.chat: true
plots.toggle.time: true
plots.set.biome: true
plots.set.home: true
plots.set.alias: true
plots.alias.set: true
plots.alias.remove: true
plots.set.description: true
plots.description: true
plots.alias: true
plots.merge: true
plots.merge.other: true
plots.merge.4: true
plots.unlink: true
plots.denied: true
plots.add: true
plots.trust: true
plots.deny: true
plots.remove: true
plots.untrust: true
plots.undeny: true
plots.kick: true
plots.download: true
plots.save: true
plots.done: true
plots.continue: true
plots.middle: true
plots.worldedit.bypass:
default: false
plots.gamemode.bypass:
default: op
plots.confirm.bypass:
default: false

View file

@ -1,85 +0,0 @@
buildscript {
repositories {
jcenter()
mavenLocal()
maven {
name = "forge"
url = "http://files.minecraftforge.net/maven"
}
maven { url = "http://repo.minecrell.net/releases" }
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath 'gradle.plugin.net.minecrell:vanillagradle:2.2-6'
classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT'
}
}
apply plugin: 'net.minecrell.vanillagradle.server'
dependencies {
compile project(':Core')
compile 'org.spongepowered:spongeapi:7.1.0-SNAPSHOT'
compile 'net.minecrell.mcstats:statslite-sponge:0.2.2'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
maven {
name = 'minecrell'
url = 'http://repo.minecrell.net/releases'
}
maven {
name = 'forge'
url = 'http://files.minecraftforge.net/maven'
}
maven {
name = "Sponge"
url = "https://repo.spongepowered.org/maven"
}
}
minecraft {
version = "1.12.2"
mappings = "snapshot_20171022"
runDir = 'run'
}
project.archivesBaseName = "${project.archivesBaseName}-mc${minecraft.version}"
processResources {
from(sourceSets.main.resources.srcDirs) {
expand 'version': project.version,
'mcVersion': project.minecraft.version
}
}
shadowJar {
dependencies {
include(dependency(':Core'))
include dependency('net.minecrell.mcstats:statslite-sponge')
}
relocate 'net.minecrell.mcstats', 'com.plotsquared.util.mcstats'
archiveName = "${parent.name}-${project.name}-${parent.version}.jar"
destinationDir = file '../target'
}
shadowJar.doLast {
task ->
ant.checksum file: task.archivePath
}
reobf {
shadowJar {
mappingType = 'SEARGE'
}
}
task deobfJar(type: Jar) {
from sourceSets.main.output
classifier = 'dev'
}
build.dependsOn(shadowJar)

View file

@ -1,400 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge;
import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection;
import com.github.intellectualsites.plotsquared.plot.IPlotMain;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.generator.HybridGen;
import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils;
import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.SetupObject;
import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager;
import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea;
import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager;
import com.github.intellectualsites.plotsquared.plot.object.worlds.SingleWorldGenerator;
import com.github.intellectualsites.plotsquared.plot.util.block.QueueProvider;
import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper;
import com.github.intellectualsites.plotsquared.sponge.generator.SpongePlotGenerator;
import com.github.intellectualsites.plotsquared.sponge.listener.ChunkProcessor;
import com.github.intellectualsites.plotsquared.sponge.listener.MainListener;
import com.github.intellectualsites.plotsquared.sponge.listener.WorldEvents;
import com.github.intellectualsites.plotsquared.sponge.util.*;
import com.github.intellectualsites.plotsquared.sponge.util.block.SpongeLocalQueue;
import com.github.intellectualsites.plotsquared.sponge.uuid.SpongeLowerOfflineUUIDWrapper;
import com.github.intellectualsites.plotsquared.sponge.uuid.SpongeOnlineUUIDWrapper;
import com.github.intellectualsites.plotsquared.sponge.uuid.SpongeUUIDHandler;
import com.google.inject.Inject;
import net.minecrell.mcstats.SpongeStatsLite;
import org.slf4j.Logger;
import org.spongepowered.api.Game;
import org.spongepowered.api.Server;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.state.GameAboutToStartServerEvent;
import org.spongepowered.api.event.game.state.GamePreInitializationEvent;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.profile.GameProfileManager;
import org.spongepowered.api.world.Chunk;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.gen.GenerationPopulator;
import org.spongepowered.api.world.gen.WorldGenerator;
import org.spongepowered.api.world.gen.WorldGeneratorModifier;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Plugin(id = "plotsquared", name = "PlotSquared", description = "Easy, yet powerful Plot World generation and management.", url = "https://github.com/IntellectualSites/PlotSquared", version = "3.5.0-SNAPSHOT")
public class SpongeMain implements IPlotMain {
public static SpongeMain THIS;
@Inject public PluginContainer plugin;
@Inject public SpongeStatsLite stats;
@Inject private Logger logger;
@Inject private Game game;
private Server server;
@Inject @ConfigDir(sharedRoot = false) private Path privateConfigDir;
private GameProfileManager resolver;
private Logger getLogger() {
return this.logger;
}
public Game getGame() {
return this.game;
}
public Server getServer() {
return this.server;
}
public GameProfileManager getResolver() {
if (this.resolver == null) {
this.resolver = this.game.getServer().getGameProfileManager();
}
return this.resolver;
}
public SpongeMain getPlugin() {
return THIS;
}
@Listener public void onPreInitialize(GamePreInitializationEvent event) {
getLogger().info(
"The metrics section in PlotSquared is ignored in favor of the actual metrics reporter configurations.");
this.stats.start();
}
@Listener public void onServerAboutToStart(GameAboutToStartServerEvent event) {
THIS = this;
new PlotSquared(this, "Sponge");
this.server = this.game.getServer();
this.game.getRegistry().register(WorldGeneratorModifier.class,
(WorldGeneratorModifier) PlotSquared.get().IMP.getDefaultGenerator().specify(null));
this.game.getRegistry().register(WorldGeneratorModifier.class,
(WorldGeneratorModifier) new SingleWorldGenerator().specify(null));
if (Settings.Enabled_Components.WORLDS) {
TaskManager.IMP.taskRepeat(new Runnable() {
@Override public void run() {
unload();
}
}, 20);
}
}
public void unload() {
PlotAreaManager manager = PlotSquared.get().getPlotAreaManager();
if (manager instanceof SinglePlotAreaManager) {
SinglePlotArea area = ((SinglePlotAreaManager) manager).getArea();
for (World world : Sponge.getServer().getWorlds()) {
String name = world.getName();
PlotId id = PlotId.fromString(name);
if (id != null) {
Plot plot = area.getOwnedPlot(id);
if (plot != null) {
List<PlotPlayer> players = plot.getPlayersInPlot();
if (players.isEmpty() && PlotPlayer.wrap(plot.owner) == null) {
try {
world.save();
} catch (IOException e) {
e.printStackTrace();
return;
}
long start = System.currentTimeMillis();
for (Chunk chunk : world.getLoadedChunks()) {
chunk.unloadChunk();
if (System.currentTimeMillis() - start > 10) {
return;
}
}
Sponge.getServer().unloadWorld(world);
return;
}
}
}
}
}
}
@Override public void log(String message) {
message = C.format(message, C.replacements);
if (!Settings.Chat.CONSOLE_COLOR) {
message = message.replaceAll('\u00a7' + "[a-z|0-9]", "");
}
if (this.server == null) {
this.logger.info(message);
return;
}
this.server.getConsole().sendMessage(SpongeUtil.getText(message));
}
@Override public File getDirectory() {
return privateConfigDir.toFile();
}
@Override public File getWorldContainer() {
return new File(game.getSavesDirectory().toFile(), "world");
}
@Override public void disable() {
PlotSquared.get().disable();
THIS = null;
}
@Override public int[] getPluginVersion() {
String ver = this.plugin.getVersion().orElse("");
String[] split = ver.split("[\\.|-]");
return new int[] {Integer.parseInt(split[0]), Integer.parseInt(split[1]),
Integer.parseInt(split[2])};
}
@Override public String getPluginVersionString() {
return this.plugin.getVersion().orElse("");
}
@Override public String getPluginName() {
return "PlotSquared";
}
@Override public int[] getServerVersion() {
PlotSquared.log("Checking minecraft version: Sponge: ");
String version = this.game.getPlatform().getMinecraftVersion().getName();
String[] split = version.split("\\.");
return new int[] {Integer.parseInt(split[0]), Integer.parseInt(split[1]),
split.length == 3 ? Integer.parseInt(split[2]) : 0};
}
@Override public InventoryUtil initInventoryUtil() {
return new SpongeInventoryUtil();
}
@Override public EconHandler getEconomyHandler() {
SpongeEconHandler econ = new SpongeEconHandler();
Sponge.getEventManager().registerListeners(this, econ);
return econ;
}
@Override public EventUtil initEventUtil() {
return new SpongeEventUtil();
}
@Override public ChunkManager initChunkManager() {
return new SpongeChunkManager();
}
@Override public SetupUtils initSetupUtils() {
return new SpongeSetupUtils();
}
@Override public HybridUtils initHybridUtils() {
return new SpongeHybridUtils();
}
@Override public SchematicHandler initSchematicHandler() {
return new SpongeSchematicHandler();
}
@Override public TaskManager getTaskManager() {
return new SpongeTaskManager(this);
}
@Override public void runEntityTask() {
new KillRoadMobs().run();
}
@Override public void registerCommands() {
getGame().getCommandManager()
.register(THIS, new SpongeCommand(), "plots", "p", "plot", "ps", "plotsquared", "p2",
"2");
}
@Override public void registerPlayerEvents() {
Sponge.getEventManager().registerListeners(this, new MainListener());
}
@Override public void registerInventoryEvents() {
// Part of PlayerEvents - can be moved if necessary
}
@Override public void registerPlotPlusEvents() {
PlotSquared.log("registerPlotPlusEvents is not implemented!");
}
@Override public void registerForceFieldEvents() {
}
@Override public boolean initWorldEdit() {
try {
Class.forName("com.sk89q.worldedit.WorldEdit");
} catch (ClassNotFoundException ignored) {
return false;
}
return true;
}
@Override public UUIDHandlerImplementation initUUIDHandler() {
UUIDWrapper wrapper;
if (Settings.UUID.OFFLINE) {
wrapper = new SpongeLowerOfflineUUIDWrapper();
} else {
wrapper = new SpongeOnlineUUIDWrapper();
}
return new SpongeUUIDHandler(wrapper);
}
@Override public boolean initPlotMeConverter() {
return false;
}
@Override public void unregister(PlotPlayer player) {
SpongeUtil.removePlayer(player.getName());
}
@Override public void registerChunkProcessor() {
Sponge.getEventManager().registerListeners(this, new ChunkProcessor());
}
@Override public void registerWorldEvents() {
Sponge.getEventManager().registerListeners(this, new WorldEvents());
}
@Override public void startMetrics() {
}
@Override public void setGenerator(String worldName) {
World world = SpongeUtil.getWorld(worldName);
if (world == null) {
// create world
ConfigurationSection worldConfig =
PlotSquared.get().worlds.getConfigurationSection("worlds." + worldName);
String manager = worldConfig.getString("generator.plugin", "PlotSquared");
String generator = worldConfig.getString("generator.init", manager);
int type = worldConfig.getInt("generator.type");
int terrain = worldConfig.getInt("generator.terrain");
SetupObject setup = new SetupObject();
setup.plotManager = manager;
setup.setupGenerator = generator;
setup.type = type;
setup.terrain = terrain;
setup.step = new ConfigurationNode[0];
setup.world = worldName;
SetupUtils.manager.setupWorld(setup);
world = SpongeUtil.getWorld(worldName);
} else {
throw new IllegalArgumentException("World already loaded: " + worldName + "???");
}
WorldGenerator wg = world.getWorldGenerator();
GenerationPopulator gen = wg.getBaseGenerationPopulator();
if (gen instanceof GeneratorWrapper) {
PlotSquared.get().loadWorld(worldName, (GeneratorWrapper) gen);
} else {
throw new UnsupportedOperationException(
"NOT IMPLEMENTED YET2! " + worldName + " | " + gen);
}
}
@Override public AbstractTitle initTitleManager() {
return new SpongeTitleManager();
}
@Override public PlotPlayer wrapPlayer(Object player) {
if (player instanceof Player) {
return SpongeUtil.getPlayer((Player) player);
} else if (UUIDHandler.implementation == null) {
return null;
} else if (player instanceof String) {
return UUIDHandler.getPlayer((String) player);
} else if (player instanceof UUID) {
return UUIDHandler.getPlayer((UUID) player);
}
// TODO FIXME offline player
return null;
}
@Override public String getNMSPackage() {
return "";//TODO FIXME
}
@Override public ChatManager<?> initChatManager() {
return new SpongeChatManager();
}
@Override public QueueProvider initBlockQueue() {
MainUtil.canSendChunk = true;
return QueueProvider.of(SpongeLocalQueue.class, null);
}
@Override public WorldUtil initWorldUtil() {
return new SpongeUtil();
}
@Override public GeneratorWrapper<?> getGenerator(String world, String name) {
if (name == null) {
return null;
}
Collection<WorldGeneratorModifier> wgms =
this.game.getRegistry().getAllOf(WorldGeneratorModifier.class);
for (WorldGeneratorModifier wgm : wgms) {
if (StringMan.isEqualIgnoreCaseToAny(name, wgm.getName(), wgm.getId())) {
if (wgm instanceof GeneratorWrapper<?>) {
return (GeneratorWrapper<?>) wgm;
}
return new SpongePlotGenerator(wgm);
}
}
return new SpongePlotGenerator(PlotSquared.get().IMP.getDefaultGenerator());
}
@Override
public GeneratorWrapper<?> wrapPlotGenerator(String world, IndependentPlotGenerator generator) {
return new SpongePlotGenerator(generator);
}
@Override public List<String> getPluginIds() {
return this.game.getPluginManager().getPlugins().stream()
.map(plugin1 -> plugin1.getName() + ';' + plugin1.getVersion() + ':' + true)
.collect(Collectors.toCollection(ArrayList::new));
}
@Override public IndependentPlotGenerator getDefaultGenerator() {
return new HybridGen();
}
}

View file

@ -1,49 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.PlotCluster;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
public class ClusterFlagRemoveEvent extends AbstractEvent implements Cancellable {
private final PlotCluster cluster;
private final Flag flag;
private boolean cancelled;
public ClusterFlagRemoveEvent(final Flag flag, final PlotCluster cluster) {
this.cluster = cluster;
this.flag = flag;
}
/**
* Get the cluster involved
*
* @return PlotCluster
*/
public PlotCluster getCluster() {
return cluster;
}
/**
* Get the flag involved
*
* @return Flag
*/
public Flag getFlag() {
return flag;
}
@Override public boolean isCancelled() {
return cancelled;
}
@Override public void setCancelled(final boolean cancel) {
cancelled = cancel;
}
@Override public Cause getCause() {
return null;
}
}

View file

@ -1,53 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.cause.Cause;
public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable {
private final Plot plot;
private final boolean auto;
private boolean cancelled;
/**
* PlayerClaimPlotEvent: Called when a plot is claimed
*
* @param player Player that claimed the plot
* @param plot Plot that was claimed
*/
public PlayerClaimPlotEvent(final Player player, final Plot plot, final boolean auto) {
super(player);
this.plot = plot;
this.auto = auto;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return plot;
}
/**
* @return true if it was an automated claim, else false
*/
public boolean wasAuto() {
return auto;
}
@Override public boolean isCancelled() {
return cancelled;
}
@Override public void setCancelled(final boolean cancel) {
cancelled = cancel;
}
@Override public Cause getCause() {
return null;
}
}

View file

@ -1,34 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.cause.Cause;
public class PlayerEnterPlotEvent extends PlayerEvent {
private final Plot plot;
/**
* PlayerEnterPlotEvent: Called when a player leaves a plot
*
* @param player Player that entered the plot
* @param plot Plot that was entered
*/
public PlayerEnterPlotEvent(final Player player, final Plot plot) {
super(player);
this.plot = plot;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return plot;
}
@Override public Cause getCause() {
return null;
}
}

View file

@ -1,23 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
public abstract class PlayerEvent extends AbstractEvent {
public final Player player;
public PlayerEvent(final Player player) {
this.player = player;
}
public Player getPlayer() {
return player;
}
@Override public Cause getCause() {
return null;
}
}

View file

@ -1,29 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.entity.living.player.Player;
public class PlayerLeavePlotEvent extends PlayerEvent {
private final Plot plot;
/**
* PlayerLeavePlotEvent: Called when a player leaves a plot
*
* @param player Player that left the plot
* @param plot Plot that was left
*/
public PlayerLeavePlotEvent(final Player player, final Plot plot) {
super(player);
this.plot = plot;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return plot;
}
}

View file

@ -1,56 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.entity.living.player.Player;
import java.util.UUID;
public class PlayerPlotDeniedEvent extends PlotEvent {
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotDeniedEvent: Called when the denied UUID list is modified for a plot
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was denied/un-denied
* @param added true of add to deny list, false if removed
*/
public PlayerPlotDeniedEvent(final Player initiator, final Plot plot, final UUID player,
final boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
/**
* If a user was added
*
* @return boolean
*/
public boolean wasAdded() {
return added;
}
/**
* The player added/removed
*
* @return UUID
*/
public UUID getPlayer() {
return player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator() {
return initiator;
}
}

View file

@ -1,56 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.entity.living.player.Player;
import java.util.UUID;
public class PlayerPlotHelperEvent extends PlotEvent {
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotHelperEvent: Called when a plot helper is added/removed
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was added/removed from the helper list
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotHelperEvent(final Player initiator, final Plot plot, final UUID player,
final boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
/**
* If a user was added
*
* @return boolean
*/
public boolean wasAdded() {
return added;
}
/**
* The player added/removed
*
* @return UUID
*/
public UUID getPlayer() {
return player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator() {
return initiator;
}
}

View file

@ -1,56 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.entity.living.player.Player;
import java.util.UUID;
public class PlayerPlotTrustedEvent extends PlotEvent {
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotTrustedEvent: Called when a plot trusted user is added/removed
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was added/removed from the trusted list
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotTrustedEvent(final Player initiator, final Plot plot, final UUID player,
final boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
/**
* If a user was added
*
* @return boolean
*/
public boolean wasAdded() {
return added;
}
/**
* The player added/removed
*
* @return UUID
*/
public UUID getPlayer() {
return player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator() {
return initiator;
}
}

View file

@ -1,52 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Cancellable;
public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellable {
private final Location from;
private final Plot plot;
private boolean cancelled;
/**
* PlayerTeleportToPlotEvent: Called when a player teleports to a plot.
*
* @param player That was teleported
* @param from Start location
* @param plot Plot to which the player was teleported
*/
public PlayerTeleportToPlotEvent(Player player, Location from, Plot plot) {
super(player);
this.from = from;
this.plot = plot;
}
/**
* Get the from location.
*
* @return Location
*/
public Location getFrom() {
return this.from;
}
/**
* Get the plot involved.
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean cancel) {
this.cancelled = cancel;
}
}

View file

@ -1,96 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Cancellable;
import java.util.UUID;
public class PlotChangeOwnerEvent extends PlotEvent implements Cancellable {
private final Player initiator;
private final UUID newOwner;
private final UUID oldOwner;
private final boolean hasOldOwner;
private boolean cancelled;
/**
* PlotChangeOwnerEvent: Called when a plot's owner is change.
*
* @param newOwner The new owner of the plot
* @param oldOwner The old owner of the plot
* @param plot The plot having its owner changed
*/
public PlotChangeOwnerEvent(Player initiator, Plot plot, UUID oldOwner, UUID newOwner,
boolean hasOldOwner) {
super(plot);
this.initiator = initiator;
this.newOwner = newOwner;
this.oldOwner = oldOwner;
this.hasOldOwner = hasOldOwner;
}
/**
* Get the PlotId.
*
* @return PlotId
*/
public PlotId getPlotId() {
return getPlot().getId();
}
/**
* Get the world name.
*
* @return String
*/
public String getWorld() {
return getPlot().getWorldName();
}
/**
* Get the change-owner initator
*
* @return Player
*/
public Player getInitiator() {
return this.initiator;
}
/**
* Get the old owner of the plot. Null if not exists.
*
* @return UUID
*/
public UUID getOldOwner() {
return this.oldOwner;
}
/**
* Get the new owner of the plot
*
* @return UUID
*/
public UUID getNewOwner() {
return this.newOwner;
}
/**
* Get if the plot had an old owner
*
* @return boolean
*/
public boolean hasOldOwner() {
return this.hasOldOwner;
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View file

@ -1,53 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
public class PlotClearEvent extends AbstractEvent implements Cancellable {
private final Plot plot;
private boolean cancelled;
/**
* PlotDeleteEvent: Called when a plot is cleared
*
* @param plot The plot that was cleared
*/
public PlotClearEvent(Plot plot) {
this.plot = plot;
}
/**
* Get the PlotId.
*
* @return PlotId
*/
public PlotId getPlotId() {
return this.plot.getId();
}
/**
* Get the world name.
*
* @return String
*/
public String getWorld() {
return this.plot.getWorldName();
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean cancel) {
this.cancelled = cancel;
}
@Override public Cause getCause() {
return null;
}
}

View file

@ -1,53 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
public class PlotComponentSetEvent extends AbstractEvent {
private final Plot plot;
private final String component;
/**
* PlotDeleteEvent: Called when a plot component is set
*
* @param plot The plot
* @param component The component which was set
*/
public PlotComponentSetEvent(Plot plot, String component) {
this.plot = plot;
this.component = component;
}
/**
* Get the PlotId
*
* @return PlotId
*/
public PlotId getPlotId() {
return this.plot.getId();
}
/**
* Get the world name
*
* @return String
*/
public String getWorld() {
return this.plot.getWorldName();
}
/**
* Get the component which was set
*
* @return Component name
*/
public String getComponent() {
return this.component;
}
@Override public Cause getCause() {
return null;
}
}

View file

@ -1,41 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
public class PlotDeleteEvent extends AbstractEvent {
private final Plot plot;
/**
* PlotDeleteEvent: Called when a plot is deleted
*
* @param plot The plot that was deleted
*/
public PlotDeleteEvent(Plot plot) {
this.plot = plot;
}
/**
* Get the PlotId
*
* @return PlotId
*/
public PlotId getPlotId() {
return plot.getId();
}
/**
* Get the world name
*
* @return String
*/
public String getWorld() {
return plot.getWorldName();
}
@Override public Cause getCause() {
return null;
}
}

View file

@ -1,23 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
public abstract class PlotEvent extends AbstractEvent {
private final Plot plot;
public PlotEvent(final Plot plot) {
this.plot = plot;
}
public final Plot getPlot() {
return plot;
}
@Override public Cause getCause() {
return null;
}
}

View file

@ -1,38 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.event.Cancellable;
public class PlotFlagAddEvent extends PlotEvent implements Cancellable {
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagAddEvent: Called when a Flag is added to a plot
*
* @param flag Flag that was added
* @param plot Plot to which the flag was added
*/
public PlotFlagAddEvent(final Flag flag, final Plot plot) {
super(plot);
this.flag = flag;
}
/**
* Get the flag involved
*
* @return Flag
*/
public Flag getFlag() {
return flag;
}
@Override public boolean isCancelled() {
return cancelled;
}
@Override public void setCancelled(final boolean cancel) {
cancelled = cancel;
}
}

View file

@ -1,38 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.event.Cancellable;
public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable {
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot
*
* @param flag Flag that was removed
* @param plot Plot from which the flag was removed
*/
public PlotFlagRemoveEvent(final Flag flag, final Plot plot) {
super(plot);
this.flag = flag;
}
/**
* Get the flag involved
*
* @return Flag
*/
public Flag getFlag() {
return flag;
}
@Override public boolean isCancelled() {
return cancelled;
}
@Override public void setCancelled(final boolean cancel) {
cancelled = cancel;
}
}

View file

@ -1,62 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
import org.spongepowered.api.world.World;
import java.util.ArrayList;
public class PlotMergeEvent extends AbstractEvent implements Cancellable {
private final ArrayList<PlotId> plots;
private boolean cancelled;
private Plot plot;
private World world;
/**
* PlotMergeEvent: Called when plots are merged
*
* @param world World in which the event occurred
* @param plot Plot that was merged
* @param plots A list of plots involved in the event
*/
public PlotMergeEvent(final World world, final Plot plot, final ArrayList<PlotId> plots) {
this.plots = plots;
}
/**
* Get the plots being added;
*
* @return Plot
*/
public ArrayList<PlotId> getPlots() {
return plots;
}
/**
* Get the main plot
*
* @return Plot
*/
public Plot getPlot() {
return plot;
}
public World getWorld() {
return world;
}
@Override public boolean isCancelled() {
return cancelled;
}
@Override public void setCancelled(final boolean cancel) {
cancelled = cancel;
}
@Override public Cause getCause() {
return null;
}
}

View file

@ -1,35 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.Rating;
import org.spongepowered.api.event.Cancellable;
public class PlotRateEvent extends PlotEvent implements Cancellable {
private final PlotPlayer rater;
private Rating rating;
private boolean cancelled = false;
public PlotRateEvent(final PlotPlayer rater, final Rating rating, final Plot plot) {
super(plot);
this.rater = rater;
this.rating = rating;
}
public PlotPlayer getRater() {
return rater;
}
public Rating getRating() {
return rating;
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean cancel) {
this.cancelled = cancel;
}
}

View file

@ -1,51 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
import org.spongepowered.api.world.World;
import java.util.ArrayList;
public class PlotUnlinkEvent extends AbstractEvent implements Cancellable {
private final ArrayList<PlotId> plots;
private final World world;
private boolean cancelled;
/**
* Called when a mega-plot is unlinked.
*
* @param world World in which the event occurred
* @param plots Plots that are involved in the event
*/
public PlotUnlinkEvent(final World world, final ArrayList<PlotId> plots) {
this.plots = plots;
this.world = world;
}
/**
* Get the plots involved
*
* @return PlotId
*/
public ArrayList<PlotId> getPlots() {
return plots;
}
public World getWorld() {
return world;
}
@Override public boolean isCancelled() {
return cancelled;
}
@Override public void setCancelled(final boolean cancel) {
cancelled = cancel;
}
@Override public Cause getCause() {
return null;
}
}

View file

@ -1,66 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.generator;
import com.flowpowered.math.vector.Vector3i;
import com.github.intellectualsites.plotsquared.plot.generator.AugmentedUtils;
import com.github.intellectualsites.plotsquared.plot.object.PlotBlock;
import com.github.intellectualsites.plotsquared.plot.util.block.DelegateLocalBlockQueue;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.extent.ImmutableBiomeVolume;
import org.spongepowered.api.world.extent.MutableBlockVolume;
import org.spongepowered.api.world.gen.GenerationPopulator;
import org.spongepowered.api.world.gen.WorldGenerator;
import java.util.List;
public class SpongeAugmentedGenerator implements GenerationPopulator {
private static SpongeAugmentedGenerator generator;
private SpongeAugmentedGenerator() {
}
public static SpongeAugmentedGenerator get(World world) {
WorldGenerator wg = world.getWorldGenerator();
List<GenerationPopulator> populators = wg.getGenerationPopulators();
for (GenerationPopulator populator : populators) {
if (populator instanceof SpongeAugmentedGenerator) {
return (SpongeAugmentedGenerator) populator;
}
}
if (generator == null) {
generator = new SpongeAugmentedGenerator();
}
populators.add(generator);
return generator;
}
@Override
public void populate(World world, MutableBlockVolume terrain, ImmutableBiomeVolume biome) {
Vector3i min = terrain.getBlockMin();
int bx = min.getX();
int bz = min.getZ();
int cx = bx >> 4;
int cz = bz >> 4;
AugmentedUtils.generate(world.getName(), cx, cz, new DelegateLocalBlockQueue(null) {
@Override public boolean setBlock(int x, int y, int z, int id, int data) {
terrain.setBlock(bx + x, y, bz + z, SpongeUtil.getBlockState(id, data));
return true;
}
@Override public PlotBlock getBlock(int x, int y, int z) {
BlockState block = terrain.getBlock(bx + x, y, bz + z);
return SpongeUtil.getPlotBlock(block);
}
@Override public boolean setBiome(int x, int z, String biome) {
return false; // TODO ?
}
@Override public String getWorld() {
return world.getName();
}
});
}
}

View file

@ -1,116 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.generator;
import com.flowpowered.math.vector.Vector3i;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.PlotManager;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.world.biome.BiomeGenerationSettings;
import org.spongepowered.api.world.biome.BiomeType;
import org.spongepowered.api.world.biome.BiomeTypes;
import org.spongepowered.api.world.extent.MutableBiomeVolume;
import org.spongepowered.api.world.gen.BiomeGenerator;
import org.spongepowered.api.world.gen.GenerationPopulator;
import org.spongepowered.api.world.gen.WorldGenerator;
import org.spongepowered.api.world.gen.WorldGeneratorModifier;
import org.spongepowered.api.world.storage.WorldProperties;
import java.util.ArrayList;
import java.util.List;
public class SpongePlotGenerator
implements WorldGeneratorModifier, GeneratorWrapper<WorldGeneratorModifier> {
private final IndependentPlotGenerator plotGenerator;
private final List<GenerationPopulator> populators = new ArrayList<>();
private final boolean loaded = false;
private final WorldGeneratorModifier platformGenerator;
private final boolean full;
private PlotManager manager;
public SpongePlotGenerator(IndependentPlotGenerator generator) {
this.plotGenerator = generator;
this.platformGenerator = this;
this.full = true;
MainUtil.initCache();
}
public SpongePlotGenerator(WorldGeneratorModifier wgm) {
this.plotGenerator = null;
this.platformGenerator = wgm;
this.full = false;
MainUtil.initCache();
}
@Override public String getId() {
if (this.plotGenerator == null) {
if (this.platformGenerator != this) {
return this.platformGenerator.getId();
}
return "null";
}
return this.plotGenerator.getName();
}
@Override public String getName() {
if (this.plotGenerator == null) {
if (this.platformGenerator != this) {
return this.platformGenerator.getName();
}
return "null";
}
return this.plotGenerator.getName();
}
@Override public void modifyWorldGenerator(WorldProperties world, DataContainer settings,
WorldGenerator worldGenerator) {
String worldName = world.getWorldName();
worldGenerator.setBaseGenerationPopulator(new SpongeTerrainGen(this.plotGenerator));
worldGenerator.setBiomeGenerator(new BiomeGenerator() {
@Override public void generateBiomes(MutableBiomeVolume buffer) {
PlotArea area = PlotSquared.get().getPlotArea(worldName, null);
if (area != null) {
BiomeType biome = SpongeUtil.getBiome(area.PLOT_BIOME);
Vector3i min = buffer.getBiomeMin();
Vector3i max = buffer.getBiomeMax();
for (int x = min.getX(); x <= max.getX(); x++) {
for (int z = min.getZ(); z <= max.getZ(); z++) {
buffer.setBiome(x, 0, z, biome);
}
}
}
}
});
for (BiomeType type : ReflectionUtils.<BiomeType>getStaticFields(BiomeTypes.class)) {
BiomeGenerationSettings biomeSettings = worldGenerator.getBiomeSettings(type);
biomeSettings.getGenerationPopulators().clear();
biomeSettings.getPopulators().clear();
biomeSettings.getGroundCoverLayers().clear();
}
worldGenerator.getGenerationPopulators().clear();
worldGenerator.getPopulators().clear();
PlotSquared.get().loadWorld(worldName, this);
}
@Override public IndependentPlotGenerator getPlotGenerator() {
return this.plotGenerator;
}
@Override public WorldGeneratorModifier getPlatformGenerator() {
return this.platformGenerator;
}
@Override public void augment(PlotArea area) {
SpongeAugmentedGenerator.get(SpongeUtil.getWorld(area.getWorldName()));
}
@Override public boolean isFull() {
return this.full;
}
}

View file

@ -1,94 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.generator;
import com.flowpowered.math.vector.Vector3i;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator;
import com.github.intellectualsites.plotsquared.plot.object.ChunkWrapper;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.PseudoRandom;
import com.github.intellectualsites.plotsquared.plot.util.ChunkManager;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import com.github.intellectualsites.plotsquared.sponge.util.block.GenChunk;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.extent.ImmutableBiomeVolume;
import org.spongepowered.api.world.extent.MutableBlockVolume;
import org.spongepowered.api.world.gen.GenerationPopulator;
public class SpongeTerrainGen
implements GenerationPopulator, GeneratorWrapper<GenerationPopulator> {
public final IndependentPlotGenerator child;
private final boolean full;
private final GenerationPopulator platformGenerator;
private final PseudoRandom random = new PseudoRandom();
public SpongeTerrainGen(IndependentPlotGenerator ipg) {
this.child = ipg;
this.full = true;
this.platformGenerator = this;
MainUtil.initCache();
}
public SpongeTerrainGen(GenerationPopulator populator) {
this.child = null;
this.platformGenerator = populator;
this.full = false;
MainUtil.initCache();
}
@Override
public void populate(World world, MutableBlockVolume terrain, ImmutableBiomeVolume biomes) {
if (platformGenerator != this) {
platformGenerator.populate(world, terrain, biomes);
return;
}
Vector3i size = terrain.getBlockSize();
if (size.getX() != 16 || size.getZ() != 16) {
throw new UnsupportedOperationException("NON CHUNK POPULATION NOT SUPPORTED");
}
String worldname = world.getName();
Vector3i min = terrain.getBlockMin();
int cx = min.getX() >> 4;
int cz = min.getZ() >> 4;
ChunkWrapper wrap = new ChunkWrapper(worldname, cx, cz);
// Create the result object
GenChunk result = new GenChunk(terrain, null, wrap);
// Catch any exceptions
try {
// Set random seed
random.state = (cx << 16) | (cz & 0xFFFF);
// Process the chunk
result.modified = false;
ChunkManager.preProcessChunk(result);
if (result.modified) {
return;
}
// Fill the result data
PlotArea area = PlotSquared.get().getPlotArea(world.getName(), null);
child.generateChunk(result, area, random);
child.populateChunk(result, area, random);
ChunkManager.postProcessChunk(result);
return;
} catch (Throwable e) {
e.printStackTrace();
}
}
@Override public IndependentPlotGenerator getPlotGenerator() {
return child;
}
@Override public GenerationPopulator getPlatformGenerator() {
return platformGenerator;
}
@Override public void augment(PlotArea area) {
SpongeAugmentedGenerator.get(SpongeUtil.getWorld(area.getWorldName()));
}
@Override public boolean isFull() {
return this.full;
}
}

View file

@ -1,5 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.listener;
public class ChunkProcessor {
// TODO FIXME
}

View file

@ -1,102 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.listener;
import com.flowpowered.math.vector.Vector3d;
import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.entity.living.player.Player;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class ForceFieldListener {
private static Set<PlotPlayer> getNearbyPlayers(Player player, Plot plot) {
Set<PlotPlayer> players = new HashSet<>();
for (Entity nearbyEntity : player
.getNearbyEntities(entity -> entity.getType().equals(EntityTypes.PLAYER))) {
Player nearbyPlayer = (Player) nearbyEntity;
PlotPlayer plotPlayer;
if ((plotPlayer = SpongeUtil.getPlayer(nearbyPlayer)) == null || !plot
.equals(plotPlayer.getCurrentPlot())) {
continue;
}
if (!plot.isAdded(plotPlayer.getUUID())) {
players.add(plotPlayer);
}
}
return players;
}
private static PlotPlayer hasNearbyPermitted(Player player, Plot plot) {
for (Entity nearbyEntity : player
.getNearbyEntities(entity -> entity.getType().equals(EntityTypes.PLAYER))) {
Player nearbyPlayer = (Player) nearbyEntity;
PlotPlayer plotPlayer;
if ((plotPlayer = SpongeUtil.getPlayer(nearbyPlayer)) == null || !plot
.equals(plotPlayer.getCurrentPlot())) {
continue;
}
if (plot.isAdded(plotPlayer.getUUID())) {
return plotPlayer;
}
}
return null;
}
private static Vector3d calculateVelocity(PlotPlayer player, PlotPlayer e) {
Location playerLocation = player.getLocationFull();
Location oPlayerLocation = e.getLocation();
double playerX = playerLocation.getX();
double playerY = playerLocation.getY();
double playerZ = playerLocation.getZ();
double oPlayerX = oPlayerLocation.getX();
double oPlayerY = oPlayerLocation.getY();
double oPlayerZ = oPlayerLocation.getZ();
double x = 0d;
if (playerX < oPlayerX) {
x = 1.0d;
} else if (playerX > oPlayerX) {
x = -1.0d;
}
double y = 0d;
if (playerY < oPlayerY) {
y = 0.5d;
} else if (playerY > oPlayerY) {
y = -0.5d;
}
double z = 0d;
if (playerZ < oPlayerZ) {
z = 1.0d;
} else if (playerZ > oPlayerZ) {
z = -1.0d;
}
return new Vector3d(x, y, z);
}
public static void handleForcefield(Player player, PlotPlayer plotPlayer, Plot plot) {
if (Flags.FORCEFIELD.isTrue(plot)) {
UUID uuid = plotPlayer.getUUID();
if (plot.isAdded(uuid)) {
Set<PlotPlayer> players = getNearbyPlayers(player, plot);
for (PlotPlayer oPlayer : players) {
((SpongePlayer) oPlayer).player
.setVelocity(calculateVelocity(plotPlayer, oPlayer));
}
} else {
PlotPlayer oPlayer = hasNearbyPermitted(player, plot);
if (oPlayer == null) {
return;
}
player.setVelocity(calculateVelocity(oPlayer, plotPlayer));
}
}
}
}

View file

@ -1,755 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.listener;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.listener.PlotListener;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import org.spongepowered.api.block.BlockSnapshot;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.data.Transaction;
import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.entity.explosive.Explosive;
import org.spongepowered.api.entity.living.Ambient;
import org.spongepowered.api.entity.living.Living;
import org.spongepowered.api.entity.living.animal.Animal;
import org.spongepowered.api.entity.living.monster.Monster;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.vehicle.Boat;
import org.spongepowered.api.entity.vehicle.minecart.Minecart;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.block.ChangeBlockEvent;
import org.spongepowered.api.event.block.InteractBlockEvent;
import org.spongepowered.api.event.block.NotifyNeighborBlockEvent;
import org.spongepowered.api.event.entity.BreedEntityEvent;
import org.spongepowered.api.event.entity.MoveEntityEvent;
import org.spongepowered.api.event.entity.SpawnEntityEvent;
import org.spongepowered.api.event.message.MessageEvent;
import org.spongepowered.api.event.network.ClientConnectionEvent;
import org.spongepowered.api.event.world.ExplosionEvent;
import org.spongepowered.api.event.world.ExplosionEvent.Detonate;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.world.World;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
@SuppressWarnings("Guava") public class MainListener {
/*
* TODO:
* - Anything marked with a TODO below
* - BlockPhysicsEvent
* - BlockFormEvent
* - BlockFadeEvent
* - BlockFromToEvent
* - BlockDamageEvent
* - Structure (tree etc)
* - ChunkPreGenerateEvent
* - PlayerIgniteBlockEvent
* - PlayerBucketEmptyEvent
* - PlayerBucketFillEvent
* - VehicleCreateEvent
* - HangingPlaceEvent
* - HangingBreakEvent
* - EntityChangeBlockEvent
* - PVP
* - block dispense
* - PVE
* - VehicleDestroy
* - Projectile
* - enderman harvest
*/
@Listener public void onChat(MessageEvent event) {
// TODO
if (event.isMessageCancelled())
return;
Player player = SpongeUtil.getCause(event.getCause(), Player.class);
if (player == null) {
return;
}
String world = player.getWorld().getName();
if (!PlotSquared.get().hasPlotArea(world)) {
return;
}
PlotArea plotworld = PlotSquared.get().getPlotAreaByString(world);
PlotPlayer plr = SpongeUtil.getPlayer(player);
if (!plotworld.PLOT_CHAT && (plr.getMeta("chat") == null || !(Boolean) plr
.getMeta("chat"))) {
return;
}
Location loc = SpongeUtil.getLocation(player);
Plot plot = loc.getPlot();
if (plot == null) {
return;
}
Text message = event.getMessage();
// TODO use display name rather than username
// - Getting displayname currently causes NPE, so wait until sponge fixes that
String sender = player.getName();
PlotId id = plot.getId();
String newMessage = StringMan
.replaceAll(C.PLOT_CHAT_FORMAT.s(), "%plot_id%", id.x + ";" + id.y, "%sender%", sender);
// String forcedMessage = StringMan.replaceAll(C.PLOT_CHAT_FORCED.s(), "%plot_id%", id.x + ";" + id.y, "%sender%", sender);
for (Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) {
PlotPlayer user = entry.getValue();
String toSend;
if (plot.equals(user.getLocation().getPlot())) {
toSend = newMessage;
} else if (Permissions.hasPermission(user, C.PERMISSION_COMMANDS_CHAT)) {
((SpongePlayer) user).player.sendMessage(message);
continue;
} else {
continue;
}
String[] split = (toSend + " ").split("%msg%");
List<Text> components = new ArrayList<>();
Text prefix = null;
for (String part : split) {
if (prefix != null) {
components.add(prefix);
} else {
prefix = message;
}
components.add(SpongeUtil.getText(part));
}
((SpongePlayer) user).player.sendMessage(Text.join(components));
}
//event.setMessage(null);
}
@Listener public void onBreedEntity(BreedEntityEvent.Breed event) {
Location loc = SpongeUtil.getLocation(event.getTargetEntity());
String world = loc.getWorld();
PlotArea plotworld = PlotSquared.get().getPlotAreaByString(world);
if (plotworld == null) {
return;
}
Plot plot = loc.getPlot();
if (plot == null) {
if (loc.isPlotRoad()) {
event.setCancelled(true);
}
return;
}
if (!plotworld.SPAWN_BREEDING) {
event.setCancelled(true);
}
}
@Listener public void onSpawnEntity(SpawnEntityEvent event) {
event.filterEntities(entity -> {
if (entity instanceof Player) {
return true;
}
Location loc = SpongeUtil.getLocation(entity);
Plot plot = loc.getPlot();
if (plot == null) {
return !loc.isPlotRoad();
}
// Player player = this.<Player> getCause(event.getCause());
// TODO selectively cancel depending on spawn reason
// - Not sure if possible to get spawn reason (since there are no callbacks)
// if (player != null && !plotworld.SPAWN_EGGS) {
// return false;
// return true;
// }
if (entity.getType() == EntityTypes.ITEM) {
return plot.getFlag(Flags.ITEM_DROP).or(true);
}
int[] mobs = null;
if (entity instanceof Living) {
if (!loc.getPlotArea().MOB_SPAWNING) {
return false;
}
com.google.common.base.Optional<Integer> mobCap = plot.getFlag(Flags.MOB_CAP);
if (mobCap.isPresent()) {
Integer cap = mobCap.get();
if (cap == 0) {
return false;
}
mobs = plot.countEntities();
if (mobs[3] >= cap) {
return false;
}
}
if (entity instanceof Ambient || entity instanceof Animal) {
com.google.common.base.Optional<Integer> animalFlag =
plot.getFlag(Flags.ANIMAL_CAP);
if (animalFlag.isPresent()) {
int cap = animalFlag.get();
if (cap == 0) {
return false;
}
if (mobs == null) {
mobs = plot.countEntities();
}
if (mobs[1] >= cap) {
return false;
}
}
} else if (entity instanceof Monster) {
com.google.common.base.Optional<Integer> monsterFlag =
plot.getFlag(Flags.HOSTILE_CAP);
if (monsterFlag.isPresent()) {
int cap = monsterFlag.get();
if (cap == 0) {
return false;
}
if (mobs == null) {
mobs = plot.countEntities();
}
if (mobs[2] >= cap) {
return false;
}
}
}
return true;
} else if (entity instanceof Minecart || entity instanceof Boat) {
com.google.common.base.Optional<Integer> vehicleFlag =
plot.getFlag(Flags.VEHICLE_CAP);
if (vehicleFlag.isPresent()) {
int cap = vehicleFlag.get();
if (cap == 0) {
return false;
}
mobs = plot.countEntities();
if (mobs[4] >= cap) {
return false;
}
}
}
com.google.common.base.Optional<Integer> entityCap = plot.getFlag(Flags.ENTITY_CAP);
if (entityCap.isPresent()) {
Integer cap = entityCap.get();
if (cap == 0) {
return false;
}
if (mobs == null) {
mobs = plot.countEntities();
}
if (mobs[0] >= cap) {
return false;
}
}
if (entity instanceof Explosive) {
entity.setCreator(plot.owner);
}
return true;
});
}
public void onNotifyNeighborBlock(NotifyNeighborBlockEvent event) {
AtomicBoolean cancelled = new AtomicBoolean(false);
// SpongeUtil.printCause("physics", event.getCause());
// PlotArea area = plotloc.getPlotArea();
// event.filterDirections(new Predicate<Direction>() {
//
// @Override
// public boolean test(Direction dir) {
// if (cancelled.get()) {
// return true;
// }
// org.spongepowered.api.world.Location<World> loc = relatives.get(dir);
// Location plotloc = SpongeUtil.getLocation(loc.getExtent().getPluginName(), loc);
// if (area == null) {
// return true;
// }
// plot = area.get
// Plot plot = plotloc.getPlot();
// if (plot == null) {
// if (MainUtil.isPlotAreaAbs(plotloc)) {
// cancelled.set(true);
// return false;
// }
// cancelled.set(true);
// return true;
// }
// org.spongepowered.api.world.Location<World> relative = loc.getRelative(dir);
// Location relLoc = SpongeUtil.getLocation(relative.getExtent().getPluginName(), relative);
// if (plot.equals(MainUtil.getPlot(relLoc))) {
// return true;
// }
// return false;
// }
// });
}
@Listener public void onInteract(InteractBlockEvent event) {
Player player = SpongeUtil.getCause(event.getCause(), Player.class);
if (player == null) {
event.setCancelled(true);
return;
}
BlockSnapshot block = event.getTargetBlock();
if (block == null) {
return;
}
Optional<org.spongepowered.api.world.Location<World>> bloc = block.getLocation();
if (!bloc.isPresent()) {
return;
}
Location loc = SpongeUtil.getLocation(player.getWorld().getName(), bloc.get());
PlotArea area = loc.getPlotArea();
if (area == null) {
return;
}
Plot plot = area.getPlot(loc);
PlotPlayer pp = SpongeUtil.getPlayer(player);
if (plot == null) {
if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD, true)) {
event.setCancelled(true);
return;
}
return;
}
if (!plot.hasOwner()) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED)) {
return;
}
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_UNOWNED);
event.setCancelled(true);
return;
}
if (plot.isAdded(pp.getUUID()) || Permissions
.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER)) {
return;
} else {
com.google.common.base.Optional<HashSet<PlotBlock>> flag = plot.getFlag(Flags.USE);
org.spongepowered.api.world.Location l = SpongeUtil.getLocation(loc);
if (flag.isPresent() && flag.get().contains(SpongeUtil.getPlotBlock(l.getBlock()))) {
return;
}
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_OTHER);
event.setCancelled(true);
return;
}
}
@Listener public void onExplosion(ExplosionEvent e) {
if (e instanceof ExplosionEvent.Detonate) {
ExplosionEvent.Detonate event = (Detonate) e;
World world = event.getTargetWorld();
String worldName = world.getName();
if (!PlotSquared.get().hasPlotArea(worldName)) {
return;
}
Optional<Explosive> source = event.getExplosion().getSourceExplosive();
if (!source.isPresent()) {
event.setCancelled(true);
return;
}
Explosive tnt = source.get();
UUID creator = tnt.getCreator().orElse(null);
Location current = SpongeUtil.getLocation(tnt);
Plot currentPlot = current.getPlot();
if (currentPlot == null) {
if (current.isPlotArea()) {
event.setCancelled(true);
}
return;
}
if (creator != null) {
if (!currentPlot.isAdded(creator)) {
event.setCancelled(true);
return;
}
}
if (!currentPlot.getFlag(Flags.EXPLOSION).or(false)) {
event.setCancelled(true);
return;
}
event.getAffectedLocations().removeIf(worldLocation -> currentPlot.equals(
SpongeUtil.getLocation(worldLocation.getExtent().getName(), worldLocation)
.getPlot()));
event.filterEntities(
entity -> currentPlot.equals(SpongeUtil.getLocation(entity).getPlot()));
}
}
public void onChangeBlock(ChangeBlockEvent event) {
List<Transaction<BlockSnapshot>> transactions = event.getTransactions();
Transaction<BlockSnapshot> first = transactions.get(0);
BlockSnapshot original = first.getOriginal();
Optional<World> world = SpongeMain.THIS.getServer().getWorld(original.getWorldUniqueId());
String worldName = world.get().getName();
Location loc = SpongeUtil.getLocation(worldName, original.getPosition());
PlotArea area = loc.getPlotArea();
if (area == null) {
return;
}
Plot plot = area.getPlot(loc);
if (plot == null) {
if (!loc.isPlotArea()) {
return;
}
event.setCancelled(true);
return;
}
event.filter(loc1 -> !SpongeUtil.getLocation(worldName, loc1).isPlotRoad());
}
@Listener public void onBlockBreak(ChangeBlockEvent.Decay event) {
onChangeBlock(event);
}
@Listener public void onBlockBreak(ChangeBlockEvent.Grow event) {
onChangeBlock(event);
}
@Listener public void onBlockBreak(ChangeBlockEvent.Modify event) {
onChangeBlock(event);
}
@Listener public void onBlockBreak(ChangeBlockEvent.Break event) {
Player player = SpongeUtil.getCause(event.getCause(), Player.class);
if (player == null) {
//SpongeUtil.printCause("break", event.getCause());
return;
}
PlotPlayer pp = SpongeUtil.getPlayer(player);
List<Transaction<BlockSnapshot>> transactions = event.getTransactions();
Transaction<BlockSnapshot> first = transactions.get(0);
BlockSnapshot original = first.getOriginal();
Optional<World> world = SpongeMain.THIS.getServer().getWorld(original.getWorldUniqueId());
String worldName = world.get().getName();
Location loc = SpongeUtil.getLocation(worldName, original.getPosition());
Plot plot = loc.getPlot();
if (plot == null) {
if (!loc.isPlotArea()) {
return;
}
if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) {
MainUtil.sendMessage(pp, C.PERMISSION_ADMIN_DESTROY_ROAD);
event.setCancelled(true);
return;
}
} else if (transactions.size() == 1) {
if (!plot.hasOwner()) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) {
return;
}
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED);
event.setCancelled(true);
return;
}
if (plot.isAdded(pp.getUUID()) || Permissions
.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) {
return;
} else {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER);
com.google.common.base.Optional<HashSet<PlotBlock>> destroy =
plot.getFlag(Flags.BREAK);
BlockState state = original.getState();
if (!destroy.isPresent() || !destroy.get()
.contains(SpongeUtil.getPlotBlock(state))) {
event.setCancelled(true);
return;
}
}
}
event.filter(l -> {
Location loc1 = SpongeUtil.getLocation(worldName, l);
PlotArea area = loc1.getPlotArea();
if (area == null) {
return true;
}
Plot plot1 = area.getPlot(loc1);
if (plot1 == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD, true);
}
if (!plot1.hasOwner()) {
if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED, true)) {
return false;
}
return true;
}
if (!plot1.isAdded(pp.getUUID()) && !Permissions
.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER, true)) {
com.google.common.base.Optional<HashSet<PlotBlock>> destroy =
plot1.getFlag(Flags.BREAK);
BlockState state = l.getBlock();
if (destroy.isPresent() && destroy.get().contains(SpongeUtil.getPlotBlock(state))) {
return true;
}
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER);
return false;
}
return true;
});
}
@Listener public void onBlockPlace(ChangeBlockEvent.Pre event) {
Player player = SpongeUtil.getCause(event.getCause(), Player.class);
if (player == null) {
return;
}
PlotPlayer pp = SpongeUtil.getPlayer(player);
List<org.spongepowered.api.world.Location<World>> locs = event.getLocations();
org.spongepowered.api.world.Location<World> first = locs.get(0);
String worldName = first.getExtent().getName();
Location loc = SpongeUtil.getLocation(worldName, first.getPosition());
PlotArea area = loc.getPlotArea();
if (area == null) {
return;
}
Plot plot = area.getPlot(loc);
if (plot == null) {
if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD, true)) {
event.setCancelled(true);
}
return;
}
if (plot.hasOwner()) {
if (plot.isAdded(pp.getUUID()) || Permissions
.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) {
return;
} else {
com.google.common.base.Optional<HashSet<PlotBlock>> place =
plot.getFlag(Flags.PLACE);
BlockState state = first.getBlock();
if (!place.isPresent() || !place.get().contains(SpongeUtil.getPlotBlock(state))) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER);
event.setCancelled(true);
return;
}
}
} else {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) {
return;
}
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED);
event.setCancelled(true);
return;
}
}
@Listener public void onBlockPlace(ChangeBlockEvent.Place event) {
Player player = SpongeUtil.getCause(event.getCause(), Player.class);
if (player == null) {
return;
}
PlotPlayer pp = SpongeUtil.getPlayer(player);
List<Transaction<BlockSnapshot>> transactions = event.getTransactions();
Transaction<BlockSnapshot> first = transactions.get(0);
BlockSnapshot pos = first.getOriginal();
Optional<World> world = SpongeMain.THIS.getServer().getWorld(pos.getWorldUniqueId());
String worldName = world.get().getName();
Location loc = SpongeUtil.getLocation(worldName, pos.getPosition());
PlotArea area = loc.getPlotArea();
if (area == null) {
return;
}
Plot plot = area.getPlot(loc);
if (plot == null) {
if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD, true)) {
event.setCancelled(true);
return;
}
} else if (transactions.size() == 1) {
if (plot.hasOwner()) {
if (plot.isAdded(pp.getUUID()) || Permissions
.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) {
return;
} else {
com.google.common.base.Optional<HashSet<PlotBlock>> place =
plot.getFlag(Flags.PLACE);
BlockState state = pos.getState();
if (!place.isPresent() || !place.get()
.contains(SpongeUtil.getPlotBlock(state))) {
MainUtil
.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER);
event.setCancelled(true);
return;
}
}
} else {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) {
return;
}
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED);
event.setCancelled(true);
return;
}
} else {
event.filter(new Predicate<org.spongepowered.api.world.Location<World>>() {
@Override public boolean test(org.spongepowered.api.world.Location<World> l) {
Location loc = SpongeUtil.getLocation(worldName, l);
Plot plot = loc.getPlot();
if (plot == null) {
return loc.getPlotArea() == null || Permissions
.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD, true);
}
if (!plot.hasOwner()) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED, true)) {
return true;
}
return false;
}
if (plot.isAdded(pp.getUUID()) || Permissions
.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER, true)) {
return true;
} else {
com.google.common.base.Optional<HashSet<PlotBlock>> place =
plot.getFlag(Flags.PLACE);
BlockState state = l.getBlock();
if (place.isPresent() && place.get()
.contains(SpongeUtil.getPlotBlock(state))) {
return true;
}
MainUtil
.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER);
return false;
}
}
});
}
}
@Listener public void onJoin(ClientConnectionEvent.Join event) {
Player player = event.getTargetEntity();
SpongeUtil.getPlayer(player).unregister();
PlotPlayer pp = SpongeUtil.getPlayer(player);
// Now
String name = pp.getName();
StringWrapper sw = new StringWrapper(name);
UUID uuid = pp.getUUID();
UUIDHandler.add(sw, uuid);
Location loc = pp.getLocation();
PlotArea area = loc.getPlotArea();
Plot plot;
if (area != null) {
plot = area.getPlot(loc);
if (plot != null) {
PlotListener.plotEntry(pp, plot);
}
} else {
plot = null;
}
// Delayed
// Async
TaskManager.runTaskLaterAsync(() -> EventUtil.manager.doJoinTask(pp), 20);
}
@Listener public void onQuit(ClientConnectionEvent.Disconnect event) {
Player player = event.getTargetEntity();
PlotPlayer pp = SpongeUtil.getPlayer(player);
pp.unregister();
}
@Listener public void onMove(MoveEntityEvent event) {
if (!(event.getTargetEntity() instanceof Player)) {
return;
}
org.spongepowered.api.world.Location<World> from = event.getFromTransform().getLocation();
org.spongepowered.api.world.Location<World> to = event.getToTransform().getLocation();
int x2;
if (MathMan.roundInt(from.getX()) != (x2 = MathMan.roundInt(to.getX()))) {
Player player = (Player) event.getTargetEntity();
PlotPlayer pp = SpongeUtil.getPlayer(player);
// Cancel teleport
TaskManager.TELEPORT_QUEUE.remove(pp.getName());
// Set last location
Location loc = SpongeUtil.getLocation(to);
pp.setMeta("location", loc);
PlotArea area = loc.getPlotArea();
if (area == null) {
pp.deleteMeta(PlotPlayer.META_LAST_PLOT);
return;
}
Plot now = area.getPlotAbs(loc);
Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT);
if (now == null) {
if (lastPlot != null && !PlotListener.plotExit(pp, lastPlot)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED);
if (lastPlot.equals(SpongeUtil.getLocation(from).getPlot())) {
player.setLocation(from);
} else {
player.setLocation(player.getWorld().getSpawnLocation());
}
event.setCancelled(true);
return;
}
} else if (now.equals(lastPlot)) {
ForceFieldListener.handleForcefield(player, pp, now);
return;
} else if (!PlotListener.plotEntry(pp, now)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED);
player.setLocation(from);
event.setCancelled(true);
return;
}
Integer border = area.getBorder();
if (x2 > border) {
to.sub(x2 - border + 4, 0, 0);
player.setLocation(to);
MainUtil.sendMessage(pp, C.BORDER);
return;
} else if (x2 < -border) {
to.add(border - x2 + 4, 0, 0);
player.setLocation(to);
MainUtil.sendMessage(pp, C.BORDER);
return;
}
return;
}
int z2;
if (MathMan.roundInt(from.getZ()) != (z2 = MathMan.roundInt(to.getZ()))) {
Player player = (Player) event.getTargetEntity();
PlotPlayer pp = SpongeUtil.getPlayer(player);
// Cancel teleport
TaskManager.TELEPORT_QUEUE.remove(pp.getName());
// Set last location
Location loc = SpongeUtil.getLocation(to);
pp.setMeta(PlotPlayer.META_LOCATION, loc);
PlotArea area = loc.getPlotArea();
if (area == null) {
pp.deleteMeta(PlotPlayer.META_LAST_PLOT);
return;
}
Plot now = area.getPlotAbs(loc);
Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT);
if (now == null) {
if (lastPlot != null && !PlotListener.plotExit(pp, lastPlot)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED);
if (lastPlot.equals(SpongeUtil.getLocation(from).getPlot())) {
player.setLocation(from);
} else {
player.setLocation(player.getWorld().getSpawnLocation());
}
event.setCancelled(true);
return;
}
} else if (now.equals(lastPlot)) {
ForceFieldListener.handleForcefield(player, pp, now);
return;
} else if (!PlotListener.plotEntry(pp, now)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED);
player.setLocation(from);
event.setCancelled(true);
return;
}
Integer border = area.getBorder();
if (z2 > border) {
to.add(0, 0, z2 - border - 4);
player.setLocation(to);
MainUtil.sendMessage(pp, C.BORDER);
} else if (z2 < -border) {
to.add(0, 0, border - z2 + 4);
player.setLocation(to);
MainUtil.sendMessage(pp, C.BORDER);
}
}
}
}

View file

@ -1,25 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.listener;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.world.LoadWorldEvent;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.gen.GenerationPopulator;
import org.spongepowered.api.world.gen.WorldGenerator;
public class WorldEvents {
@Listener public void onLoadWorld(LoadWorldEvent event) {
final World world = event.getTargetWorld();
final String name = world.getName();
WorldGenerator generator = world.getWorldGenerator();
GenerationPopulator terrain = generator.getBaseGenerationPopulator();
if (terrain instanceof GeneratorWrapper) {
GeneratorWrapper stg = (GeneratorWrapper) terrain;
PlotSquared.get().loadWorld(name, stg);
} else {
PlotSquared.get().loadWorld(name, null);
}
}
}

View file

@ -1,31 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.object;
import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer;
import org.spongepowered.api.entity.living.player.User;
import java.util.UUID;
public class SpongeOfflinePlayer implements OfflinePlotPlayer {
private User user;
public SpongeOfflinePlayer(User user) {
this.user = user;
}
@Override public UUID getUUID() {
return user.getUniqueId();
}
@Override public long getLastPlayed() {
return 0; //todo
}
@Override public boolean isOnline() {
return user.isOnline();
}
@Override public String getName() {
return user.getName();
}
}

View file

@ -1,251 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.object;
import com.flowpowered.math.vector.Vector3d;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.commands.RequiredType;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.TeleportCause;
import com.github.intellectualsites.plotsquared.plot.util.PlotGameMode;
import com.github.intellectualsites.plotsquared.plot.util.PlotWeather;
import com.github.intellectualsites.plotsquared.plot.util.StringMan;
import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.mutable.TargetedLocationData;
import org.spongepowered.api.effect.sound.SoundTypes;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.gamemode.GameMode;
import org.spongepowered.api.entity.living.player.gamemode.GameModes;
import org.spongepowered.api.service.ban.BanService;
import org.spongepowered.api.text.chat.ChatTypes;
import org.spongepowered.api.text.serializer.TextSerializers;
import org.spongepowered.api.util.Tristate;
import org.spongepowered.api.world.World;
import java.util.Optional;
import java.util.UUID;
public class SpongePlayer extends PlotPlayer {
public final Player player;
private UUID uuid;
private String name;
public SpongePlayer(Player player) {
this.player = player;
super.populatePersistentMetaMap();
}
@Override public RequiredType getSuperCaller() {
return RequiredType.PLAYER;
}
@Override public Location getLocation() {
Location location = super.getLocation();
if (location == null) {
return SpongeUtil.getLocation(this.player);
} else {
return location;
}
}
@Override public Location getLocationFull() {
return SpongeUtil.getLocationFull(this.player);
}
@Override public UUID getUUID() {
if (this.uuid == null) {
this.uuid = UUIDHandler.getUUID(this);
}
return this.uuid;
}
@Override public long getLastPlayed() {
return this.player.lastPlayed().get().toEpochMilli();
}
@Override public boolean hasPermission(String permission) {
return this.player.hasPermission(permission);
}
@Override public boolean isPermissionSet(String permission) {
Tristate state =
this.player.getPermissionValue(this.player.getActiveContexts(), permission);
return state != Tristate.UNDEFINED;
}
@Override public void sendMessage(String message) {
if (!StringMan.isEqual(this.getMeta("lastMessage"), message) || (
System.currentTimeMillis() - this.<Long>getMeta("lastMessageTime") > 5000)) {
setMeta("lastMessage", message);
setMeta("lastMessageTime", System.currentTimeMillis());
this.player.sendMessage(ChatTypes.CHAT,
TextSerializers.LEGACY_FORMATTING_CODE.deserialize(message));
}
}
@Override public void teleport(Location location, TeleportCause cause) {
if ((Math.abs(location.getX()) >= 30000000) || (Math.abs(location.getZ()) >= 30000000)) {
return;
}
String world = this.player.getWorld().getName();
if (!world.equals(location.getWorld())) {
this.player.transferToWorld(location.getWorld(),
new Vector3d(location.getX(), location.getY(), location.getZ()));
} else {
org.spongepowered.api.world.Location<World> current = this.player.getLocation();
current = current
.setPosition(new Vector3d(location.getX(), location.getY(), location.getZ()));
this.player.setLocation(current);
}
}
@Override public boolean isOnline() {
return this.player.isOnline();
}
@Override public String getName() {
if (this.name == null) {
this.name = this.player.getName();
}
return this.name;
}
@Override public void setCompassTarget(Location location) {
Optional<TargetedLocationData> target = this.player.getOrCreate(TargetedLocationData.class);
if (target.isPresent()) {
target.get()
.set(Keys.TARGETED_LOCATION, SpongeUtil.getLocation(location).getPosition());
} else {
PlotSquared.debug("Failed to set compass target.");
}
}
@Override public void setWeather(PlotWeather weather) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public PlotGameMode getGameMode() {
GameMode gamemode = this.player.getGameModeData().type().get();
if (gamemode == GameModes.ADVENTURE) {
return PlotGameMode.ADVENTURE;
} else if (gamemode == GameModes.CREATIVE) {
return PlotGameMode.CREATIVE;
} else if (gamemode == GameModes.SPECTATOR) {
return PlotGameMode.SPECTATOR;
} else if (gamemode == GameModes.SURVIVAL) {
return PlotGameMode.SURVIVAL;
} else {
return PlotGameMode.NOT_SET;
}
}
@Override public void setGameMode(PlotGameMode gameMode) {
switch (gameMode) {
case ADVENTURE:
this.player.offer(Keys.GAME_MODE, GameModes.ADVENTURE);
return;
case CREATIVE:
this.player.offer(Keys.GAME_MODE, GameModes.CREATIVE);
return;
case SPECTATOR:
this.player.offer(Keys.GAME_MODE, GameModes.SPECTATOR);
return;
case SURVIVAL:
this.player.offer(Keys.GAME_MODE, GameModes.SURVIVAL);
return;
case NOT_SET:
this.player.offer(Keys.GAME_MODE, GameModes.NOT_SET);
}
}
@Override public void setTime(long time) {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public boolean getFlight() {
Optional<Boolean> flying = player.get(Keys.CAN_FLY);
return flying.isPresent() && flying.get();
}
@Override public void setFlight(boolean fly) {
this.player.offer(Keys.IS_FLYING, fly);
this.player.offer(Keys.CAN_FLY, fly);
}
@Override public void playMusic(Location location, int id) {
switch (id) {
case 0:
//Placeholder because Sponge doesn't have a stopSound() implemented yet.
this.player.playSound(SoundTypes.BLOCK_CLOTH_PLACE,
SpongeUtil.getLocation(location).getPosition(), 0);
break;
case 2256:
this.player
.playSound(SoundTypes.RECORD_11, SpongeUtil.getLocation(location).getPosition(),
1);
break;
case 2257:
this.player
.playSound(SoundTypes.RECORD_13, SpongeUtil.getLocation(location).getPosition(),
1);
break;
case 2258:
this.player.playSound(SoundTypes.RECORD_BLOCKS,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2259:
this.player.playSound(SoundTypes.RECORD_CAT,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2260:
this.player.playSound(SoundTypes.RECORD_CHIRP,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2261:
this.player.playSound(SoundTypes.RECORD_FAR,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2262:
this.player.playSound(SoundTypes.RECORD_MALL,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2263:
this.player.playSound(SoundTypes.RECORD_MELLOHI,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2264:
this.player.playSound(SoundTypes.RECORD_STAL,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2265:
this.player.playSound(SoundTypes.RECORD_STRAD,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2266:
this.player.playSound(SoundTypes.RECORD_WAIT,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2267:
this.player.playSound(SoundTypes.RECORD_WARD,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
}
}
@Override public void kick(String message) {
this.player.kick(SpongeUtil.getText(message));
}
@Override public void stopSpectating() {
//Not Implemented
}
@Override public boolean isBanned() {
Optional<BanService> service = Sponge.getServiceManager().provide(BanService.class);
return service.isPresent() && service.get().isBanned(this.player.getProfile());
}
}

View file

@ -1,8 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util;
public class KillRoadMobs {
public void run() {
// TODO kill road mobs
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
}

View file

@ -1,147 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotMessage;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.ChatManager;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextColor;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.text.format.TextStyle;
import org.spongepowered.api.text.format.TextStyles;
import java.util.List;
public class SpongeChatManager extends ChatManager<Text.Builder> {
@Override public Text.Builder builder() {
return Text.builder();
}
@Override public void color(PlotMessage message, String color) {
TextColor tc = null;
TextStyle ts = null;
switch (color.charAt(1)) {
case 'a':
tc = TextColors.GREEN;
break;
case 'b':
tc = TextColors.AQUA;
break;
case 'c':
tc = TextColors.RED;
break;
case 'd':
tc = TextColors.LIGHT_PURPLE;
break;
case 'e':
tc = TextColors.YELLOW;
break;
case 'f':
tc = TextColors.WHITE;
break;
case '1':
tc = TextColors.DARK_BLUE;
break;
case '2':
tc = TextColors.DARK_GREEN;
break;
case '3':
tc = TextColors.DARK_AQUA;
break;
case '4':
tc = TextColors.DARK_RED;
break;
case '5':
tc = TextColors.DARK_PURPLE;
break;
case '6':
tc = TextColors.GOLD;
break;
case '7':
tc = TextColors.GRAY;
break;
case '8':
tc = TextColors.DARK_GRAY;
break;
case '9':
tc = TextColors.BLUE;
break;
case '0':
tc = TextColors.BLACK;
break;
case 'k':
ts = TextStyles.OBFUSCATED;
break;
case 'l':
ts = TextStyles.BOLD;
break;
case 'm':
ts = TextStyles.UNDERLINE;
break;
case 'n':
ts = TextStyles.STRIKETHROUGH;
break;
case 'o':
ts = TextStyles.ITALIC;
break;
case 'r':
tc = TextColors.RESET;
break;
}
if (tc != null) {
apply(message, getChild(message).color(tc));
}
if (ts != null) {
apply(message, getChild(message).style(ts));
}
}
public Text.Builder getChild(PlotMessage m) {
Text.Builder builder = m.$(this);
List<Text> children = builder.getChildren();
Text last = children.get(children.size() - 1);
builder.remove(last);
return Text.builder().append(last);
}
public void apply(PlotMessage m, Text.Builder builder) {
m.$(this).append(builder.build());
}
@Override public void tooltip(PlotMessage message, PlotMessage... tooltips) {
Text.Builder builder = Text.builder();
boolean lb = false;
for (PlotMessage tooltip : tooltips) {
if (lb) {
builder.append(Text.of("\n"));
}
builder.append(tooltip.$(this).build());
lb = true;
}
apply(message, getChild(message).onHover(TextActions.showText(builder.toText())));
}
@Override public void command(PlotMessage message, String command) {
apply(message, getChild(message).onClick(TextActions.runCommand(command)));
}
@Override public void text(PlotMessage message, String text) {
message.$(this).append(SpongeUtil.getText(text));
}
@Override public void send(PlotMessage plotMessage, PlotPlayer player) {
if (player instanceof ConsolePlayer || !Settings.Chat.INTERACTIVE) {
player.sendMessage(plotMessage.$(this).build().toPlain());
} else {
((SpongePlayer) player).player.sendMessage(plotMessage.$(this).build());
}
}
@Override public void suggest(PlotMessage plotMessage, String command) {
apply(plotMessage, getChild(plotMessage).onClick(TextActions.suggestCommand(command)));
}
}

View file

@ -1,117 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.object.BlockVector2;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.util.ChunkManager;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.living.Living;
import org.spongepowered.api.entity.living.animal.Animal;
import org.spongepowered.api.entity.living.monster.Monster;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.world.Chunk;
import org.spongepowered.api.world.World;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
public class SpongeChunkManager extends ChunkManager {
@Override public int[] countEntities(Plot plot) {
Location pos1 = plot.getBottomAbs();
Location pos2 = plot.getTopAbs();
World world = SpongeUtil.getWorld(pos1.getWorld());
int bx = pos1.getX();
int bz = pos1.getZ();
int tx = pos2.getX();
int tz = pos2.getZ();
int[] count = new int[6];
world.getEntities(entity -> {
org.spongepowered.api.world.Location loc = entity.getLocation();
int x = loc.getBlockX();
if ((x >= bx) && (x <= tx)) {
int z = loc.getBlockZ();
if ((z >= bz) && (z <= tz)) {
count[0]++;
if (entity instanceof Living) {
count[3]++;
if (entity instanceof Animal) {
count[1]++;
} else if (entity instanceof Monster) {
count[2]++;
}
} else {
count[4]++;
}
}
}
return false;
});
return count;
}
@Override public boolean loadChunk(String world, BlockVector2 loc, boolean force) {
World worldObj = SpongeUtil.getWorld(world);
return worldObj.loadChunk(loc.x << 4, 0, loc.z << 4, force).isPresent();
}
@Override public Set<BlockVector2> getChunkChunks(String world) {
// TODO save world;
return super.getChunkChunks(world);
}
@Override
public boolean copyRegion(Location pos1, Location pos2, Location newPos, Runnable whenDone) {
// TODO copy a region
TaskManager.runTask(whenDone);
return false;
}
@Override public void clearAllEntities(Location pos1, Location pos2) {
String worldName = pos1.getWorld();
World world = SpongeUtil.getWorld(worldName);
int bx = pos1.getX();
int bz = pos1.getZ();
int tx = pos2.getX();
int tz = pos2.getZ();
world.getEntities(new Predicate<Entity>() {
@Override public boolean test(Entity entity) {
org.spongepowered.api.world.Location loc = entity.getLocation();
int x = loc.getBlockX();
if ((x >= bx) && (x <= tx)) {
int z = loc.getBlockZ();
if ((z >= bz) && (z <= tz)) {
if (!(entity instanceof Player)) {
entity.remove();
}
}
}
return false;
}
});
}
@Override public void swap(Location bot1, Location top1, Location bot2, Location top2,
Runnable whenDone) {
// TODO swap region
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public void unloadChunk(String world, BlockVector2 loc, boolean save, boolean safe) {
World worldObj = SpongeUtil.getWorld(world);
Optional<Chunk> chunk = worldObj.getChunk(loc.x << 4, 0, loc.z << 4);
if (chunk.isPresent()) {
worldObj.unloadChunk(chunk.get());
}
}
@Override public boolean regenerateRegion(Location pos1, Location pos2, boolean ignoreAugment,
Runnable whenDone) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
}

View file

@ -1,87 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.commands.MainCommand;
import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import com.google.common.collect.ImmutableList;
import org.spongepowered.api.command.CommandCallable;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
public class SpongeCommand implements CommandCallable {
@Override public CommandResult process(CommandSource source, String arguments)
throws CommandException {
TaskManager.runTask(() -> {
String id = source.getIdentifier();
PlotPlayer plotPlayer = null;
try {
UUID uuid = UUID.fromString(id);
Optional<Player> player = SpongeMain.THIS.getServer().getPlayer(uuid);
if (player.isPresent()) {
plotPlayer = SpongeUtil.getPlayer(player.get());
}
} catch (Exception ignored) {
plotPlayer = ConsolePlayer.getConsole();
}
MainCommand.onCommand(plotPlayer,
arguments.isEmpty() ? new String[] {} : arguments.split(" "));
});
return CommandResult.success();
}
@Override public List<String> getSuggestions(CommandSource source, String arguments,
Location<World> targetPosition) throws CommandException {
if (!(source instanceof Player)) {
return ImmutableList.of();
}
PlotPlayer player = SpongeUtil.getPlayer((Player) source);
String[] args = arguments.split(" ");
if (args.length == 0) {
return Collections.singletonList(MainCommand.getInstance().toString());
}
Collection objects = MainCommand.getInstance().tab(player, args, arguments.endsWith(" "));
if (objects != null && !objects.isEmpty()) {
List<String> result = new ArrayList<>();
for (Object o : objects) {
result.add(o.toString());
}
return result;
}
List<String> names = new ArrayList<>();
String startsWith = arguments.endsWith(" ") ? "" : args[args.length - 1];
for (Map.Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) {
String name = entry.getKey();
if (name.startsWith(startsWith)) {
names.add(name);
}
}
return names;
}
@Override public boolean testPermission(CommandSource source) {
return true;
}
@Override public Optional<Text> getShortDescription(CommandSource source) {
return Optional.of(Text.of("Shows plot help"));
}
@Override public Optional<Text> getHelp(CommandSource source) {
return Optional.of(Text.of("/plot"));
}
@Override public Text getUsage(CommandSource source) {
return Text.of("/plot <command>");
}
}

View file

@ -1,84 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.EconHandler;
import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.service.ChangeServiceProviderEvent;
import org.spongepowered.api.service.economy.EconomyService;
import org.spongepowered.api.service.economy.account.UniqueAccount;
import java.math.BigDecimal;
import java.util.Optional;
public class SpongeEconHandler extends EconHandler {
private EconomyService econ;
public SpongeEconHandler() {
if (Sponge.getServiceManager().isRegistered(EconomyService.class)) {
econ = Sponge.getServiceManager().provide(EconomyService.class).get();
}
}
@Listener public void onChangeServiceProvider(ChangeServiceProviderEvent event) {
if (event.getService().equals(EconomyService.class)) {
econ = (EconomyService) event.getNewProviderRegistration().getProvider();
}
}
@Override public void withdrawMoney(PlotPlayer player, double amount) {
if (econ != null) {
Optional<UniqueAccount> accOpt = econ.getOrCreateAccount(player.getUUID());
if (accOpt.isPresent()) {
UniqueAccount acc = accOpt.get();
acc.withdraw(econ.getDefaultCurrency(), new BigDecimal(amount), SpongeUtil.CAUSE);
}
}
}
@Override public void depositMoney(PlotPlayer player, double amount) {
if (econ != null) {
Optional<UniqueAccount> accOpt = econ.getOrCreateAccount(player.getUUID());
if (accOpt.isPresent()) {
UniqueAccount acc = accOpt.get();
acc.deposit(econ.getDefaultCurrency(), new BigDecimal(amount), SpongeUtil.CAUSE);
}
}
}
@Override public void depositMoney(OfflinePlotPlayer player, double amount) {
if (econ != null) {
Optional<UniqueAccount> accOpt = econ.getOrCreateAccount(player.getUUID());
if (accOpt.isPresent()) {
UniqueAccount acc = accOpt.get();
acc.deposit(econ.getDefaultCurrency(), new BigDecimal(amount), SpongeUtil.CAUSE);
}
}
}
@Override public boolean hasPermission(String world, String player, String perm) {
SpongePlayer obj = (SpongePlayer) UUIDHandler.getPlayer(player);
if (obj != null) {
return obj.player.hasPermission(perm);
}
// TODO offline
return false;
}
@Override public double getBalance(PlotPlayer player) {
if (econ != null) {
Optional<UniqueAccount> accOpt = econ.getOrCreateAccount(player.getUUID());
if (accOpt.isPresent()) {
UniqueAccount acc = accOpt.get();
BigDecimal balance = acc.getBalance(econ.getDefaultCurrency());
return balance.doubleValue();
}
}
return 0;
}
}

View file

@ -1,103 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.util.EventUtil;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import com.github.intellectualsites.plotsquared.sponge.events.*;
import org.spongepowered.api.event.Event;
import org.spongepowered.api.event.EventManager;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.UUID;
public class SpongeEventUtil extends EventUtil {
public EventManager events;
public SpongeEventUtil() {
this.events = SpongeMain.THIS.getGame().getEventManager();
}
public boolean callEvent(Event event) {
return !this.events.post(event);
}
@Override public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) {
return callEvent(new PlayerClaimPlotEvent(SpongeUtil.getPlayer(player), plot, auto));
}
@Override public boolean callTeleport(PlotPlayer player, Location from, Plot plot) {
return callEvent(new PlayerTeleportToPlotEvent(SpongeUtil.getPlayer(player), from, plot));
}
@Override public boolean callComponentSet(Plot plot, String component) {
return callEvent(new PlotComponentSetEvent(plot, component));
}
@Override public boolean callClear(Plot plot) {
return callEvent(new PlotClearEvent(plot));
}
@Override public void callDelete(Plot plot) {
callEvent(new PlotDeleteEvent(plot));
}
@Override public boolean callFlagAdd(Flag flag, Plot plot) {
return callEvent(new PlotFlagAddEvent(flag, plot));
}
@Override public boolean callFlagRemove(Flag<?> flag, Plot plot, Object value) {
return callEvent(new PlotFlagRemoveEvent(flag, plot));
}
@Override public boolean callMerge(Plot plot, ArrayList<PlotId> plots) {
return callEvent(new PlotMergeEvent(SpongeUtil.getWorld(plot.getWorldName()), plot, plots));
}
@Override public boolean callUnlink(PlotArea area, ArrayList<PlotId> plots) {
return callEvent(new PlotUnlinkEvent(SpongeUtil.getWorld(area.getWorldName()), plots));
}
@Override public void callEntry(PlotPlayer player, Plot plot) {
callEvent(new PlayerEnterPlotEvent(SpongeUtil.getPlayer(player), plot));
}
@Override public void callLeave(PlotPlayer player, Plot plot) {
callEvent(new PlayerLeavePlotEvent(SpongeUtil.getPlayer(player), plot));
}
@Override public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotDeniedEvent(SpongeUtil.getPlayer(initiator), plot, player, added));
}
@Override public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotTrustedEvent(SpongeUtil.getPlayer(initiator), plot, player, added));
}
@Override public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotHelperEvent(SpongeUtil.getPlayer(initiator), plot, player, added));
}
@Override
public boolean callOwnerChange(PlotPlayer initiator, Plot plot, UUID oldOwner, UUID newOwner,
boolean hasOldOwner) {
return callEvent(
new PlotChangeOwnerEvent(SpongeUtil.getPlayer(initiator), plot, oldOwner, newOwner,
hasOldOwner));
}
@Override public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) {
return callEvent(new ClusterFlagRemoveEvent(flag, cluster));
}
@Override @Nullable public Rating callRating(PlotPlayer player, Plot plot, Rating rating) {
PlotRateEvent event = new PlotRateEvent(player, rating, plot);
this.events.post(event);
if (event.isCancelled()) {
return null;
}
return event.getRating();
}
}

View file

@ -1,15 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils;
import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper;
import com.github.intellectualsites.plotsquared.plot.object.RunnableVal;
import com.github.intellectualsites.plotsquared.plot.util.expiry.PlotAnalysis;
public class SpongeHybridUtils extends HybridUtils {
@Override public void analyzeRegion(String world, RegionWrapper region,
RunnableVal<PlotAnalysis> whenDone) {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
}

View file

@ -1,111 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.object.PlotInventory;
import com.github.intellectualsites.plotsquared.plot.object.PlotItemStack;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.InventoryUtil;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.item.ItemType;
import org.spongepowered.api.item.ItemTypes;
import org.spongepowered.api.item.inventory.Carrier;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.item.inventory.type.CarriedInventory;
import java.util.ArrayList;
public class SpongeInventoryUtil extends InventoryUtil {
public ItemStack.Builder builder;
public SpongeInventoryUtil() {
builder = SpongeMain.THIS.getGame().getRegistry().createBuilder(ItemStack.Builder.class);
}
@Override public void open(final PlotInventory inv) {
/*
// TODO Auto-generated method stub
final SpongePlayer sp = (SpongePlayer) inv.player;
final Player player = sp.player;
final CustomInventory inventory = Inventory.builder().of(InventoryArchetypes.MENU_ROW)property("test",
InventoryTitle.of(org.spongepowered.api.text.Text.of(inv.getTitle())))
.property("size",org.spongepowered.api.item.inventory.property.InventoryDimension.)
//name(SpongeUtil.getTranslation(inv.getTitle())).size(inv.size).build();
final PlotItemStack[] items = inv.getItems();
for (int i = 0; i < (inv.size * 9); i++) {
final PlotItemStack item = items[i];
if (item != null) {
inventory.set(new SlotIndex(i), getItem(item));
}
}
inv.player.setMeta("inventory", inv);
player.openInventory(inventory, SpongeUtil.CAUSE);
*/
throw new UnsupportedOperationException("Broken as of 1.11");
}
public ItemStack getItem(final PlotItemStack item) {
// FIXME item type, item data, item name, item lore
return builder.itemType(ItemTypes.SPONGE).quantity(item.amount).build();
}
@Override public void close(final PlotInventory inv) {
if (!inv.isOpen()) {
return;
}
inv.player.deleteMeta("inventory");
final SpongePlayer sp = (SpongePlayer) inv.player;
sp.player.closeInventory();
}
@Override
public void setItem(final PlotInventory inv, final int index, final PlotItemStack item) {
if (!inv.isOpen()) {
return;
}
final SpongePlayer sp = (SpongePlayer) inv.player;
final Player player = sp.player;
player.getOpenInventory().get();
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
public PlotItemStack getItem(final ItemStack item) {
if (item == null) {
return null;
}
final ItemType type = item.getItem();
final String id = type.getId();
final int amount = item.getQuantity();
// TODO name / lore
return new PlotItemStack(id, amount, null);
}
@Override public PlotItemStack[] getItems(final PlotPlayer player) {
final SpongePlayer sp = (SpongePlayer) player;
sp.player.getInventory();
new ArrayList<PlotItemStack>();
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
// return list.toArray();
}
@Override public boolean isOpen(final PlotInventory inv) {
if (!inv.isOpen()) {
return false;
}
final SpongePlayer sp = (SpongePlayer) inv.player;
final Player player = sp.player;
if (player.isViewingInventory()) {
final CarriedInventory<? extends Carrier> inventory = player.getInventory();
return inv.getTitle().equals(inventory.getName().getId()); // TODO getId()
}
return false;
}
}

View file

@ -1,514 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.google.inject.Inject;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
import ninja.leaping.configurate.loader.ConfigurationLoader;
import org.spongepowered.api.Game;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.scheduler.Task;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream;
/*
* Copyright 2011-2013 Tyler Blair. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and contributors and should not be interpreted as representing official policies,
* either expressed or implied, of anybody else.
*/
public class SpongeMetrics {
/**
* The current revision number
*/
private final static int REVISION = 7;
/**
* The base url of the metrics domain
*/
private static final String BASE_URL = "http://report.mcstats.org";
/**
* The url used to report a server's status
*/
private static final String REPORT_URL = "/plugin/%s";
/**
* Interval of time to ping (in minutes)
*/
private static final int PING_INTERVAL = 15;
/**
* The game data is being sent for
*/
private final Game game;
/**
* The plugin this metrics submits for
*/
private final PluginContainer plugin;
/**
* Lock for synchronization
*/
private final Object optOutLock = new Object();
/**
* The plugin configuration file
*/
private CommentedConfigurationNode config;
/**
* The configuration loader
*/
private ConfigurationLoader<CommentedConfigurationNode> configurationLoader;
/**
* The plugin configuration file
*/
private File configurationFile;
/**
* Unique server id
*/
private String guid;
/**
* Debug mode
*/
private boolean debug;
/**
* The scheduled task
*/
private volatile Task task = null;
@Inject public SpongeMetrics(final Game game, final PluginContainer plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.game = game;
this.plugin = plugin;
loadConfiguration();
}
/**
* GZip compress a string of bytes
*
* @param input
* @return
*/
public static byte[] gzip(final String input) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (final IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) {
try {
gzos.close();
} catch (final IOException ignore) {
}
}
}
return baos.toByteArray();
}
/**
* Appends a json encoded key/value pair to the given string builder.
*
* @param json
* @param key
* @param value
* @throws UnsupportedEncodingException
*/
private static void appendJSONPair(final StringBuilder json, final String key,
final String value) {
boolean isValueNumeric = false;
try {
if (value.equals("0") || !value.endsWith("0")) {
Double.parseDouble(value);
isValueNumeric = true;
}
} catch (final NumberFormatException ignored) {
isValueNumeric = false;
}
if (json.charAt(json.length() - 1) != '{') {
json.append(',');
}
json.append(escapeJSON(key));
json.append(':');
if (isValueNumeric) {
json.append(value);
} else {
json.append(escapeJSON(value));
}
}
/**
* Escape a string to create a valid JSON string
*
* @param text
* @return
*/
private static String escapeJSON(final String text) {
final StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
final char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
final String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
}
/**
* Encode text as UTF-8
*
* @param text the text to encode
* @return the encoded text, as UTF-8
*/
private static String urlEncode(final String text) throws UnsupportedEncodingException {
return URLEncoder.encode(text, "UTF-8");
}
/**
* Loads the configuration
*/
private void loadConfiguration() {
configurationFile = getConfigFile();
configurationLoader = HoconConfigurationLoader.builder().setFile(configurationFile).build();
try {
if (!configurationFile.exists()) {
configurationFile.createNewFile();
config = configurationLoader.load();
config.setComment("This contains settings for MCStats: http://mcstats.org");
config.getNode("mcstats.guid").setValue(UUID.randomUUID().toString());
config.getNode("mcstats.opt-out").setValue(false);
config.getNode("mcstats.debug").setValue(false);
configurationLoader.save(config);
} else {
config = configurationLoader.load();
}
guid = config.getNode("mcstats.guid").getString();
debug = config.getNode("mcstats.debug").getBoolean();
} catch (final IOException e) {
e.printStackTrace();
}
}
/**
* Start measuring statistics. This will immediately create an async repeating task as the plugin and send the
* initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200
* ticks.
*
* @return True if statistics measuring is running, otherwise false.
*/
public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
final Task.Builder builder = game.getScheduler().createTaskBuilder();
builder.async().interval(PING_INTERVAL, TimeUnit.MINUTES).execute(new Runnable() {
private boolean firstPost = true;
@Override public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && (task != null)) {
task.cancel();
task = null;
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (final IOException e) {
if (debug) {
PlotSquared.debug("[Metrics] " + e.getMessage());
}
}
}
});
return true;
}
}
/**
* Has the server owner denied plugin metrics?
*
* @return true if metrics should be opted out of it
*/
public boolean isOptOut() {
synchronized (optOutLock) {
loadConfiguration();
return config.getNode("mcstats.opt-out").getBoolean();
}
}
/**
* Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task.
*
* @throws IOException
*/
public void enable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (isOptOut()) {
config.getNode("mcstats.opt-out").setValue(false);
configurationLoader.save(config);
}
// Enable Task, if it is not running
if (task == null) {
start();
}
}
}
/**
* Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task.
*
* @throws IOException
*/
public void disable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (!isOptOut()) {
config.getNode("mcstats.opt-out").setValue(true);
configurationLoader.save(config);
}
// Disable Task, if it is running
if (task != null) {
task.cancel();
task = null;
}
}
}
/**
* Gets the File object of the config file that should be used to store data such as the GUID and opt-out status
*
* @return the File object for the config file
*/
public File getConfigFile() {
// TODO configDir
final File configFolder = new File("config");
return new File(configFolder, "PluginMetrics.conf");
}
/**
* Generic method that posts a plugin to the metrics website
*/
private void postPlugin(final boolean isPing) throws IOException {
// Server software specific section
final String pluginName = plugin.getName();
final boolean onlineMode =
game.getServer().getOnlineMode(); // TRUE if online mode is enabled
final String pluginVersion = plugin.getVersion().orElse("unknown");
final String serverVersion =
String.format("%s %s", "Sponge", game.getPlatform().getMinecraftVersion());
final int playersOnline = game.getServer().getOnlinePlayers().size();
// END server software specific section -- all code below does not use any code outside of this class / Java
// Construct the post data
final StringBuilder json = new StringBuilder(1024);
json.append('{');
// The plugin's description file containg all of the plugin data such as name, version, author, etc
appendJSONPair(json, "guid", guid);
appendJSONPair(json, "plugin_version", pluginVersion);
appendJSONPair(json, "server_version", serverVersion);
appendJSONPair(json, "players_online", Integer.toString(playersOnline));
// New data as of R6
final String osname = System.getProperty("os.name");
String osarch = System.getProperty("os.arch");
final String osversion = System.getProperty("os.version");
final String java_version = System.getProperty("java.version");
final int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64")) {
osarch = "x86_64";
}
appendJSONPair(json, "osname", osname);
appendJSONPair(json, "osarch", osarch);
appendJSONPair(json, "osversion", osversion);
appendJSONPair(json, "cores", Integer.toString(coreCount));
appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0");
appendJSONPair(json, "java_version", java_version);
// If we're pinging, append it
if (isPing) {
appendJSONPair(json, "ping", "1");
}
// close json
json.append('}');
// Create the url
final URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName)));
// Connect to the website
URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY);
} else {
connection = url.openConnection();
}
final byte[] uncompressed = json.toString().getBytes();
final byte[] compressed = gzip(json.toString());
// Headers
connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Content-Encoding", "gzip");
connection.addRequestProperty("Content-Length", Integer.toString(compressed.length));
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true);
if (debug) {
PlotSquared.debug("[Metrics] Prepared request for " + pluginName + " uncompressed="
+ uncompressed.length + " compressed=" + compressed.length);
}
// Write the data
final OutputStream os = connection.getOutputStream();
os.write(compressed);
os.flush();
// Now read the response
final BufferedReader reader =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = reader.readLine();
// close resources
os.close();
reader.close();
if ((response == null) || response.startsWith("ERR") || response.startsWith("7")) {
if (response == null) {
response = "null";
} else if (response.startsWith("7")) {
response = response.substring(response.startsWith("7,") ? 2 : 1);
}
throw new IOException(response);
}
}
/**
* Check if mineshafter is present. If it is, we need to bypass it to send POST requests
*
* @return true if mineshafter is installed on the server
*/
private boolean isMineshafterPresent() {
try {
Class.forName("mineshafter.MineServer");
return true;
} catch (final Exception ignored) {
return false;
}
}
}

View file

@ -1,298 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.jnbt.*;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue;
import com.sk89q.worldedit.math.BlockVector2;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.item.inventory.Carrier;
import org.spongepowered.api.item.inventory.type.CarriedInventory;
import org.spongepowered.api.world.World;
import java.util.Map.Entry;
public class SpongeSchematicHandler extends SchematicHandler {
@Override
public boolean restoreTile(LocalBlockQueue queue, CompoundTag tag, int x, int y, int z) {
// TODO Auto-generated method stub
// This method should place the compound tag at a location e.g. chest contents
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public void getCompoundTag(String world, Set<RegionWrapper> regions,
RunnableVal<CompoundTag> whenDone) {
// async
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
// Main positions
Location[] corners = MainUtil.getCorners(world, regions);
Location bot = corners[0];
Location top = corners[1];
int width = top.getX() - bot.getX() + 1;
int height = top.getY() - bot.getY() + 1;
int length = top.getZ() - bot.getZ() + 1;
// Main Schematic tag
HashMap<String, Tag> schematic = new HashMap<>();
schematic.put("Width", new ShortTag("Width", (short) width));
schematic.put("Length", new ShortTag("Length", (short) length));
schematic.put("Height", new ShortTag("Height", (short) height));
schematic.put("Materials", new StringTag("Materials", "Alpha"));
schematic.put("WEOriginX", new IntTag("WEOriginX", 0));
schematic.put("WEOriginY", new IntTag("WEOriginY", 0));
schematic.put("WEOriginZ", new IntTag("WEOriginZ", 0));
schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0));
schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0));
schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0));
// Arrays of data types
List<Tag> tileEntities = new ArrayList<>();
byte[] blocks = new byte[width * height * length];
byte[] blockData = new byte[width * height * length];
// Queue
ArrayDeque<RegionWrapper> queue = new ArrayDeque<>(regions);
TaskManager.runTask(new Runnable() {
@Override public void run() {
if (queue.isEmpty()) {
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
schematic.put("Blocks", new ByteArrayTag("Blocks", blocks));
schematic.put("Data", new ByteArrayTag("Data", blockData));
schematic.put("Entities",
new ListTag("Entities", CompoundTag.class,
new ArrayList<>()));
schematic.put("TileEntities",
new ListTag("TileEntities", CompoundTag.class,
tileEntities));
whenDone.value = new CompoundTag("Schematic", schematic);
TaskManager.runTask(whenDone);
System.gc();
System.gc();
}
});
return;
}
Runnable regionTask = this;
RegionWrapper region = queue.poll();
Location pos1 = new Location(world, region.minX, region.minY, region.minZ);
Location pos2 = new Location(world, region.maxX, region.maxY, region.maxZ);
int bx = bot.getX();
int bz = bot.getZ();
int p1x = pos1.getX();
int p1z = pos1.getZ();
int p2x = pos2.getX();
int p2z = pos2.getZ();
int bcx = p1x >> 4;
int bcz = p1z >> 4;
int tcx = p2x >> 4;
int tcz = p2z >> 4;
int sy = pos1.getY();
int ey = pos2.getY();
// Generate list of chunks
ArrayList<BlockVector2> chunks = new ArrayList<>();
for (int x = bcx; x <= tcx; x++) {
for (int z = bcz; z <= tcz; z++) {
chunks.add(BlockVector2.at(x, z));
}
}
World worldObj = SpongeUtil.getWorld(world);
// Main thread
TaskManager.runTask(new Runnable() {
@Override public void run() {
long start = System.currentTimeMillis();
while (!chunks.isEmpty()
&& System.currentTimeMillis() - start < 20) {
// save schematics
BlockVector2 chunk = chunks.remove(0);
int X = chunk.x;
int Z = chunk.z;
if (!worldObj.getChunk(X, 0, Z).isPresent() && !worldObj
.loadChunk(X, 0, Z, false).isPresent()) {
continue;
}
int xxb = X << 4;
int zzb = Z << 4;
int xxt = xxb + 15;
int zzt = zzb + 15;
if (X == bcx) {
xxb = p1x;
}
if (X == tcx) {
xxt = p2x;
}
if (Z == bcz) {
zzb = p1z;
}
if (Z == tcz) {
zzt = p2z;
}
for (int y = sy; y <= Math.min(255, ey); y++) {
int ry = y - sy;
int i1 = ry * width * length;
for (int z = zzb; z <= zzt; z++) {
int rz = z - bz;
int i2 = i1 + rz * width;
for (int x = xxb; x <= xxt; x++) {
int rx = x - bx;
int index = i2 + rx;
BlockState state = worldObj.getBlock(x, y, z);
PlotBlock block = SpongeUtil.getPlotBlock(state);
int id = block.id;
switch (id) {
case 0:
case 2:
case 4:
case 13:
case 14:
case 15:
case 20:
case 21:
case 22:
case 24:
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 55:
case 56:
case 57:
case 58:
case 60:
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 85:
case 87:
case 88:
case 101:
case 102:
case 103:
case 110:
case 112:
case 113:
case 121:
case 122:
case 129:
case 133:
case 165:
case 166:
case 169:
case 170:
case 172:
case 173:
case 174:
case 181:
case 182:
case 188:
case 189:
case 190:
case 191:
case 192:
break;
case 54:
case 130:
case 142:
case 27:
case 137:
case 52:
case 154:
case 84:
case 25:
case 144:
case 138:
case 176:
case 177:
case 63:
case 68:
case 323:
case 117:
case 116:
case 28:
case 66:
case 157:
case 61:
case 62:
case 140:
case 146:
case 149:
case 150:
case 158:
case 23:
case 123:
case 124:
case 29:
case 33:
case 151:
case 178:
CompoundTag rawTag;
if (state instanceof Carrier) {
Carrier chest = (Carrier) state;
CarriedInventory<? extends Carrier>
inv = chest.getInventory();
// TODO serialize inventory
rawTag = null;
} else {
rawTag = null;
}
if (rawTag != null) {
Map<String, Tag> values =
new HashMap<>();
for (Entry<String, Tag> entry : rawTag
.getValue().entrySet()) {
values.put(entry.getKey(),
entry.getValue());
}
values.put("id",
new StringTag("id", "Chest"));
values.put("x", new IntTag("x", x));
values.put("y", new IntTag("y", y));
values.put("z", new IntTag("z", z));
CompoundTag tileEntityTag =
new CompoundTag(values);
tileEntities.add(tileEntityTag);
}
default:
blockData[index] = block.data;
}
blocks[index] = (byte) id;
}
}
}
}
if (!chunks.isEmpty()) {
TaskManager.runTaskLater(this, 1);
} else {
regionTask.run();
}
}
});
}
});
}
});
}
}

View file

@ -1,204 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.SetupObject;
import com.github.intellectualsites.plotsquared.plot.object.worlds.SingleWorldGenerator;
import com.github.intellectualsites.plotsquared.plot.util.SetupUtils;
import com.github.intellectualsites.plotsquared.sponge.generator.SpongePlotGenerator;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.world.DimensionTypes;
import org.spongepowered.api.world.GeneratorTypes;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.WorldArchetype;
import org.spongepowered.api.world.gen.WorldGenerator;
import org.spongepowered.api.world.gen.WorldGeneratorModifier;
import org.spongepowered.api.world.storage.WorldProperties;
import java.io.IOException;
import java.util.Map.Entry;
public class SpongeSetupUtils extends SetupUtils {
@Override public void updateGenerators() {
if (!SetupUtils.generators.isEmpty()) {
return;
}
SetupUtils.generators.put(PlotSquared.imp().getPluginName(),
new SpongePlotGenerator(PlotSquared.get().IMP.getDefaultGenerator()));
SetupUtils.generators.put(PlotSquared.imp().getPluginName() + ":single",
new SpongePlotGenerator(new SingleWorldGenerator()));
// TODO get external world generators
Collection<WorldGeneratorModifier> wgms =
Sponge.getRegistry().getAllOf(WorldGeneratorModifier.class);
for (WorldGeneratorModifier wgm : wgms) {
String id = wgm.getId();
String name = wgm.getName();
if (wgm instanceof GeneratorWrapper<?>) {
SetupUtils.generators.put(id, (GeneratorWrapper<?>) wgm);
SetupUtils.generators.put(name, (GeneratorWrapper<?>) wgm);
} else {
SpongePlotGenerator wrap = new SpongePlotGenerator(wgm);
SetupUtils.generators.put(id, wrap);
SetupUtils.generators.put(name, wrap);
}
}
}
@Override public void unload(String worldName, boolean safe) {
Optional<World> world = Sponge.getServer().getWorld(worldName);
if (world.isPresent()) {
Sponge.getServer().unloadWorld(world.get());
}
}
@Override public String getGenerator(PlotArea plotArea) {
if (SetupUtils.generators.isEmpty()) {
updateGenerators();
}
World world = SpongeUtil.getWorld(plotArea.getWorldName());
if (world == null) {
return null;
}
WorldGenerator generator = world.getWorldGenerator();
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public String setupWorld(SetupObject object) {
SetupUtils.manager.updateGenerators();
ConfigurationNode[] steps = object.step == null ? new ConfigurationNode[0] : object.step;
String world = object.world;
int type = object.type;
String worldPath = "worlds." + object.world;
switch (type) {
case 2: {
if (!PlotSquared.get().worlds.contains(worldPath)) {
PlotSquared.get().worlds.createSection(worldPath);
}
ConfigurationSection worldSection =
PlotSquared.get().worlds.getConfigurationSection(worldPath);
if (object.id != null) {
String areaName = object.id + "-" + object.min + "-" + object.max;
String areaPath = "areas." + areaName;
if (!worldSection.contains(areaPath)) {
worldSection.createSection(areaPath);
}
ConfigurationSection areaSection =
worldSection.getConfigurationSection(areaPath);
HashMap<String, Object> options = new HashMap<>();
for (ConfigurationNode step : steps) {
options.put(step.getConstant(), step.getValue());
}
options.put("generator.type", object.type);
options.put("generator.terrain", object.terrain);
options.put("generator.plugin", object.plotManager);
if (object.setupGenerator != null && !object.setupGenerator
.equals(object.plotManager)) {
options.put("generator.init", object.setupGenerator);
}
for (Entry<String, Object> entry : options.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (worldSection.contains(key)) {
Object current = worldSection.get(key);
if (!Objects.equals(value, current)) {
areaSection.set(key, value);
}
} else {
worldSection.set(key, value);
}
}
}
GeneratorWrapper<?> gen = SetupUtils.generators.get(object.setupGenerator);
if (gen != null && gen.isFull()) {
object.setupGenerator = null;
}
break;
}
case 1: {
if (!PlotSquared.get().worlds.contains(worldPath)) {
PlotSquared.get().worlds.createSection(worldPath);
}
ConfigurationSection worldSection =
PlotSquared.get().worlds.getConfigurationSection(worldPath);
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
PlotSquared.get().worlds.set("worlds." + world + ".generator.type", object.type);
PlotSquared.get().worlds
.set("worlds." + world + ".generator.terrain", object.terrain);
PlotSquared.get().worlds
.set("worlds." + world + ".generator.plugin", object.plotManager);
if (object.setupGenerator != null && !object.setupGenerator
.equals(object.plotManager)) {
PlotSquared.get().worlds
.set("worlds." + world + ".generator.init", object.setupGenerator);
}
GeneratorWrapper<?> gen = SetupUtils.generators.get(object.setupGenerator);
if (gen != null && gen.isFull()) {
object.setupGenerator = null;
}
break;
}
case 0: {
if (steps.length != 0) {
if (!PlotSquared.get().worlds.contains(worldPath)) {
PlotSquared.get().worlds.createSection(worldPath);
}
ConfigurationSection worldSection =
PlotSquared.get().worlds.getConfigurationSection(worldPath);
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
}
break;
}
}
try {
PlotSquared.get().worlds.save(PlotSquared.get().worldsFile);
} catch (IOException e) {
e.printStackTrace();
}
if (object.setupGenerator != null) {
// create world with generator
GeneratorWrapper<?> gw = SetupUtils.generators.get(object.setupGenerator);
WorldGeneratorModifier wgm = (WorldGeneratorModifier) gw.getPlatformGenerator();
WorldArchetype settings =
WorldArchetype.builder().loadsOnStartup(true).keepsSpawnLoaded(true)
.dimension(DimensionTypes.OVERWORLD).generator(GeneratorTypes.FLAT)
.usesMapFeatures(false).enabled(true).generatorModifiers(wgm)
.build("PS-" + UUID.randomUUID(), object.world);
WorldProperties properties = null;
try {
properties = Sponge.getServer().createWorldProperties(object.world, settings);
} catch (IOException e) {
e.printStackTrace();
}
World worldObj;
Optional<World> world1 = Sponge.getServer().loadWorld(properties);
if (world1.isPresent()) {
worldObj = world1.get();
}
System.out.println("Create normal world");
} else {
System.out.println("Create vanilla world");
// create vanilla world
WorldArchetype settings =
WorldArchetype.builder().loadsOnStartup(true).keepsSpawnLoaded(true)
.dimension(DimensionTypes.OVERWORLD).generator(GeneratorTypes.OVERWORLD)
.usesMapFeatures(true).enabled(true)
.build("PS-" + UUID.randomUUID(), object.world);
WorldProperties properties = null;
try {
properties = Sponge.getServer().createWorldProperties(object.world, settings);
} catch (IOException e) {
e.printStackTrace();
}
World worldObj = Sponge.getServer().loadWorld(properties).get();
}
return object.world;
}
}

View file

@ -1,67 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import org.spongepowered.api.scheduler.Task;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class SpongeTaskManager extends TaskManager {
private final AtomicInteger i = new AtomicInteger();
private final HashMap<Integer, Task> tasks = new HashMap<>();
private final SpongeMain spongeMain;
public SpongeTaskManager(SpongeMain spongeMain) {
this.spongeMain = spongeMain;
}
@Override public int taskRepeat(Runnable runnable, int interval) {
int val = this.i.incrementAndGet();
Task.Builder builder = this.spongeMain.getGame().getScheduler().createTaskBuilder();
Task.Builder built = builder.delayTicks(interval).intervalTicks(interval).execute(runnable);
Task task = built.submit(this.spongeMain.getPlugin());
this.tasks.put(val, task);
return val;
}
@Override public int taskRepeatAsync(Runnable runnable, int interval) {
int val = this.i.incrementAndGet();
Task.Builder builder = this.spongeMain.getGame().getScheduler().createTaskBuilder();
Task.Builder built =
builder.delayTicks(interval).async().intervalTicks(interval).execute(runnable);
Task task = built.submit(this.spongeMain.getPlugin());
this.tasks.put(val, task);
return val;
}
@Override public void taskAsync(Runnable runnable) {
Task.Builder builder = this.spongeMain.getGame().getScheduler().createTaskBuilder();
builder.async().execute(runnable).submit(this.spongeMain.getPlugin());
}
@Override public void task(Runnable runnable) {
Task.Builder builder = this.spongeMain.getGame().getScheduler().createTaskBuilder();
builder.execute(runnable).submit(this.spongeMain.getPlugin());
}
@Override public void taskLater(Runnable runnable, int delay) {
Task.Builder builder = this.spongeMain.getGame().getScheduler().createTaskBuilder();
builder.delayTicks(delay).execute(runnable).submit(this.spongeMain.getPlugin());
}
@Override public void taskLaterAsync(Runnable runnable, int delay) {
Task.Builder builder = this.spongeMain.getGame().getScheduler().createTaskBuilder();
builder.async().delayTicks(delay).execute(runnable).submit(this.spongeMain.getPlugin());
}
@Override public void cancelTask(int i) {
Task task = this.tasks.remove(i);
if (task != null) {
task.cancel();
}
}
}

View file

@ -1,17 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.AbstractTitle;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import org.spongepowered.api.text.title.Title;
public class SpongeTitleManager extends AbstractTitle {
@Override
public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) {
Title title =
Title.builder().title(SpongeUtil.getText(head)).subtitle(SpongeUtil.getText(sub))
.fadeIn(in * 20).stay(delay * 20).fadeOut(out * 20).build();
((SpongePlayer) player).player.sendTitle(title);
}
}

View file

@ -1,414 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.flowpowered.math.vector.Vector3d;
import com.flowpowered.math.vector.Vector3i;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.PlotBlock;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper;
import com.github.intellectualsites.plotsquared.plot.object.schematic.PlotItem;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.world.biome.Biome;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.block.tileentity.Sign;
import org.spongepowered.api.block.tileentity.TileEntity;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.mutable.tileentity.SignData;
import org.spongepowered.api.data.property.block.SolidCubeProperty;
import org.spongepowered.api.data.value.mutable.ListValue;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.EventContext;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.serializer.TextSerializers;
import org.spongepowered.api.text.translation.Translation;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.biome.BiomeType;
import org.spongepowered.api.world.biome.BiomeTypes;
import org.spongepowered.api.world.extent.Extent;
import java.io.IOException;
import java.lang.reflect.Field;
public class SpongeUtil extends WorldUtil {
public static Cause CAUSE =
Cause.builder().append(Sponge.getPluginManager().fromInstance(SpongeMain.THIS).get())
.build(EventContext.empty());
private static BiomeType[] biomes;
private static HashMap<String, Integer> biomeMap;
private static Player lastPlayer = null;
private static PlotPlayer lastPlotPlayer = null;
private static World lastWorld;
private static String last;
public static Location getLocation(Entity player) {
String world = player.getWorld().getName();
org.spongepowered.api.world.Location loc = player.getLocation();
Vector3i pos = loc.getBlockPosition();
return new Location(world, pos.getX(), pos.getY(), pos.getZ());
}
public static BiomeType getBiome(String biome) {
if (biomes == null) {
initBiomeCache();
}
return biomes[biomeMap.get(biome.toUpperCase())];
}
public static <T> T getCause(Cause cause, Class<T> clazz) {
Optional<?> root = Optional.of(cause.root());
if (root.isPresent()) {
Object source = root.get();
if (clazz.isInstance(source)) {
return (T) source;
}
}
return null;
}
public static void printCause(String method, Cause cause) {
System.out.println(method + ": " + cause.toString());
System.out.println(method + ": " + cause.getClass());
System.out.println(method + ": " + StringMan.getString(cause.all()));
System.out.println(method + ": " + cause.root());
}
public static void initBiomeCache() {
try {
Field[] fields = BiomeTypes.class.getFields();
biomes = new BiomeType[fields.length];
biomeMap = new HashMap<>();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
String name = field.getName();
biomeMap.put(name, i);
biomes[i] = (BiomeType) field.get(null);
}
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
public static BiomeType getBiome(int index) {
return (BiomeType) Biome.getBiome(index);
}
public static Text getText(String m) {
return TextSerializers.LEGACY_FORMATTING_CODE.deserialize(C.color(m));
}
public static Translation getTranslation(String m) {
return new Translation() {
@Override public String getId() {
return m;
}
@Override public String get(Locale l, Object... args) {
return m;
}
@Override public String get(Locale l) {
return m;
}
};
}
public static BlockState getBlockState(int id, int data) {
return (BlockState) Block.getBlockById(id).getStateFromMeta(data);
}
public static PlotBlock getPlotBlock(BlockState state) {
if (state == null) {
return PlotBlock.get(0, 0);
}
IBlockState ibs = ((IBlockState) state);
Block block = ibs.getBlock();
int id = Block.getIdFromBlock(block);
int data = block.getMetaFromState(ibs);
return PlotBlock.get(id, data);
}
public static Location getLocation(org.spongepowered.api.world.Location<World> block) {
return getLocation(block.getExtent().getName(), block);
}
public static Location getLocationFull(Entity player) {
String world = player.getWorld().getName();
Vector3d rot = player.getRotation();
float[] pitchYaw =
MathMan.getPitchAndYaw((float) rot.getX(), (float) rot.getY(), (float) rot.getZ());
org.spongepowered.api.world.Location loc = player.getLocation();
Vector3i pos = loc.getBlockPosition();
return new Location(world, pos.getX(), pos.getY(), pos.getZ(), pitchYaw[1], pitchYaw[0]);
}
public static PlotPlayer getPlayer(Player player) {
if (player == lastPlayer) {
return lastPlotPlayer;
}
String name = player.getName();
PlotPlayer pp = UUIDHandler.getPlayer(name);
if (pp != null) {
return pp;
}
lastPlotPlayer = new SpongePlayer(player);
UUIDHandler.getPlayers().put(name, lastPlotPlayer);
lastPlayer = player;
return lastPlotPlayer;
}
public static Player getPlayer(PlotPlayer player) {
if (player instanceof SpongePlayer) {
return ((SpongePlayer) player).player;
}
return null;
}
public static World getWorld(String world) {
if (StringMan.isEqual(world, last)) {
return lastWorld;
}
Optional<World> optional = Sponge.getServer().getWorld(world);
if (!optional.isPresent()) {
last = null;
return lastWorld = null;
}
last = world;
return lastWorld = optional.get();
}
public static void removePlayer(String player) {
lastPlayer = null;
lastPlotPlayer = null;
}
public static Location getLocation(String world, org.spongepowered.api.world.Location spawn) {
return new Location(world, spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ());
}
public static String getWorldName(org.spongepowered.api.world.Location origin) {
Extent extent = origin.getExtent();
if (extent == lastWorld) {
return lastWorld.getName();
}
if (extent instanceof World) {
lastWorld = (World) extent;
return lastWorld.getName();
}
return null;
}
public static org.spongepowered.api.world.Location<World> getLocation(Location location) {
Collection<World> worlds = Sponge.getServer().getWorlds();
World world = Sponge.getServer().getWorld(location.getWorld())
.orElse(worlds.toArray(new World[worlds.size()])[0]);
return new org.spongepowered.api.world.Location<>(world, location.getX(), location.getY(),
location.getZ());
}
public static Location getLocation(String world, Vector3i position) {
return new Location(world, position.getX(), position.getY(), position.getZ());
}
public static Location getLocation(String world, Vector3d position) {
return new Location(world, MathMan.roundInt(position.getX()),
MathMan.roundInt(position.getY()), MathMan.roundInt(position.getZ()));
}
@Override public boolean isBlockSolid(PlotBlock block) {
BlockState state = SpongeUtil.getBlockState(block.id, block.data);
Optional<SolidCubeProperty> property = state.getType().getProperty(SolidCubeProperty.class);
if (property.isPresent()) {
return property.get().getValue();
} else {
return false;
}
}
@Override public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) {
try {
byte data;
String[] split = name.split(":");
if (split.length == 2) {
data = Byte.parseByte(split[1]);
name = split[0];
} else {
data = 0;
}
short id;
double match;
if (MathMan.isInteger(split[0])) {
id = Short.parseShort(split[0]);
match = 0;
} else {
List<BlockType> types = ReflectionUtils.getStaticFields(BlockTypes.class);
StringComparison<BlockType>.ComparisonResult comparison =
new StringComparison<BlockType>(name,
types.toArray(new BlockType[types.size()])) {
@Override public String getString(BlockType type) {
return type.getId();
}
}.getBestMatchAdvanced();
match = comparison.match;
id = SpongeUtil.getPlotBlock(comparison.best.getDefaultState()).id;
}
PlotBlock block = PlotBlock.get(id, data);
StringComparison<PlotBlock> outer = new StringComparison<PlotBlock>();
return outer.new ComparisonResult(match, block);
} catch (NumberFormatException ignored) {
}
return null;
}
@Override public String getClosestMatchingName(PlotBlock block) {
// TODO Auto-generated method stub
return null;
}
@Override public String[] getBiomeList() {
if (biomes == null) {
initBiomeCache();
}
return biomeMap.keySet().toArray(new String[biomeMap.size()]);
}
@Override public boolean addItems(String world, PlotItem items) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public int getBiomeFromString(String biome) {
if (biomes == null) {
initBiomeCache();
}
return biomeMap.get(biome.toUpperCase());
}
@Override public String getBiome(String world, int x, int z) {
return SpongeUtil.getWorld(world).getBiome(x, 0, z).getName().toUpperCase();
}
@Override public PlotBlock getBlock(Location location) {
BlockState state = SpongeUtil.getWorld(location.getWorld())
.getBlock(location.getX(), location.getY(), location.getZ());
return SpongeUtil.getPlotBlock(state);
}
@Override public Location getSpawn(PlotPlayer plotPlayer) {
World world = getWorld(plotPlayer.getLocation().getWorld());
return SpongeUtil.getLocation(world.getSpawnLocation());
}
@Override public Location getSpawn(String world) {
Location result =
SpongeUtil.getLocation(world, SpongeUtil.getWorld(world).getSpawnLocation());
result.setY(1 + getHighestBlock(world, result.getX(), result.getZ()));
return result;
}
@Override public void setSpawn(Location location) {
World world = getWorld(location.getWorld());
if (world != null) {
world.getProperties()
.setSpawnPosition(new Vector3i(location.getX(), location.getY(), location.getZ()));
}
}
@Override public void saveWorld(String worldName) {
try {
SpongeUtil.getWorld(worldName).save();
} catch (IOException e) {
e.printStackTrace();
PlotSquared.debug("Failed to save world.");
}
}
@Override public String[] getSign(Location location) {
World world = SpongeUtil.getWorld(location.getWorld());
Optional<TileEntity> block =
world.getTileEntity(location.getX(), location.getY(), location.getZ());
if (!block.isPresent()) {
return null;
}
TileEntity tile = block.get();
if (!(tile instanceof Sign)) {
return null;
}
Sign sign = (Sign) tile;
Optional<SignData> optional = sign.get(SignData.class);
if (!optional.isPresent()) {
return null;
}
String[] result = new String[4];
ListValue<Text> lines = optional.get().lines();
for (int i = 0; i < 4; i++) {
result[i] = lines.get(i).toString();
}
return result;
}
@Override public boolean isWorld(String worldName) {
return SpongeUtil.getWorld(worldName) != null;
}
@Override public String getMainWorld() {
return Sponge.getServer().getWorlds().iterator().next().getName();
}
@Override public int getHighestBlock(String worldName, int x, int z) {
World world = SpongeUtil.getWorld(worldName);
if (world == null) {
return 63;
}
for (int y = 255; y > 0; y--) {
BlockState block = world.getBlock(x, y, z);
if (block.getType() != BlockTypes.AIR) {
return y;
}
}
return 63;
}
@Override public void setSign(String worldName, int x, int y, int z, String[] lines) {
World world = SpongeUtil.getWorld(worldName);
world.setBlock(x, y, z, BlockTypes.WALL_SIGN.getDefaultState());
Optional<TileEntity> block = world.getTileEntity(x, y, z);
if (!block.isPresent()) {
return;
}
TileEntity tile = block.get();
if (!(tile instanceof Sign)) {
return;
}
Sign sign = (Sign) tile;
List<Text> text = new ArrayList<>(4);
for (int i = 0; i < 4; i++) {
text.add(SpongeUtil.getText(lines[i]));
}
sign.offer(Keys.SIGN_LINES, text);
}
@Override public void setBiomes(String worldName, RegionWrapper region, String biomename) {
World world = SpongeUtil.getWorld(worldName);
BiomeType biome = SpongeUtil.getBiome(biomename);
for (int x = region.minX; x <= region.maxX; x++) {
for (int z = region.minZ; z <= region.maxZ; z++) {
world.setBiome(x, 0, z, biome);
}
}
}
}

View file

@ -1,83 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util.block;
import com.sk89q.worldedit.math.BlockVector2;
import com.github.intellectualsites.plotsquared.plot.object.ChunkWrapper;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.PlotBlock;
import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import org.spongepowered.api.world.biome.BiomeType;
import org.spongepowered.api.world.extent.MutableBiomeVolume;
import org.spongepowered.api.world.extent.MutableBlockVolume;
public class GenChunk extends ScopedLocalBlockQueue {
private final MutableBlockVolume terrain;
private final MutableBiomeVolume biome;
private final int bz;
private final int bx;
private final String world;
public boolean modified = false;
public GenChunk(MutableBlockVolume terrain, MutableBiomeVolume biome, ChunkWrapper wrap) {
super(null, new Location(null, 0, 0, 0), new Location(null, 15, 255, 15));
this.bx = wrap.x << 4;
this.bz = wrap.z << 4;
this.terrain = terrain;
this.biome = biome;
this.world = wrap.world;
}
@Override public void fillBiome(String biomeName) {
if (this.biome == null) {
return;
}
BiomeType biome = SpongeUtil.getBiome(biomeName.toUpperCase());
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
this.biome.setBiome(this.bx + x, 0, this.bz + z, biome);
}
}
}
@Override public boolean setBiome(int x, int z, String biomeName) {
modified = true;
BiomeType biome = SpongeUtil.getBiome(biomeName.toUpperCase());
this.biome.setBiome(this.bx + x, 0, this.bz + z, biome);
return true;
}
@Override public boolean setBlock(int x, int y, int z, int id, int data) {
modified = true;
this.terrain.setBlock(this.bx + x, y, this.bz + z, SpongeUtil.getBlockState(id, data));
return true;
}
@Override public PlotBlock getBlock(int x, int y, int z) {
return SpongeUtil.getPlotBlock(this.terrain.getBlock(this.bx + x, y, this.bz + z));
}
@Override public String getWorld() {
return this.world;
}
@Override public Location getMax() {
return new Location(getWorld(), 15 + bx, 255, 15 + bz);
}
@Override public Location getMin() {
return new Location(getWorld(), bx, 0, bz);
}
public GenChunk clone() {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
public GenChunk shallowClone() {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
}

View file

@ -1,508 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.util.block;
import com.sk89q.worldedit.math.BlockVector2;
import com.github.intellectualsites.plotsquared.plot.object.PlotBlock;
import com.github.intellectualsites.plotsquared.plot.object.PseudoRandom;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.plot.util.StringMan;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.util.block.BasicLocalBlockQueue;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityTracker;
import net.minecraft.entity.EntityTrackerEntry;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.network.play.server.SPacketChunkData;
import net.minecraft.network.play.server.SPacketDestroyEntities;
import net.minecraft.server.management.PlayerChunkMap;
import net.minecraft.util.ClassInheritanceMultiMap;
import net.minecraft.util.IntHashMap;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.WorldServer;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.biome.BiomeType;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
public class SpongeLocalQueue extends BasicLocalBlockQueue<char[]> {
private BlockState AIR = BlockTypes.AIR.getDefaultState();
public SpongeLocalQueue(String world) {
super(world);
}
@Override public LocalChunk<char[]> getLocalChunk(int x, int z) {
return new CharLocalChunk_Sponge(this, x, z) {
// Custom stuff?
};
}
@Override public void optimize() {
}
public World getSpongeWorld() {
return SpongeUtil.getWorld(getWorld());
}
@Override public PlotBlock getBlock(int x, int y, int z) {
World worldObj = getSpongeWorld();
BlockState block = worldObj.getBlock(x, y, z);
return SpongeUtil.getPlotBlock(block);
}
@Override public void refreshChunk(int x, int z) {
World world = getSpongeWorld();
Chunk nmsChunk = ((net.minecraft.world.World) world).getChunkProvider().provideChunk(x, z);
if (nmsChunk == null || !nmsChunk.isLoaded()) {
return;
}
try {
ChunkPos pos = nmsChunk.getPos();
WorldServer w = (WorldServer) nmsChunk.getWorld();
PlayerChunkMap chunkMap = w.getPlayerChunkMap();
if (!chunkMap.contains(x, z)) {
return;
}
EntityTracker tracker = w.getEntityTracker();
HashSet<EntityPlayerMP> players = new HashSet<>();
for (EntityPlayer player : w.playerEntities) {
if (player instanceof EntityPlayerMP) {
if (chunkMap.isPlayerWatchingChunk((EntityPlayerMP) player, x, z)) {
players.add((EntityPlayerMP) player);
}
}
}
if (players.isEmpty()) {
return;
}
HashSet<EntityTrackerEntry> entities = new HashSet<>();
ClassInheritanceMultiMap<Entity>[] entitieSlices = nmsChunk.getEntityLists();
IntHashMap<EntityTrackerEntry> entries = null;
for (Field field : tracker.getClass().getDeclaredFields()) {
if (field.getType() == IntHashMap.class) {
field.setAccessible(true);
entries = (IntHashMap<EntityTrackerEntry>) field.get(tracker);
}
}
for (ClassInheritanceMultiMap<Entity> slice : entitieSlices) {
if (slice == null) {
continue;
}
for (Entity ent : slice) {
EntityTrackerEntry entry =
entries != null ? entries.lookup(ent.getEntityId()) : null;
if (entry == null) {
continue;
}
entities.add(entry);
SPacketDestroyEntities packet = new SPacketDestroyEntities(ent.getEntityId());
for (EntityPlayerMP player : players) {
player.connection.sendPacket(packet);
}
}
}
// Send chunks
SPacketChunkData packet = new SPacketChunkData(nmsChunk, 65535);
for (EntityPlayerMP player : players) {
player.connection.sendPacket(packet);
}
// send ents
for (EntityTrackerEntry entry : entities) {
try {
TaskManager.IMP.taskLater(new Runnable() {
@Override public void run() {
for (EntityPlayerMP player : players) {
if (entry.isVisibleTo(player)) {
entry.removeFromTrackedPlayers(player);
if (entry.getTrackedEntity() != player) {
entry.updatePlayerEntity(player);
}
}
}
}
}, 2);
} catch (Throwable e) {
e.printStackTrace();
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
@Override public void fixChunkLighting(int x, int z) {
Chunk nmsChunk = getChunk(getSpongeWorld(), x, z);
nmsChunk.generateSkylightMap();
}
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)) && isSolid(getId(sections, x, y, z + 1))
&& isSolid(getId(sections, x, y, z - 1));
}
public boolean isSolid(int i) {
return i != 0 && Block.getBlockById(i)
.isOpaqueCube(Block.getBlockById(i).getDefaultState());
}
public int getId(char[][] 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];
char[] section = sections[i];
if (section == null) {
return 0;
}
int j = MainUtil.CACHE_I[y][x][z];
int combined = section[j];
return combined >> 4;
}
public boolean fixLighting(CharLocalChunk_Sponge bc, Chunk nmsChunk) {
try {
if (!nmsChunk.isLoaded()) {
return false;
}
ExtendedBlockStorage[] sections = nmsChunk.getBlockStorageArray();
nmsChunk.generateSkylightMap();
net.minecraft.world.World nmsWorld = nmsChunk.getWorld();
int X = bc.getX() << 4;
int Z = bc.getZ() << 4;
BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(0, 0, 0);
for (int j = 0; j < sections.length; j++) {
ExtendedBlockStorage section = sections[j];
if (section == null) {
continue;
}
if ((bc.getCount(j) == 0) || ((bc.getCount(j) >= 4096) && (bc.getAir(j) == 0))
|| bc.getAir(j) == 4096) {
continue;
}
char[] array = bc.getIdArray(j);
if (array != null) {
int l = PseudoRandom.random.random(2);
for (int k = 0; k < array.length; k++) {
int i = array[k];
if (i < 16) {
continue;
}
short id = (short) (i >> 4);
switch (id) { // Lighting
default:
if ((k & 1) == l) {
l = 1 - l;
continue;
}
case 10:
case 11:
case 39:
case 40:
case 50:
case 51:
case 62:
case 74:
case 76:
case 89:
case 122:
case 124:
case 130:
case 138:
case 169:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
if (isSurrounded(bc.blocks, x, y, z)) {
continue;
}
pos.setPos(X + x, y, Z + z);
nmsWorld.checkLight(pos);
}
}
}
}
return true;
} catch (Throwable e) {
e.printStackTrace();
}
return false;
}
@Override public final void regenChunk(int x, int z) {
World worldObj = getSpongeWorld();
throw new UnsupportedOperationException("NOT SUPPORTED");
}
@Override public final void setComponents(LocalChunk<char[]> lc) {
setBlocks(lc);
setBiomes(lc);
}
public Chunk getChunk(World world, int x, int z) {
net.minecraft.world.chunk.Chunk chunk =
((net.minecraft.world.World) world).getChunkProvider().provideChunk(x, z);
if (chunk != null && !chunk.isLoaded()) {
chunk.onLoad();
}
return chunk;
}
public void setBlocks(LocalChunk<char[]> lc) {
World worldObj = getSpongeWorld();
net.minecraft.world.World nmsWorld = ((net.minecraft.world.World) worldObj);
org.spongepowered.api.world.Chunk spongeChunk =
(org.spongepowered.api.world.Chunk) getChunk(worldObj, lc.getX(), lc.getZ());
Chunk nmsChunk = (Chunk) spongeChunk;
char[][] ids = ((CharLocalChunk) lc).blocks;
for (int layer = 0; layer < 16; layer++) {
char[] array = ids[layer];
if (array == null) {
continue;
}
ExtendedBlockStorage[] sections = nmsChunk.getBlockStorageArray();
ExtendedBlockStorage section = sections[layer];
if (section == null) {
section = sections[layer] =
new ExtendedBlockStorage(layer << 4, nmsWorld.provider.hasSkyLight());
}
short[] cacheX = MainUtil.x_loc[0];
short[] cacheY = MainUtil.y_loc[0];
short[] cacheZ = MainUtil.z_loc[0];
for (int j = 0; j < array.length; j++) {
int combinedId = array[j];
switch (combinedId) {
case 0:
continue;
case 1:
int x = cacheX[j];
int y = cacheY[j];
int z = cacheZ[j];
section.set(x, y, z, Blocks.AIR.getDefaultState());
continue;
default:
int id = combinedId >> 4;
Block block = Block.getBlockById(id);
int data = combinedId & 0xf;
IBlockState ibd;
if (data != 0) {
ibd = block.getStateFromMeta(data);
} else {
ibd = block.getDefaultState();
}
x = cacheX[j];
y = cacheY[j];
z = cacheZ[j];
section.set(x, y, z, ibd);
continue;
}
}
}
refreshChunk(nmsChunk.x, nmsChunk.z);
}
public void setBiomes(LocalChunk<char[]> lc) {
if (lc.biomes != null) {
World worldObj = getSpongeWorld();
int bx = lc.getX() << 4;
int bz = lc.getX() << 4;
String last = null;
BiomeType 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 = SpongeUtil.getBiome(biomeStr.toUpperCase());
}
worldObj.setBiome(bx, 0, bz, biome);
}
}
}
}
}
}
public class CharLocalChunk_Sponge extends CharLocalChunk {
public short[] count;
public short[] air;
public short[] relight;
public CharLocalChunk_Sponge(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;
}
}
}

View file

@ -1,91 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.uuid;
import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler;
import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import com.google.common.base.Charsets;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.profile.GameProfile;
import java.util.Collection;
import java.util.UUID;
public class SpongeLowerOfflineUUIDWrapper extends UUIDWrapper {
public SpongeLowerOfflineUUIDWrapper() {
// Anything?
}
@Override public UUID getUUID(PlotPlayer player) {
return getUUID(player.getName());
}
@Override public UUID getUUID(OfflinePlotPlayer player) {
return getUUID(player.getName());
}
@Override public OfflinePlotPlayer getOfflinePlayer(UUID uuid) {
String name = UUIDHandler.getName(uuid);
if (name == null) {
try {
GameProfile profile = SpongeMain.THIS.getResolver().get(uuid).get();
if (profile != null) {
name = profile.getName().orElse(null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (name == null) {
for (GameProfile profile : SpongeMain.THIS.getResolver().getCache().getProfiles()) {
String tmp = profile.getName().orElse(null);
if (tmp != null) {
if (getUUID(name).equals(uuid)) {
name = tmp;
break;
}
}
}
}
String username = name;
return new OfflinePlotPlayer() {
@Override public boolean isOnline() {
return UUIDHandler.getPlayer(uuid) != null;
}
@Override public UUID getUUID() {
return uuid;
}
@Override public String getName() {
return username;
}
@Override public long getLastPlayed() {
// TODO FIXME
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
};
}
public Player[] getOnlinePlayers() {
Collection<Player> onlinePlayers = SpongeMain.THIS.getServer().getOnlinePlayers();
return onlinePlayers.toArray(new Player[onlinePlayers.size()]);
}
@Override public UUID getUUID(String name) {
return UUID
.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override public OfflinePlotPlayer[] getOfflinePlayers() {
// TODO FIXME
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public OfflinePlotPlayer getOfflinePlayer(String name) {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
}

View file

@ -1,67 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.uuid;
import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper;
import com.github.intellectualsites.plotsquared.sponge.object.SpongeOfflinePlayer;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.service.user.UserStorageService;
import org.spongepowered.api.util.Identifiable;
import java.util.Optional;
import java.util.UUID;
public class SpongeOnlineUUIDWrapper extends UUIDWrapper {
private UserStorageService userStorageService;
public SpongeOnlineUUIDWrapper() {
Optional<UserStorageService> userStorage =
Sponge.getServiceManager().provide(UserStorageService.class);
userStorage.ifPresent(userStorageService -> this.userStorageService = userStorageService);
}
@Override public UUID getUUID(PlotPlayer player) {
return ((SpongePlayer) player).player.getUniqueId();
}
@Override public UUID getUUID(OfflinePlotPlayer player) {
return player.getUUID();
}
@Override public UUID getUUID(String name) {
Optional<Player> player = Sponge.getServer().getPlayer(name);
if (player.isPresent()) {
return player.get().getUniqueId();
}
Optional<User> user = userStorageService.get(name);
return user.map(Identifiable::getUniqueId).orElse(null);
}
@Override public OfflinePlotPlayer getOfflinePlayer(UUID uuid) {
Optional<Player> player = Sponge.getServer().getPlayer(uuid);
if (player.isPresent()) {
return new SpongeOfflinePlayer(player.get());
}
Optional<User> user = userStorageService.get(uuid);
return user.map(SpongeOfflinePlayer::new).orElse(null);
}
@Override public OfflinePlotPlayer[] getOfflinePlayers() {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public OfflinePlotPlayer getOfflinePlayer(String name) {
Optional<Player> player = Sponge.getServer().getPlayer(name);
if (player.isPresent()) {
return new SpongeOfflinePlayer(player.get());
}
Optional<User> user = userStorageService.get(name);
return user.map(SpongeOfflinePlayer::new).orElse(null);
}
}

View file

@ -1,46 +0,0 @@
package com.github.intellectualsites.plotsquared.sponge.uuid;
import com.github.intellectualsites.plotsquared.plot.object.RunnableVal;
import com.github.intellectualsites.plotsquared.plot.object.StringWrapper;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.util.UUIDHandlerImplementation;
import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import org.spongepowered.api.profile.GameProfile;
import java.util.UUID;
public class SpongeUUIDHandler extends UUIDHandlerImplementation {
public SpongeUUIDHandler(UUIDWrapper wrapper) {
super(wrapper);
}
@Override public boolean startCaching(Runnable whenDone) {
if (!super.startCaching(whenDone)) {
return false;
}
return cache(whenDone);
}
public boolean cache(Runnable whenDone) {
for (GameProfile profile : SpongeMain.THIS.getServer().getGameProfileManager().getCache()
.getProfiles()) {
String name = profile.getName().orElse(null);
if (name != null) {
add(new StringWrapper(name), profile.getUniqueId());
}
}
return true;
}
@Override public void fetchUUID(String name, RunnableVal<UUID> ifFetch) {
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
ifFetch.value = SpongeUUIDHandler.this.uuidWrapper.getUUID(name);
TaskManager.runTask(ifFetch);
}
});
}
}