Merge remote-tracking branch 'origin/master' into update-paintball

Conflicts:
	Plugins/Nautilus.Game.Arcade/src/nautilus/game/arcade/game/games/wither/WitherGame.java
This commit is contained in:
Mysticate 2015-12-06 12:00:06 -05:00
commit 88dcdaa445
695 changed files with 48111 additions and 6356 deletions

1
.gitignore vendored
View File

@ -51,3 +51,4 @@ zSotanna2
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/segments.gen
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/segments_1
/.recommenders/index/http___download_eclipse_org_recommenders_models_mars_/write.lock
/Pocket

BIN
Art/MS SMoke.psd Normal file

Binary file not shown.

View File

@ -0,0 +1,47 @@
From c6e51ae8ffc31d0fc059d33ca159df31c2b7a83e Mon Sep 17 00:00:00 2001
From: libraryaddict <libraryaddict115@yahoo.co.nz>
Date: Sun, 22 Nov 2015 14:37:11 +1300
Subject: [PATCH] EntityDismountEvent
diff --git a/src/main/java/org/spigotmc/event/entity/EntityDismountEvent.java b/src/main/java/org/spigotmc/event/entity/EntityDismountEvent.java
index 24d4942..02943d6 100644
--- a/src/main/java/org/spigotmc/event/entity/EntityDismountEvent.java
+++ b/src/main/java/org/spigotmc/event/entity/EntityDismountEvent.java
@@ -2,13 +2,14 @@ package org.spigotmc.event.entity;
import org.bukkit.entity.Entity;
import org.bukkit.event.HandlerList;
+import org.bukkit.event.Cancellable;
import org.bukkit.event.entity.EntityEvent;
/**
* Called when an entity stops riding another entity.
*
*/
-public class EntityDismountEvent extends EntityEvent
+public class EntityDismountEvent extends EntityEvent implements Cancellable
{
private static final HandlerList handlers = new HandlerList();
@@ -36,4 +37,17 @@ public class EntityDismountEvent extends EntityEvent
{
return handlers;
}
+
+ @Override
+ public boolean isCancelled()
+ {
+ return cancelled;
+ }
+
+ @Override
+ public void setCancelled(boolean cancel)
+ {
+ this.cancelled = cancel;
+ }
+
}
--
1.9.5.msysgit.0

View File

@ -0,0 +1,159 @@
From bc86c3b02f2efa4c1194fc908e8d1ee8723f62c5 Mon Sep 17 00:00:00 2001
From: libraryaddict <libraryaddict115@yahoo.co.nz>
Date: Sun, 22 Nov 2015 14:41:11 +1300
Subject: [PATCH] EntityDismountEvent & teleport crash fix
diff --git a/src/main/java/net/minecraft/server/Entity.java b/src/main/java/net/minecraft/server/Entity.java
index 81ca499..7165579 100644
--- a/src/main/java/net/minecraft/server/Entity.java
+++ b/src/main/java/net/minecraft/server/Entity.java
@@ -23,6 +23,8 @@ import org.bukkit.event.painting.PaintingBreakByEntityEvent;
import org.bukkit.event.vehicle.VehicleBlockCollisionEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
+import org.spigotmc.event.entity.EntityDismountEvent;
+import org.spigotmc.event.entity.EntityMountEvent;
import org.bukkit.craftbukkit.CraftWorld;
import org.bukkit.craftbukkit.entity.CraftEntity;
import org.bukkit.craftbukkit.entity.CraftPlayer;
@@ -1591,7 +1593,12 @@ public abstract class Entity implements ICommandListener {
}
}
// CraftBukkit end
- pluginManager.callEvent( new org.spigotmc.event.entity.EntityDismountEvent( this.getBukkitEntity(), this.vehicle.getBukkitEntity() ) ); // Spigot
+ EntityDismountEvent event = new org.spigotmc.event.entity.EntityDismountEvent(this.getBukkitEntity(), this.vehicle.getBukkitEntity());
+ pluginManager.callEvent(event); // Spigot
+
+ if (event.isCancelled() || vehicle != originalVehicle) {
+ return;
+ } // Spigot
this.setPositionRotation(this.vehicle.locX, this.vehicle.getBoundingBox().b + (double) this.vehicle.length, this.vehicle.locZ, this.yaw, this.pitch);
this.vehicle.passenger = null;
}
@@ -1599,44 +1606,45 @@ public abstract class Entity implements ICommandListener {
this.vehicle = null;
} else {
// CraftBukkit start
- if ((this.bukkitEntity instanceof LivingEntity) && (entity.getBukkitEntity() instanceof Vehicle) && entity.world.isChunkLoaded((int) entity.locX >> 4, (int) entity.locZ >> 4, true)) {
+ if (entity.world.isChunkLoaded((int) entity.locX >> 4, (int) entity.locZ >> 4, true)) {
// It's possible to move from one vehicle to another. We need to check if they're already in a vehicle, and fire an exit event if they are.
VehicleExitEvent exitEvent = null;
+ EntityDismountEvent exitEvent1 = null;
if (this.vehicle != null) {
- exitEvent = new VehicleExitEvent((Vehicle) this.vehicle.getBukkitEntity(), (LivingEntity) this.bukkitEntity);
+ if ((this.bukkitEntity instanceof LivingEntity) && (entity.getBukkitEntity() instanceof Vehicle))
+ exitEvent = new VehicleExitEvent((Vehicle) this.vehicle.getBukkitEntity(), (LivingEntity) this.bukkitEntity);
pluginManager.callEvent(exitEvent);
if (exitEvent.isCancelled() || this.vehicle != originalVehicle || (this.vehicle != null && this.vehicle.passenger != originalPassenger)) {
return;
}
+
+ exitEvent1 = new EntityDismountEvent(this.vehicle.getBukkitEntity(), this.bukkitEntity);
+
+ pluginManager.callEvent(exitEvent1);
+
+ if (exitEvent1.isCancelled() || this.vehicle != originalVehicle || (this.vehicle != null && this.vehicle.passenger != originalPassenger)) {
+ return;
+ }
}
- VehicleEnterEvent event = new VehicleEnterEvent((Vehicle) entity.getBukkitEntity(), this.bukkitEntity);
- pluginManager.callEvent(event);
+ if ((this.bukkitEntity instanceof LivingEntity) && (entity.getBukkitEntity() instanceof Vehicle)) {
+ VehicleEnterEvent event = new VehicleEnterEvent((Vehicle) entity.getBukkitEntity(), this.bukkitEntity);
+ pluginManager.callEvent(event);
- // If a plugin messes with the vehicle or the vehicle's passenger
- if (event.isCancelled() || this.vehicle != originalVehicle || (this.vehicle != null && this.vehicle.passenger != originalPassenger)) {
- // If we only cancelled the enterevent then we need to put the player in a decent position.
- if (exitEvent != null && this.vehicle == originalVehicle && this.vehicle != null && this.vehicle.passenger == originalPassenger) {
- this.setPositionRotation(this.vehicle.locX, this.vehicle.getBoundingBox().b + (double) this.vehicle.length, this.vehicle.locZ, this.yaw, this.pitch);
- this.vehicle.passenger = null;
- this.vehicle = null;
+ // If a plugin messes with the vehicle or the vehicle's passenger
+ if (event.isCancelled() || this.vehicle != originalVehicle || (this.vehicle != null && this.vehicle.passenger != originalPassenger)) {
+ // If we only cancelled the enterevent then we need to put the player in a decent position.
+ if (exitEvent != null && this.vehicle == originalVehicle && this.vehicle != null && this.vehicle.passenger == originalPassenger) {
+ this.setPositionRotation(this.vehicle.locX, this.vehicle.getBoundingBox().b + (double) this.vehicle.length, this.vehicle.locZ, this.yaw, this.pitch);
+ this.vehicle.passenger = null;
+ this.vehicle = null;
+ }
+ return;
}
- return;
}
}
// CraftBukkit end
- // Spigot Start
- if ( entity.world.isChunkLoaded( (int) entity.locX >> 4, (int) entity.locZ >> 4, true ) )
- {
- org.spigotmc.event.entity.EntityMountEvent event = new org.spigotmc.event.entity.EntityMountEvent( this.getBukkitEntity(), entity.getBukkitEntity() );
- pluginManager.callEvent( event );
- if ( event.isCancelled() )
- {
- return;
- }
- }
- // Spigot End
if (this.vehicle != null) {
this.vehicle.passenger = null;
diff --git a/src/main/java/net/minecraft/server/EntityLiving.java b/src/main/java/net/minecraft/server/EntityLiving.java
index b861dbe..96b3905 100644
--- a/src/main/java/net/minecraft/server/EntityLiving.java
+++ b/src/main/java/net/minecraft/server/EntityLiving.java
@@ -21,6 +21,7 @@ import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageModifier;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
+import org.spigotmc.event.entity.EntityDismountEvent;
// CraftBukkit end
import org.bukkit.craftbukkit.SpigotTimings; // Spigot
@@ -1725,8 +1726,15 @@ public abstract class EntityLiving extends Entity {
return;
}
}
+
+ EntityDismountEvent event = new EntityDismountEvent(this.vehicle.getBukkitEntity(), (LivingEntity) this.bukkitEntity);
+ getBukkitEntity().getServer().getPluginManager().callEvent(event);
+
+ if (event.isCancelled() || vehicle != originalVehicle) {
+ return;
+ }
// CraftBukkit end
-
+
if (!this.world.isClientSide) {
this.q(this.vehicle);
}
diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java
index efbf1a8..dbc7b54 100644
--- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java
+++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java
@@ -1,6 +1,7 @@
package org.bukkit.craftbukkit.entity;
import com.google.common.base.Preconditions;
+import com.google.common.primitives.Doubles;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -234,6 +235,12 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity {
// If this entity is riding another entity, we must dismount before teleporting.
entity.mount(null);
+ if (!Doubles.isFinite(location.getX()) || !Doubles.isFinite(location.getY()) || !Doubles.isFinite(location.getZ()))
+ {
+ Thread.dumpStack();
+ return false;
+ }
+
// Spigot start
if (!location.getWorld().equals(getWorld())) {
entity.teleportTo(location, cause.equals(TeleportCause.NETHER_PORTAL));
--
1.9.5.msysgit.0

View File

@ -18,6 +18,9 @@
<element id="file-copy" path="$PROJECT_DIR$/Mineplex.Game.Clans/plugin.yml" />
<element id="module-output" name="Mineplex.ServerData" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/jooq-3.5.2.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/commons-dbcp2-2.0.1.jar" path-in-jar="/" />
<element id="module-output" name="Mineplex.Game.Clans.Core" />
<element id="module-output" name="Mineplex.PlayerCache" />
</root>
</artifact>
</component>

View File

@ -21,6 +21,7 @@
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/jooq-3.5.2.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/Libraries/commons-dbcp2-2.0.1.jar" path-in-jar="/" />
<element id="module-output" name="Mineplex.PlayerCache" />
<element id="module-output" name="Mineplex.Game.Clans.Core" />
</root>
</artifact>
</component>

View File

@ -7,6 +7,14 @@
<option name="STATIC_FIELD_NAME_PREFIX" value="_" />
<option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="20" />
<option name="NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND" value="10" />
<option name="PACKAGES_TO_USE_IMPORT_ON_DEMAND">
<value>
<package name="java.awt" withSubpackages="false" static="false" />
<package name="org.jooq.impl.DSL" withSubpackages="false" static="true" />
<package name="mineplex.database.Tables" withSubpackages="false" static="true" />
<package name="javax.swing" withSubpackages="false" static="false" />
</value>
</option>
<option name="IMPORT_LAYOUT_TABLE">
<value>
<package name="javax" withSubpackages="true" static="false" />

View File

@ -5,9 +5,6 @@
<excludeFromCompile>
<directory url="file://$PROJECT_DIR$/Nautilus.Game.PvP" includeSubdirectories="true" />
<directory url="file://$PROJECT_DIR$/Mineplex.ServerMonitor" includeSubdirectories="true" />
<directory url="file://$PROJECT_DIR$/Mineplex.Game.Clans" includeSubdirectories="true" />
<directory url="file://$PROJECT_DIR$/Nautilus.Game.Arcade" includeSubdirectories="true" />
<directory url="file://$PROJECT_DIR$/Mineplex.Hub" includeSubdirectories="true" />
</excludeFromCompile>
<resourceExtensions />
<wildcardResourcePatterns>
@ -31,9 +28,7 @@
<processorPath useClasspath="true" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel target="1.7">
<module name="bungee" target="1.7" />
</bytecodeTargetLevel>
<bytecodeTargetLevel target="1.7" />
</component>
<component name="JavacSettings">
<option name="GENERATE_NO_WARNINGS" value="true" />

View File

@ -1,11 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" hash="4268976312">
<component name="DataSourceManagerImpl" format="xml" hash="2876127046">
<data-source source="LOCAL" name="Mineplex" uuid="14dfc55d-5343-47c4-ab24-76a055b8059e">
<driver-ref>mysql</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>com.mysql.jdbc.Driver</jdbc-driver>
<jdbc-url>jdbc:mysql://db.mineplex.com:3306</jdbc-url>
<jdbc-url>jdbc:mysql://db.mineplex.com:3306/Account</jdbc-url>
<driver-properties>
<property name="zeroDateTimeBehavior" value="convertToNull" />
<property name="tinyInt1isBit" value="false" />

View File

@ -4,7 +4,7 @@
<root url="jar://$PROJECT_DIR$/Libraries/craftbukkit.jar!/" />
</CLASSES>
<JAVADOC>
<root url="http://jd.bukkit.org/dev/apidocs/" />
<root url="https://hub.spigotmc.org/javadocs/spigot/" />
</JAVADOC>
<SOURCES>
<root url="jar://$PROJECT_DIR$/Libraries/craftbukkit.jar!/" />

View File

@ -16,7 +16,7 @@
</set>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" assert-keyword="true" jdk-15="true" project-jdk-name="1.7" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="false" assert-keyword="true" jdk-15="true" project-jdk-name="1.7" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View File

@ -3,21 +3,23 @@
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Classpath.Dummy/Classpath.Dummy.iml" filepath="$PROJECT_DIR$/Classpath.Dummy/Classpath.Dummy.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/JedisTest/JedisTest.iml" filepath="$PROJECT_DIR$/JedisTest/JedisTest.iml" />
<module fileurl="file://$PROJECT_DIR$/JedisTest/JedisTest.iml" filepath="$PROJECT_DIR$/JedisTest/JedisTest.iml" group="Legacy" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Bungee.Mineplexer/Mineplex.Bungee.Mineplexer.iml" filepath="$PROJECT_DIR$/Mineplex.Bungee.Mineplexer/Mineplex.Bungee.Mineplexer.iml" group="Bungee" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Core/Mineplex.Core.iml" filepath="$PROJECT_DIR$/Mineplex.Core/Mineplex.Core.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Core.Common/Mineplex.Core.Common.iml" filepath="$PROJECT_DIR$/Mineplex.Core.Common/Mineplex.Core.Common.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Database/Mineplex.Database.iml" filepath="$PROJECT_DIR$/Mineplex.Database/Mineplex.Database.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Game.Clans/Mineplex.Game.Clans.iml" filepath="$PROJECT_DIR$/Mineplex.Game.Clans/Mineplex.Game.Clans.iml" group="Game" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Game.Clans.Core/Mineplex.Game.Clans.Core.iml" filepath="$PROJECT_DIR$/Mineplex.Game.Clans.Core/Mineplex.Game.Clans.Core.iml" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Hub/Mineplex.Hub.iml" filepath="$PROJECT_DIR$/Mineplex.Hub/Mineplex.Hub.iml" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.MapParser/Mineplex.MapParser.iml" filepath="$PROJECT_DIR$/Mineplex.MapParser/Mineplex.MapParser.iml" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Minecraft.Game.ClassCombat/Mineplex.Minecraft.Game.ClassCombat.iml" filepath="$PROJECT_DIR$/Mineplex.Minecraft.Game.ClassCombat/Mineplex.Minecraft.Game.ClassCombat.iml" group="Game" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Minecraft.Game.Core/Mineplex.Minecraft.Game.Core.iml" filepath="$PROJECT_DIR$/Mineplex.Minecraft.Game.Core/Mineplex.Minecraft.Game.Core.iml" group="Game" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.PlayerCache/Mineplex.PlayerCache.iml" filepath="$PROJECT_DIR$/Mineplex.PlayerCache/Mineplex.PlayerCache.iml" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.PlayerCache/Mineplex.PlayerCache.iml" filepath="$PROJECT_DIR$/Mineplex.PlayerCache/Mineplex.PlayerCache.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.ServerData/Mineplex.ServerData.iml" filepath="$PROJECT_DIR$/Mineplex.ServerData/Mineplex.ServerData.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.ServerMonitor/Mineplex.ServerMonitor.iml" filepath="$PROJECT_DIR$/Mineplex.ServerMonitor/Mineplex.ServerMonitor.iml" group="Core" />
<module fileurl="file://$PROJECT_DIR$/Mineplex.Votifier/Mineplex.Votifier.iml" filepath="$PROJECT_DIR$/Mineplex.Votifier/Mineplex.Votifier.iml" />
<module fileurl="file://$PROJECT_DIR$/Nautilus.Game.Arcade/Nautilus.Game.Arcade.iml" filepath="$PROJECT_DIR$/Nautilus.Game.Arcade/Nautilus.Game.Arcade.iml" group="Game" />
<module fileurl="file://$PROJECT_DIR$/Nautilus.Game.PvP/Nautilus.Game.PvP.iml" filepath="$PROJECT_DIR$/Nautilus.Game.PvP/Nautilus.Game.PvP.iml" group="Legacy" />
</modules>
</component>
</project>

View File

@ -149,6 +149,9 @@
<fileset dir="../Mineplex.Minecraft.Game.Core/bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="../Mineplex.Game.Clans.Core/bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="../Mineplex.Hub">
<include name="*.yml"/>
</fileset>
@ -189,6 +192,9 @@
<fileset dir="../Mineplex.Core.Common/bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="../Mineplex.Game.Clans.Core/bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="../Mineplex.Minecraft.Game.ClassCombat/bin">
<include name="**/*.class"/>
</fileset>

View File

@ -13,4 +13,3 @@
<orderEntry type="library" name="commons-logging" level="project" />
</component>
</module>

View File

@ -1,328 +0,0 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.bukkit.command;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import org.apache.commons.lang.Validate;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandException;
import org.bukkit.command.CommandMap;
import org.bukkit.command.CommandSender;
import org.bukkit.command.FormattedCommandAlias;
import org.bukkit.command.defaults.AchievementCommand;
import org.bukkit.command.defaults.BanCommand;
import org.bukkit.command.defaults.BanIpCommand;
import org.bukkit.command.defaults.BanListCommand;
import org.bukkit.command.defaults.ClearCommand;
import org.bukkit.command.defaults.DefaultGameModeCommand;
import org.bukkit.command.defaults.DeopCommand;
import org.bukkit.command.defaults.DifficultyCommand;
import org.bukkit.command.defaults.EffectCommand;
import org.bukkit.command.defaults.EnchantCommand;
import org.bukkit.command.defaults.ExpCommand;
import org.bukkit.command.defaults.GameModeCommand;
import org.bukkit.command.defaults.GameRuleCommand;
import org.bukkit.command.defaults.GiveCommand;
import org.bukkit.command.defaults.HelpCommand;
import org.bukkit.command.defaults.KickCommand;
import org.bukkit.command.defaults.KillCommand;
import org.bukkit.command.defaults.ListCommand;
import org.bukkit.command.defaults.MeCommand;
import org.bukkit.command.defaults.OpCommand;
import org.bukkit.command.defaults.PardonCommand;
import org.bukkit.command.defaults.PardonIpCommand;
import org.bukkit.command.defaults.PlaySoundCommand;
import org.bukkit.command.defaults.PluginsCommand;
import org.bukkit.command.defaults.ReloadCommand;
import org.bukkit.command.defaults.SaveCommand;
import org.bukkit.command.defaults.SaveOffCommand;
import org.bukkit.command.defaults.SaveOnCommand;
import org.bukkit.command.defaults.SayCommand;
import org.bukkit.command.defaults.ScoreboardCommand;
import org.bukkit.command.defaults.SeedCommand;
import org.bukkit.command.defaults.SetIdleTimeoutCommand;
import org.bukkit.command.defaults.SetWorldSpawnCommand;
import org.bukkit.command.defaults.SpawnpointCommand;
import org.bukkit.command.defaults.SpreadPlayersCommand;
import org.bukkit.command.defaults.StopCommand;
import org.bukkit.command.defaults.TeleportCommand;
import org.bukkit.command.defaults.TellCommand;
import org.bukkit.command.defaults.TestForCommand;
import org.bukkit.command.defaults.TimeCommand;
import org.bukkit.command.defaults.TimingsCommand;
import org.bukkit.command.defaults.ToggleDownfallCommand;
import org.bukkit.command.defaults.VanillaCommand;
import org.bukkit.command.defaults.VersionCommand;
import org.bukkit.command.defaults.WeatherCommand;
import org.bukkit.command.defaults.WhitelistCommand;
import org.bukkit.entity.Player;
import org.bukkit.event.TabCompleteEvent;
import org.bukkit.util.Java15Compat;
import org.bukkit.util.StringUtil;
public class SimpleCommandMap implements CommandMap {
private static final Pattern PATTERN_ON_SPACE = Pattern.compile(" ", 16);
protected final Map<String, Command> knownCommands = new HashMap<String, Command>();
private final Server server;
public SimpleCommandMap(Server server) {
this.server = server;
this.setDefaultCommands();
}
private void setDefaultCommands() {
this.register("bukkit", new SaveCommand());
this.register("bukkit", new SaveOnCommand());
this.register("bukkit", new SaveOffCommand());
this.register("bukkit", new StopCommand());
this.register("bukkit", new VersionCommand("version"));
this.register("bukkit", new ReloadCommand("reload"));
this.register("bukkit", new PluginsCommand("plugins"));
this.register("bukkit", new TimingsCommand("timings"));
}
public void setFallbackCommands() {
this.register("bukkit", new ListCommand());
this.register("bukkit", new OpCommand());
this.register("bukkit", new DeopCommand());
this.register("bukkit", new BanIpCommand());
this.register("bukkit", new PardonIpCommand());
this.register("bukkit", new BanCommand());
this.register("bukkit", new PardonCommand());
this.register("bukkit", new KickCommand());
this.register("bukkit", new TeleportCommand());
this.register("bukkit", new GiveCommand());
this.register("bukkit", new TimeCommand());
this.register("bukkit", new SayCommand());
this.register("bukkit", new WhitelistCommand());
this.register("bukkit", new TellCommand());
this.register("bukkit", new MeCommand());
this.register("bukkit", new KillCommand());
this.register("bukkit", new GameModeCommand());
this.register("bukkit", new HelpCommand());
this.register("bukkit", new ExpCommand());
this.register("bukkit", new ToggleDownfallCommand());
this.register("bukkit", new BanListCommand());
this.register("bukkit", new DefaultGameModeCommand());
this.register("bukkit", new SeedCommand());
this.register("bukkit", new DifficultyCommand());
this.register("bukkit", new WeatherCommand());
this.register("bukkit", new SpawnpointCommand());
this.register("bukkit", new ClearCommand());
this.register("bukkit", new GameRuleCommand());
this.register("bukkit", new EnchantCommand());
this.register("bukkit", new TestForCommand());
this.register("bukkit", new EffectCommand());
this.register("bukkit", new ScoreboardCommand());
this.register("bukkit", new PlaySoundCommand());
this.register("bukkit", new SpreadPlayersCommand());
this.register("bukkit", new SetWorldSpawnCommand());
this.register("bukkit", new SetIdleTimeoutCommand());
this.register("bukkit", new AchievementCommand());
}
public void registerAll(String fallbackPrefix, List<Command> commands) {
if(commands != null) {
Iterator var3 = commands.iterator();
while(var3.hasNext()) {
Command c = (Command)var3.next();
this.register(fallbackPrefix, c);
}
}
}
public boolean register(String fallbackPrefix, Command command) {
return this.register(command.getName(), fallbackPrefix, command);
}
public boolean register(String label, String fallbackPrefix, Command command) {
label = label.toLowerCase().trim();
fallbackPrefix = fallbackPrefix.toLowerCase().trim();
boolean registered = this.register(label, command, false, fallbackPrefix);
Iterator iterator = command.getAliases().iterator();
while(iterator.hasNext()) {
if(!this.register((String)iterator.next(), command, true, fallbackPrefix)) {
iterator.remove();
}
}
if(!registered) {
command.setLabel(fallbackPrefix + ":" + label);
}
command.register(this);
return registered;
}
private synchronized boolean register(String label, Command command, boolean isAlias, String fallbackPrefix) {
this.knownCommands.put(fallbackPrefix + ":" + label, command);
if((command instanceof VanillaCommand || isAlias) && this.knownCommands.containsKey(label)) {
return false;
} else {
boolean registered = true;
Command conflict = (Command)this.knownCommands.get(label);
if(conflict != null && conflict.getLabel().equals(label)) {
return false;
} else {
if(!isAlias) {
command.setLabel(label);
}
this.knownCommands.put(label, command);
return registered;
}
}
}
public boolean dispatch(CommandSender sender, String commandLine) throws CommandException {
String[] args = PATTERN_ON_SPACE.split(commandLine);
if(args.length == 0) {
return false;
} else {
String sentCommandLabel = args[0].toLowerCase();
Command target = this.getCommand(sentCommandLabel);
if(target == null) {
return false;
} else {
try {
target.timings.startTiming();
target.execute(sender, sentCommandLabel, (String[])Java15Compat.Arrays_copyOfRange(args, 1, args.length));
target.timings.stopTiming();
return true;
} catch (CommandException var7) {
target.timings.stopTiming();
throw var7;
} catch (Throwable var8) {
target.timings.stopTiming();
throw new CommandException("Unhandled exception executing \'" + commandLine + "\' in " + target, var8);
}
}
}
}
public synchronized void clearCommands() {
Iterator var1 = this.knownCommands.entrySet().iterator();
while(var1.hasNext()) {
Entry entry = (Entry)var1.next();
((Command)entry.getValue()).unregister(this);
}
this.knownCommands.clear();
this.setDefaultCommands();
}
public Command getCommand(String name) {
Command target = (Command)this.knownCommands.get(name.toLowerCase());
return target;
}
public List<String> tabComplete(CommandSender sender, String cmdLine) {
Validate.notNull(sender, "Sender cannot be null");
Validate.notNull(cmdLine, "Command line cannot null");
int spaceIndex = cmdLine.indexOf(32);
String argLine;
if(spaceIndex == -1) {
ArrayList commandName1 = new ArrayList();
Map target1 = this.knownCommands;
argLine = sender instanceof Player?"/":"";
Iterator args1 = target1.entrySet().iterator();
while(args1.hasNext()) {
Entry ex = (Entry)args1.next();
Command command = (Command)ex.getValue();
if(command.testPermissionSilent(sender)) {
String name = (String)ex.getKey();
if(StringUtil.startsWithIgnoreCase(name, cmdLine)) {
commandName1.add(argLine + name);
}
}
}
Collections.sort(commandName1, String.CASE_INSENSITIVE_ORDER);
return commandName1;
} else {
String commandName = cmdLine.substring(0, spaceIndex);
Command target = this.getCommand(commandName);
argLine = cmdLine.substring(spaceIndex + 1, cmdLine.length());
String[] args = PATTERN_ON_SPACE.split(argLine, -1);
TabCompleteEvent event = new TabCompleteEvent(sender, commandName, args);
if (target != null) {
try {
event.getSuggestions().addAll(target.tabComplete(sender, commandName, args));
} catch (CommandException var11) {
throw var11;
} catch (Throwable var12) {
throw new CommandException("Unhandled exception executing tab-completer for \'" + cmdLine + "\' in " + target, var12);
}
}
server.getPluginManager().callEvent(event);
return event.getSuggestions();
}
}
public Collection<Command> getCommands() {
return Collections.unmodifiableCollection(this.knownCommands.values());
}
public void registerServerAliases() {
Map values = this.server.getCommandAliases();
Iterator var2 = values.keySet().iterator();
while(var2.hasNext()) {
String alias = (String)var2.next();
if(!alias.contains(":") && !alias.contains(" ")) {
String[] commandStrings = (String[])values.get(alias);
ArrayList targets = new ArrayList();
StringBuilder bad = new StringBuilder();
String[] var7 = commandStrings;
int var8 = commandStrings.length;
for(int var9 = 0; var9 < var8; ++var9) {
String commandString = var7[var9];
String[] commandArgs = commandString.split(" ");
Command command = this.getCommand(commandArgs[0]);
if(command == null) {
if(bad.length() > 0) {
bad.append(", ");
}
bad.append(commandString);
} else {
targets.add(commandString);
}
}
if(bad.length() > 0) {
this.server.getLogger().warning("Could not register alias " + alias + " because it contains commands that do not exist: " + bad);
} else if(targets.size() > 0) {
this.knownCommands.put(alias.toLowerCase(), new FormattedCommandAlias(alias.toLowerCase(), (String[])targets.toArray(new String[targets.size()])));
} else {
this.knownCommands.remove(alias.toLowerCase());
}
} else {
this.server.getLogger().warning("Could not register alias " + alias + " because it contains illegal characters");
}
}
}
}

View File

@ -1,61 +0,0 @@
package org.bukkit.event;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.CommandSender;
public class TabCompleteEvent extends Event
{
private static final HandlerList handlers = new HandlerList();
private CommandSender _sender;
private String _command;
private String[] _args;
private List<String> _suggestions;
public TabCompleteEvent(CommandSender sender, String command, String[] args)
{
_sender = sender;
_command = command;
_args = args;
_suggestions = new ArrayList<String>();
}
public CommandSender getSender()
{
return _sender;
}
public String getCommand()
{
return _command;
}
public String[] getArgs()
{
return _args;
}
public List<String> getSuggestions()
{
return _suggestions;
}
public void setSuggestions(List<String> suggestions)
{
_suggestions = suggestions;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
}

View File

@ -1,77 +0,0 @@
package org.bukkit.scoreboard;
import java.util.Set;
import org.bukkit.OfflinePlayer;
public abstract interface Team
{
public abstract String getName()
throws IllegalStateException;
public abstract String getDisplayName()
throws IllegalStateException;
public abstract void setDisplayName(String paramString)
throws IllegalStateException, IllegalArgumentException;
public abstract String getPrefix()
throws IllegalStateException;
public abstract void setPrefix(String paramString)
throws IllegalStateException, IllegalArgumentException;
public abstract String getSuffix()
throws IllegalStateException;
public abstract void setSuffix(String paramString)
throws IllegalStateException, IllegalArgumentException;
public abstract boolean allowFriendlyFire()
throws IllegalStateException;
// Mineplex
public abstract void setNameTagVisibility(TeamNameTagVisibility visibility)
throws IllegalStateException;
public abstract void setAllowFriendlyFire(boolean paramBoolean)
throws IllegalStateException;
public abstract boolean canSeeFriendlyInvisibles()
throws IllegalStateException;
public abstract void setCanSeeFriendlyInvisibles(boolean paramBoolean)
throws IllegalStateException;
public abstract Set<OfflinePlayer> getPlayers()
throws IllegalStateException;
public abstract Set<String> getEntries()
throws IllegalStateException;
public abstract int getSize()
throws IllegalStateException;
public abstract Scoreboard getScoreboard();
public abstract void addPlayer(OfflinePlayer paramOfflinePlayer)
throws IllegalStateException, IllegalArgumentException;
public abstract void addEntry(String paramString)
throws IllegalStateException, IllegalArgumentException;
public abstract boolean removePlayer(OfflinePlayer paramOfflinePlayer)
throws IllegalStateException, IllegalArgumentException;
public abstract boolean removeEntry(String paramString)
throws IllegalStateException, IllegalArgumentException;
public abstract void unregister()
throws IllegalStateException;
public abstract boolean hasPlayer(OfflinePlayer paramOfflinePlayer)
throws IllegalArgumentException, IllegalStateException;
public abstract boolean hasEntry(String paramString)
throws IllegalArgumentException, IllegalStateException;
}

View File

@ -1,22 +0,0 @@
package org.bukkit.scoreboard;
/**
* Created by shaun on 14-10-05.
*/
public enum TeamNameTagVisibility
{
NEVER("never"), HIDE_FOR_OTHER_TEAMS("hideForOtherTeams"), HIDE_FOR_OWN_TEAM("hideForOwnTeam"), ALWAYS("always");
private String _keyword;
TeamNameTagVisibility(String keyword)
{
_keyword = keyword;
}
@Override
public String toString()
{
return _keyword;
}
}

Binary file not shown.

View File

@ -55,12 +55,12 @@ public class MotdManager implements Listener, Runnable
//String motdLine = "§f§l◄ §c§lMaintenance§f§l ►";
//String motdLine = "§f§l◄ §a§lCarl the Creeper§f§l ►";
String motdLine = " §2§l§n M O N S T E R M A Z E B E T A §f";
//String motdLine = " §f§l◄ §a§lCarl the Creeper§f§l ▬ §c§l75% OFF SALE§f§l ►";
// String motdLine = " §2§l§n M O N S T E R M A Z E B E T A §f";
String motdLine = " §f§l◄ §b§lNew Game§f§l ▬ §3§lChampions CTF§f§l ►";
//String motdLine = " §d§lRank Sale §a§l40% Off");
//String motdLine = " §f§l◄§c§lMAINTENANCE§f§l►");
updateMainMotd(" §4§l§m §f§l§m §8§l§m[ §r §4§lMineplex§r §f§lGames§r §8§l§m ]§f§l§m §4§l§m §r", motdLine);
updateMainMotd(" §f§l§m §8§l§m[ §r §6§lMineplex§r §f§lGames§r §8§l§m ]§f§l§m §r", motdLine);
System.out.println("Updated Bungee MOTD");
}
}

View File

@ -38,9 +38,8 @@ public class PlayerTracker implements Listener, Runnable
_plugin.getProxy().getPluginManager().registerListener(_plugin, this);
_plugin.getProxy().getScheduler().schedule(_plugin, this, 1L, 1L, TimeUnit.MINUTES);
Region region = !new File("eu.dat").exists() ? Region.US : Region.EU;
_repository = new RedisDataRepository<PlayerStatus>(ServerManager.getMasterConnection(), ServerManager.getSlaveConnection(),
region, PlayerStatus.class, "playerStatus");
Region.currentRegion(), PlayerStatus.class, "playerStatus");
ServerCommandManager.getInstance().registerCommandType("PlayerJoinCommand", mineplex.serverdata.commands.PlayerJoinCommand.class, new PlayerJoinHandler(this));

View File

@ -0,0 +1,57 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_Byte_Array} tag.
*/
public final class ByteArrayTag extends Tag {
private final byte[] value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public ByteArrayTag(byte[] value) {
super();
this.value = value;
}
@Override
public byte[] getValue() {
return value;
}
@Override
public String toString() {
StringBuilder hex = new StringBuilder();
for (byte b : value) {
String hexDigits = Integer.toHexString(b).toUpperCase();
if (hexDigits.length() == 1) {
hex.append("0");
}
hex.append(hexDigits).append(" ");
}
return "TAG_Byte_Array(" + hex + ")";
}
}

View File

@ -0,0 +1,49 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_Byte} tag.
*/
public final class ByteTag extends Tag {
private final byte value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public ByteTag(byte value) {
super();
this.value = value;
}
@Override
public Byte getValue() {
return value;
}
@Override
public String toString() {
return "TAG_Byte(" + value + ")";
}
}

View File

@ -0,0 +1,420 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The {@code TAG_Compound} tag.
*/
public final class CompoundTag extends Tag {
private final Map<String, Tag> value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public CompoundTag(Map<String, Tag> value) {
super();
this.value = Collections.unmodifiableMap(value);
}
/**
* Returns whether this compound tag contains the given key.
*
* @param key the given key
* @return true if the tag contains the given key
*/
public boolean containsKey(String key) {
return value.containsKey(key);
}
@Override
public Map<String, Tag> getValue() {
return value;
}
/**
* Return a new compound tag with the given values.
*
* @param value the value
* @return the new compound tag
*/
public CompoundTag setValue(Map<String, Tag> value) {
return new CompoundTag(value);
}
/**
* Create a compound tag builder.
*
* @return the builder
*/
public CompoundTagBuilder createBuilder() {
return new CompoundTagBuilder(new HashMap<String, Tag>(value));
}
/**
* Get a byte array named with the given key.
*
* <p>If the key does not exist or its value is not a byte array tag,
* then an empty byte array will be returned.</p>
*
* @param key the key
* @return a byte array
*/
public byte[] getByteArray(String key) {
Tag tag = value.get(key);
if (tag instanceof ByteArrayTag) {
return ((ByteArrayTag) tag).getValue();
} else {
return new byte[0];
}
}
/**
* Get a byte named with the given key.
*
* <p>If the key does not exist or its value is not a byte tag,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return a byte
*/
public byte getByte(String key) {
Tag tag = value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else {
return (byte) 0;
}
}
/**
* Get a double named with the given key.
*
* <p>If the key does not exist or its value is not a double tag,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return a double
*/
public double getDouble(String key) {
Tag tag = value.get(key);
if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a double named with the given key, even if it's another
* type of number.
*
* <p>If the key does not exist or its value is not a number,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return a double
*/
public double asDouble(String key) {
Tag tag = value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
} else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue();
} else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a float named with the given key.
*
* <p>If the key does not exist or its value is not a float tag,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return a float
*/
public float getFloat(String key) {
Tag tag = value.get(key);
if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a {@code int[]} named with the given key.
*
* <p>If the key does not exist or its value is not an int array tag,
* then an empty array will be returned.</p>
*
* @param key the key
* @return an int array
*/
public int[] getIntArray(String key) {
Tag tag = value.get(key);
if (tag instanceof IntArrayTag) {
return ((IntArrayTag) tag).getValue();
} else {
return new int[0];
}
}
/**
* Get an int named with the given key.
*
* <p>If the key does not exist or its value is not an int tag,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return an int
*/
public int getInt(String key) {
Tag tag = value.get(key);
if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get an int named with the given key, even if it's another
* type of number.
*
* <p>If the key does not exist or its value is not a number,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return an int
*/
public int asInt(String key) {
Tag tag = value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue().intValue();
} else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue().intValue();
} else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue().intValue();
} else {
return 0;
}
}
/**
* Get a list of tags named with the given key.
*
* <p>If the key does not exist or its value is not a list tag,
* then an empty list will be returned.</p>
*
* @param key the key
* @return a list of tags
*/
public List<Tag> getList(String key) {
Tag tag = value.get(key);
if (tag instanceof ListTag) {
return ((ListTag) tag).getValue();
} else {
return Collections.emptyList();
}
}
/**
* Get a {@code TagList} named with the given key.
*
* <p>If the key does not exist or its value is not a list tag,
* then an empty tag list will be returned.</p>
*
* @param key the key
* @return a tag list instance
*/
public ListTag getListTag(String key) {
Tag tag = value.get(key);
if (tag instanceof ListTag) {
return (ListTag) tag;
} else {
return new ListTag(StringTag.class, Collections.<Tag>emptyList());
}
}
/**
* Get a list of tags named with the given key.
*
* <p>If the key does not exist or its value is not a list tag,
* then an empty list will be returned. If the given key references
* a list but the list of of a different type, then an empty
* list will also be returned.</p>
*
* @param key the key
* @param listType the class of the contained type
* @return a list of tags
* @param <T> the type of list
*/
@SuppressWarnings("unchecked")
public <T extends Tag> List<T> getList(String key, Class<T> listType) {
Tag tag = value.get(key);
if (tag instanceof ListTag) {
ListTag listTag = (ListTag) tag;
if (listTag.getType().equals(listType)) {
return (List<T>) listTag.getValue();
} else {
return Collections.emptyList();
}
} else {
return Collections.emptyList();
}
}
/**
* Get a long named with the given key.
*
* <p>If the key does not exist or its value is not a long tag,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return a long
*/
public long getLong(String key) {
Tag tag = value.get(key);
if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
} else {
return 0L;
}
}
/**
* Get a long named with the given key, even if it's another
* type of number.
*
* <p>If the key does not exist or its value is not a number,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return a long
*/
public long asLong(String key) {
Tag tag = value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
} else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue().longValue();
} else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue().longValue();
} else {
return 0L;
}
}
/**
* Get a short named with the given key.
*
* <p>If the key does not exist or its value is not a short tag,
* then {@code 0} will be returned.</p>
*
* @param key the key
* @return a short
*/
public short getShort(String key) {
Tag tag = value.get(key);
if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a string named with the given key.
*
* <p>If the key does not exist or its value is not a string tag,
* then {@code ""} will be returned.</p>
*
* @param key the key
* @return a string
*/
public String getString(String key) {
Tag tag = value.get(key);
if (tag instanceof StringTag) {
return ((StringTag) tag).getValue();
} else {
return "";
}
}
@Override
public String toString() {
StringBuilder bldr = new StringBuilder();
bldr.append("TAG_Compound").append(": ").append(value.size()).append(" entries\r\n{\r\n");
for (Map.Entry<String, Tag> entry : value.entrySet()) {
bldr.append(" ").append(entry.getValue().toString().replaceAll("\r\n", "\r\n ")).append("\r\n");
}
bldr.append("}");
return bldr.toString();
}
}

View File

@ -0,0 +1,204 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import java.util.HashMap;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Helps create compound tags.
*/
public class CompoundTagBuilder {
private final Map<String, Tag> entries;
/**
* Create a new instance.
*/
CompoundTagBuilder() {
this.entries = new HashMap<String, Tag>();
}
/**
* Create a new instance and use the given map (which will be modified).
*
* @param value the value
*/
CompoundTagBuilder(Map<String, Tag> value) {
checkNotNull(value);
this.entries = value;
}
/**
* Put the given key and tag into the compound tag.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder put(String key, Tag value) {
checkNotNull(key);
checkNotNull(value);
entries.put(key, value);
return this;
}
/**
* Put the given key and value into the compound tag as a
* {@code ByteArrayTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putByteArray(String key, byte[] value) {
return put(key, new ByteArrayTag(value));
}
/**
* Put the given key and value into the compound tag as a
* {@code ByteTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putByte(String key, byte value) {
return put(key, new ByteTag(value));
}
/**
* Put the given key and value into the compound tag as a
* {@code DoubleTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putDouble(String key, double value) {
return put(key, new DoubleTag(value));
}
/**
* Put the given key and value into the compound tag as a
* {@code FloatTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putFloat(String key, float value) {
return put(key, new FloatTag(value));
}
/**
* Put the given key and value into the compound tag as a
* {@code IntArrayTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putIntArray(String key, int[] value) {
return put(key, new IntArrayTag(value));
}
/**
* Put the given key and value into the compound tag as an {@code IntTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putInt(String key, int value) {
return put(key, new IntTag(value));
}
/**
* Put the given key and value into the compound tag as a
* {@code LongTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putLong(String key, long value) {
return put(key, new LongTag(value));
}
/**
* Put the given key and value into the compound tag as a
* {@code ShortTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putShort(String key, short value) {
return put(key, new ShortTag(value));
}
/**
* Put the given key and value into the compound tag as a
* {@code StringTag}.
*
* @param key they key
* @param value the value
* @return this object
*/
public CompoundTagBuilder putString(String key, String value) {
return put(key, new StringTag(value));
}
/**
* Put all the entries from the given map into this map.
*
* @param value the map of tags
* @return this object
*/
public CompoundTagBuilder putAll(Map<String, ? extends Tag> value) {
checkNotNull(value);
for (Map.Entry<String, ? extends Tag> entry : value.entrySet()) {
put(entry.getKey(), entry.getValue());
}
return this;
}
/**
* Build an unnamed compound tag with this builder's entries.
*
* @return the new compound tag
*/
public CompoundTag build() {
return new CompoundTag(new HashMap<String, Tag>(entries));
}
/**
* Create a new builder instance.
*
* @return a new builder
*/
public static CompoundTagBuilder create() {
return new CompoundTagBuilder();
}
}

View File

@ -0,0 +1,50 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_Double} tag.
*
*/
public final class DoubleTag extends Tag {
private final double value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public DoubleTag(double value) {
super();
this.value = value;
}
@Override
public Double getValue() {
return value;
}
@Override
public String toString() {
return "TAG_Double(" + value + ")";
}
}

View File

@ -0,0 +1,37 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_End} tag.
*/
public final class EndTag extends Tag {
@Override
public Object getValue() {
return null;
}
@Override
public String toString() {
return "TAG_End";
}
}

View File

@ -0,0 +1,49 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_Float} tag.
*/
public final class FloatTag extends Tag {
private final float value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public FloatTag(float value) {
super();
this.value = value;
}
@Override
public Float getValue() {
return value;
}
@Override
public String toString() {
return "TAG_Float(" + value + ")";
}
}

View File

@ -0,0 +1,60 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* The {@code TAG_Int_Array} tag.
*/
public final class IntArrayTag extends Tag {
private final int[] value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public IntArrayTag(int[] value) {
super();
checkNotNull(value);
this.value = value;
}
@Override
public int[] getValue() {
return value;
}
@Override
public String toString() {
StringBuilder hex = new StringBuilder();
for (int b : value) {
String hexDigits = Integer.toHexString(b).toUpperCase();
if (hexDigits.length() == 1) {
hex.append("0");
}
hex.append(hexDigits).append(" ");
}
return "TAG_Int_Array(" + hex + ")";
}
}

View File

@ -0,0 +1,49 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_Int} tag.
*/
public final class IntTag extends Tag {
private final int value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public IntTag(int value) {
super();
this.value = value;
}
@Override
public Integer getValue() {
return value;
}
@Override
public String toString() {
return "TAG_Int(" + value + ")";
}
}

View File

@ -0,0 +1,431 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* The {@code TAG_List} tag.
*/
public final class ListTag extends Tag {
private final Class<? extends Tag> type;
private final List<Tag> value;
/**
* Creates the tag with an empty name.
*
* @param type the type of tag
* @param value the value of the tag
*/
public ListTag(Class<? extends Tag> type, List<? extends Tag> value) {
super();
checkNotNull(value);
this.type = type;
this.value = Collections.unmodifiableList(value);
}
/**
* Gets the type of item in this list.
*
* @return The type of item in this list.
*/
public Class<? extends Tag> getType() {
return type;
}
@Override
public List<Tag> getValue() {
return value;
}
/**
* Create a new list tag with this tag's name and type.
*
* @param list the new list
* @return a new list tag
*/
public ListTag setValue(List<Tag> list) {
return new ListTag(getType(), list);
}
/**
* Get the tag if it exists at the given index.
*
* @param index the index
* @return the tag or null
*/
@Nullable
public Tag getIfExists(int index) {
try {
return value.get(index);
} catch (NoSuchElementException e) {
return null;
}
}
/**
* Get a byte array named with the given index.
*
* <p>If the index does not exist or its value is not a byte array tag,
* then an empty byte array will be returned.</p>
*
* @param index the index
* @return a byte array
*/
public byte[] getByteArray(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ByteArrayTag) {
return ((ByteArrayTag) tag).getValue();
} else {
return new byte[0];
}
}
/**
* Get a byte named with the given index.
*
* <p>If the index does not exist or its value is not a byte tag,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return a byte
*/
public byte getByte(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else {
return (byte) 0;
}
}
/**
* Get a double named with the given index.
*
* <p>If the index does not exist or its value is not a double tag,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return a double
*/
public double getDouble(int index) {
Tag tag = getIfExists(index);
if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a double named with the given index, even if it's another
* type of number.
*
* <p>If the index does not exist or its value is not a number,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return a double
*/
public double asDouble(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
} else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue();
} else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a float named with the given index.
*
* <p>If the index does not exist or its value is not a float tag,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return a float
*/
public float getFloat(int index) {
Tag tag = getIfExists(index);
if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a {@code int[]} named with the given index.
*
* <p>If the index does not exist or its value is not an int array tag,
* then an empty array will be returned.</p>
*
* @param index the index
* @return an int array
*/
public int[] getIntArray(int index) {
Tag tag = getIfExists(index);
if (tag instanceof IntArrayTag) {
return ((IntArrayTag) tag).getValue();
} else {
return new int[0];
}
}
/**
* Get an int named with the given index.
*
* <p>If the index does not exist or its value is not an int tag,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return an int
*/
public int getInt(int index) {
Tag tag = getIfExists(index);
if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get an int named with the given index, even if it's another
* type of number.
*
* <p>If the index does not exist or its value is not a number,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return an int
*/
public int asInt(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue().intValue();
} else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue().intValue();
} else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue().intValue();
} else {
return 0;
}
}
/**
* Get a list of tags named with the given index.
*
* <p>If the index does not exist or its value is not a list tag,
* then an empty list will be returned.</p>
*
* @param index the index
* @return a list of tags
*/
public List<Tag> getList(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ListTag) {
return ((ListTag) tag).getValue();
} else {
return Collections.emptyList();
}
}
/**
* Get a {@code TagList} named with the given index.
*
* <p>If the index does not exist or its value is not a list tag,
* then an empty tag list will be returned.</p>
*
* @param index the index
* @return a tag list instance
*/
public ListTag getListTag(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ListTag) {
return (ListTag) tag;
} else {
return new ListTag(StringTag.class, Collections.<Tag>emptyList());
}
}
/**
* Get a list of tags named with the given index.
*
* <p>If the index does not exist or its value is not a list tag,
* then an empty list will be returned. If the given index references
* a list but the list of of a different type, then an empty
* list will also be returned.</p>
*
* @param index the index
* @param listType the class of the contained type
* @return a list of tags
* @param <T> the NBT type
*/
@SuppressWarnings("unchecked")
public <T extends Tag> List<T> getList(int index, Class<T> listType) {
Tag tag = getIfExists(index);
if (tag instanceof ListTag) {
ListTag listTag = (ListTag) tag;
if (listTag.getType().equals(listType)) {
return (List<T>) listTag.getValue();
} else {
return Collections.emptyList();
}
} else {
return Collections.emptyList();
}
}
/**
* Get a long named with the given index.
*
* <p>If the index does not exist or its value is not a long tag,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return a long
*/
public long getLong(int index) {
Tag tag = getIfExists(index);
if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
} else {
return 0L;
}
}
/**
* Get a long named with the given index, even if it's another
* type of number.
*
* <p>If the index does not exist or its value is not a number,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return a long
*/
public long asLong(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
} else if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue().longValue();
} else if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue().longValue();
} else {
return 0;
}
}
/**
* Get a short named with the given index.
*
* <p>If the index does not exist or its value is not a short tag,
* then {@code 0} will be returned.</p>
*
* @param index the index
* @return a short
*/
public short getShort(int index) {
Tag tag = getIfExists(index);
if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else {
return 0;
}
}
/**
* Get a string named with the given index.
*
* <p>If the index does not exist or its value is not a string tag,
* then {@code ""} will be returned.</p>
*
* @param index the index
* @return a string
*/
public String getString(int index) {
Tag tag = getIfExists(index);
if (tag instanceof StringTag) {
return ((StringTag) tag).getValue();
} else {
return "";
}
}
@Override
public String toString() {
StringBuilder bldr = new StringBuilder();
bldr.append("TAG_List").append(": ").append(value.size()).append(" entries of type ").append(NBTUtils.getTypeName(type)).append("\r\n{\r\n");
for (Tag t : value) {
bldr.append(" ").append(t.toString().replaceAll("\r\n", "\r\n ")).append("\r\n");
}
bldr.append("}");
return bldr.toString();
}
}

View File

@ -0,0 +1,119 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Helps create list tags.
*/
public class ListTagBuilder {
private final Class<? extends Tag> type;
private final List<Tag> entries;
/**
* Create a new instance.
*
* @param type of tag contained in this list
*/
ListTagBuilder(Class<? extends Tag> type) {
checkNotNull(type);
this.type = type;
this.entries = new ArrayList<Tag>();
}
/**
* Add the given tag.
*
* @param value the tag
* @return this object
*/
public ListTagBuilder add(Tag value) {
checkNotNull(value);
if (!type.isInstance(value)) {
throw new IllegalArgumentException(value.getClass().getCanonicalName() + " is not of expected type " + type.getCanonicalName());
}
entries.add(value);
return this;
}
/**
* Add all the tags in the given list.
*
* @param value a list of tags
* @return this object
*/
public ListTagBuilder addAll(Collection<? extends Tag> value) {
checkNotNull(value);
for (Tag v : value) {
add(v);
}
return this;
}
/**
* Build an unnamed list tag with this builder's entries.
*
* @return the new list tag
*/
public ListTag build() {
return new ListTag(type, new ArrayList<Tag>(entries));
}
/**
* Create a new builder instance.
*
* @return a new builder
*/
public static ListTagBuilder create(Class<? extends Tag> type) {
return new ListTagBuilder(type);
}
/**
* Create a new builder instance.
*
* @return a new builder
*/
public static <T extends Tag> ListTagBuilder createWith(T ... entries) {
checkNotNull(entries);
if (entries.length == 0) {
throw new IllegalArgumentException("This method needs an array of at least one entry");
}
Class<? extends Tag> type = entries[0].getClass();
for (int i = 1; i < entries.length; i++) {
if (!type.isInstance(entries[i])) {
throw new IllegalArgumentException("An array of different tag types was provided");
}
}
ListTagBuilder builder = new ListTagBuilder(type);
builder.addAll(Arrays.asList(entries));
return builder;
}
}

View File

@ -0,0 +1,50 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_Long} tag.
*
*/
public final class LongTag extends Tag {
private final long value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public LongTag(long value) {
super();
this.value = value;
}
@Override
public Long getValue() {
return value;
}
@Override
public String toString() {
return "TAG_Long(" + value + ")";
}
}

View File

@ -0,0 +1,81 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import java.nio.charset.Charset;
/**
* A class which holds constant values.
*/
public final class NBTConstants {
public static final Charset CHARSET = Charset.forName("UTF-8");
public static final int TYPE_END = 0, TYPE_BYTE = 1, TYPE_SHORT = 2,
TYPE_INT = 3, TYPE_LONG = 4, TYPE_FLOAT = 5, TYPE_DOUBLE = 6,
TYPE_BYTE_ARRAY = 7, TYPE_STRING = 8, TYPE_LIST = 9,
TYPE_COMPOUND = 10, TYPE_INT_ARRAY = 11;
/**
* Default private constructor.
*/
private NBTConstants() {
}
/**
* Convert a type ID to its corresponding {@link Tag} class.
*
* @param id type ID
* @return tag class
* @throws IllegalArgumentException thrown if the tag ID is not valid
*/
public static Class<? extends Tag> getClassFromType(int id) {
switch (id) {
case TYPE_END:
return EndTag.class;
case TYPE_BYTE:
return ByteTag.class;
case TYPE_SHORT:
return ShortTag.class;
case TYPE_INT:
return IntTag.class;
case TYPE_LONG:
return LongTag.class;
case TYPE_FLOAT:
return FloatTag.class;
case TYPE_DOUBLE:
return DoubleTag.class;
case TYPE_BYTE_ARRAY:
return ByteArrayTag.class;
case TYPE_STRING:
return StringTag.class;
case TYPE_LIST:
return ListTag.class;
case TYPE_COMPOUND:
return CompoundTag.class;
case TYPE_INT_ARRAY:
return IntArrayTag.class;
default:
throw new IllegalArgumentException("Unknown tag type ID of " + id);
}
}
}

View File

@ -0,0 +1,171 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class reads <strong>NBT</strong>, or <strong>Named Binary Tag</strong>
* streams, and produces an object graph of subclasses of the {@code Tag}
* object.
*
* <p>The NBT format was created by Markus Persson, and the specification may be
* found at <a href="http://www.minecraft.net/docs/NBT.txt">
* http://www.minecraft.net/docs/NBT.txt</a>.</p>
*/
public final class NBTInputStream implements Closeable {
private final DataInputStream is;
/**
* Creates a new {@code NBTInputStream}, which will source its data
* from the specified input stream.
*
* @param is the input stream
* @throws IOException if an I/O error occurs
*/
public NBTInputStream(InputStream is) throws IOException {
this.is = new DataInputStream(is);
}
/**
* Reads an NBT tag from the stream.
*
* @return The tag that was read.
* @throws IOException if an I/O error occurs.
*/
public NamedTag readNamedTag() throws IOException {
return readNamedTag(0);
}
/**
* Reads an NBT from the stream.
*
* @param depth the depth of this tag
* @return The tag that was read.
* @throws IOException if an I/O error occurs.
*/
private NamedTag readNamedTag(int depth) throws IOException {
int type = is.readByte() & 0xFF;
String name;
if (type != NBTConstants.TYPE_END) {
int nameLength = is.readShort() & 0xFFFF;
byte[] nameBytes = new byte[nameLength];
is.readFully(nameBytes);
name = new String(nameBytes, NBTConstants.CHARSET);
} else {
name = "";
}
return new NamedTag(name, readTagPayload(type, depth));
}
/**
* Reads the payload of a tag given the type.
*
* @param type the type
* @param depth the depth
* @return the tag
* @throws IOException if an I/O error occurs.
*/
private Tag readTagPayload(int type, int depth) throws IOException {
switch (type) {
case NBTConstants.TYPE_END:
if (depth == 0) {
throw new IOException(
"TAG_End found without a TAG_Compound/TAG_List tag preceding it.");
} else {
return new EndTag();
}
case NBTConstants.TYPE_BYTE:
return new ByteTag(is.readByte());
case NBTConstants.TYPE_SHORT:
return new ShortTag(is.readShort());
case NBTConstants.TYPE_INT:
return new IntTag(is.readInt());
case NBTConstants.TYPE_LONG:
return new LongTag(is.readLong());
case NBTConstants.TYPE_FLOAT:
return new FloatTag(is.readFloat());
case NBTConstants.TYPE_DOUBLE:
return new DoubleTag(is.readDouble());
case NBTConstants.TYPE_BYTE_ARRAY:
int length = is.readInt();
byte[] bytes = new byte[length];
is.readFully(bytes);
return new ByteArrayTag(bytes);
case NBTConstants.TYPE_STRING:
length = is.readShort();
bytes = new byte[length];
is.readFully(bytes);
return new StringTag(new String(bytes, NBTConstants.CHARSET));
case NBTConstants.TYPE_LIST:
int childType = is.readByte();
length = is.readInt();
List<Tag> tagList = new ArrayList<Tag>();
for (int i = 0; i < length; ++i) {
Tag tag = readTagPayload(childType, depth + 1);
if (tag instanceof EndTag) {
throw new IOException("TAG_End not permitted in a list.");
}
tagList.add(tag);
}
return new ListTag(NBTUtils.getTypeClass(childType), tagList);
case NBTConstants.TYPE_COMPOUND:
Map<String, Tag> tagMap = new HashMap<String, Tag>();
while (true) {
NamedTag namedTag = readNamedTag(depth + 1);
Tag tag = namedTag.getTag();
if (tag instanceof EndTag) {
break;
} else {
tagMap.put(namedTag.getName(), tag);
}
}
return new CompoundTag(tagMap);
case NBTConstants.TYPE_INT_ARRAY:
length = is.readInt();
int[] data = new int[length];
for (int i = 0; i < length; i++) {
data[i] = is.readInt();
}
return new IntArrayTag(data);
default:
throw new IOException("Invalid tag type: " + type + ".");
}
}
@Override
public void close() throws IOException {
is.close();
}
}

View File

@ -0,0 +1,294 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* This class writes <strong>NBT</strong>, or <strong>Named Binary Tag</strong>
* {@code Tag} objects to an underlying {@code OutputStream}.
*
* <p>The NBT format was created by Markus Persson, and the specification may be
* found at <a href="http://www.minecraft.net/docs/NBT.txt">
* http://www.minecraft.net/docs/NBT.txt</a>.</p>
*/
public final class NBTOutputStream implements Closeable {
/**
* The output stream.
*/
private final DataOutputStream os;
/**
* Creates a new {@code NBTOutputStream}, which will write data to the
* specified underlying output stream.
*
* @param os
* The output stream.
* @throws IOException
* if an I/O error occurs.
*/
public NBTOutputStream(OutputStream os) throws IOException {
this.os = new DataOutputStream(os);
}
/**
* Writes a tag.
*
* @param tag
* The tag to write.
* @throws IOException
* if an I/O error occurs.
*/
public void writeNamedTag(String name, Tag tag) throws IOException {
checkNotNull(name);
checkNotNull(tag);
int type = NBTUtils.getTypeCode(tag.getClass());
byte[] nameBytes = name.getBytes(NBTConstants.CHARSET);
os.writeByte(type);
os.writeShort(nameBytes.length);
os.write(nameBytes);
if (type == NBTConstants.TYPE_END) {
throw new IOException("Named TAG_End not permitted.");
}
writeTagPayload(tag);
}
/**
* Writes tag payload.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeTagPayload(Tag tag) throws IOException {
int type = NBTUtils.getTypeCode(tag.getClass());
switch (type) {
case NBTConstants.TYPE_END:
writeEndTagPayload((EndTag) tag);
break;
case NBTConstants.TYPE_BYTE:
writeByteTagPayload((ByteTag) tag);
break;
case NBTConstants.TYPE_SHORT:
writeShortTagPayload((ShortTag) tag);
break;
case NBTConstants.TYPE_INT:
writeIntTagPayload((IntTag) tag);
break;
case NBTConstants.TYPE_LONG:
writeLongTagPayload((LongTag) tag);
break;
case NBTConstants.TYPE_FLOAT:
writeFloatTagPayload((FloatTag) tag);
break;
case NBTConstants.TYPE_DOUBLE:
writeDoubleTagPayload((DoubleTag) tag);
break;
case NBTConstants.TYPE_BYTE_ARRAY:
writeByteArrayTagPayload((ByteArrayTag) tag);
break;
case NBTConstants.TYPE_STRING:
writeStringTagPayload((StringTag) tag);
break;
case NBTConstants.TYPE_LIST:
writeListTagPayload((ListTag) tag);
break;
case NBTConstants.TYPE_COMPOUND:
writeCompoundTagPayload((CompoundTag) tag);
break;
case NBTConstants.TYPE_INT_ARRAY:
writeIntArrayTagPayload((IntArrayTag) tag);
break;
default:
throw new IOException("Invalid tag type: " + type + ".");
}
}
/**
* Writes a {@code TAG_Byte} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeByteTagPayload(ByteTag tag) throws IOException {
os.writeByte(tag.getValue());
}
/**
* Writes a {@code TAG_Byte_Array} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeByteArrayTagPayload(ByteArrayTag tag) throws IOException {
byte[] bytes = tag.getValue();
os.writeInt(bytes.length);
os.write(bytes);
}
/**
* Writes a {@code TAG_Compound} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeCompoundTagPayload(CompoundTag tag) throws IOException {
for (Map.Entry<String, Tag> entry : tag.getValue().entrySet()) {
writeNamedTag(entry.getKey(), entry.getValue());
}
os.writeByte((byte) 0); // end tag - better way?
}
/**
* Writes a {@code TAG_List} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeListTagPayload(ListTag tag) throws IOException {
Class<? extends Tag> clazz = tag.getType();
List<Tag> tags = tag.getValue();
int size = tags.size();
os.writeByte(NBTUtils.getTypeCode(clazz));
os.writeInt(size);
for (Tag tag1 : tags) {
writeTagPayload(tag1);
}
}
/**
* Writes a {@code TAG_String} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeStringTagPayload(StringTag tag) throws IOException {
byte[] bytes = tag.getValue().getBytes(NBTConstants.CHARSET);
os.writeShort(bytes.length);
os.write(bytes);
}
/**
* Writes a {@code TAG_Double} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeDoubleTagPayload(DoubleTag tag) throws IOException {
os.writeDouble(tag.getValue());
}
/**
* Writes a {@code TAG_Float} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeFloatTagPayload(FloatTag tag) throws IOException {
os.writeFloat(tag.getValue());
}
/**
* Writes a {@code TAG_Long} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeLongTagPayload(LongTag tag) throws IOException {
os.writeLong(tag.getValue());
}
/**
* Writes a {@code TAG_Int} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeIntTagPayload(IntTag tag) throws IOException {
os.writeInt(tag.getValue());
}
/**
* Writes a {@code TAG_Short} tag.
*
* @param tag
* The tag.
* @throws IOException
* if an I/O error occurs.
*/
private void writeShortTagPayload(ShortTag tag) throws IOException {
os.writeShort(tag.getValue());
}
/**
* Writes a {@code TAG_Empty} tag.
*
* @param tag the tag
*/
private void writeEndTagPayload(EndTag tag) {
/* empty */
}
private void writeIntArrayTagPayload(IntArrayTag tag) throws IOException {
int[] data = tag.getValue();
os.writeInt(data.length);
for (int aData : data) {
os.writeInt(aData);
}
}
@Override
public void close() throws IOException {
os.close();
}
}

View File

@ -0,0 +1,170 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import java.util.Map;
/**
* A class which contains NBT-related utility methods.
*
*/
public final class NBTUtils {
/**
* Default private constructor.
*/
private NBTUtils() {
}
/**
* Gets the type name of a tag.
*
* @param clazz the tag class
* @return The type name.
*/
public static String getTypeName(Class<? extends Tag> clazz) {
if (clazz.equals(ByteArrayTag.class)) {
return "TAG_Byte_Array";
} else if (clazz.equals(ByteTag.class)) {
return "TAG_Byte";
} else if (clazz.equals(CompoundTag.class)) {
return "TAG_Compound";
} else if (clazz.equals(DoubleTag.class)) {
return "TAG_Double";
} else if (clazz.equals(EndTag.class)) {
return "TAG_End";
} else if (clazz.equals(FloatTag.class)) {
return "TAG_Float";
} else if (clazz.equals(IntTag.class)) {
return "TAG_Int";
} else if (clazz.equals(ListTag.class)) {
return "TAG_List";
} else if (clazz.equals(LongTag.class)) {
return "TAG_Long";
} else if (clazz.equals(ShortTag.class)) {
return "TAG_Short";
} else if (clazz.equals(StringTag.class)) {
return "TAG_String";
} else if (clazz.equals(IntArrayTag.class)) {
return "TAG_Int_Array";
} else {
throw new IllegalArgumentException("Invalid tag classs ("
+ clazz.getName() + ").");
}
}
/**
* Gets the type code of a tag class.
*
* @param clazz the tag class
* @return The type code.
* @throws IllegalArgumentException if the tag class is invalid.
*/
public static int getTypeCode(Class<? extends Tag> clazz) {
if (clazz.equals(ByteArrayTag.class)) {
return NBTConstants.TYPE_BYTE_ARRAY;
} else if (clazz.equals(ByteTag.class)) {
return NBTConstants.TYPE_BYTE;
} else if (clazz.equals(CompoundTag.class)) {
return NBTConstants.TYPE_COMPOUND;
} else if (clazz.equals(DoubleTag.class)) {
return NBTConstants.TYPE_DOUBLE;
} else if (clazz.equals(EndTag.class)) {
return NBTConstants.TYPE_END;
} else if (clazz.equals(FloatTag.class)) {
return NBTConstants.TYPE_FLOAT;
} else if (clazz.equals(IntTag.class)) {
return NBTConstants.TYPE_INT;
} else if (clazz.equals(ListTag.class)) {
return NBTConstants.TYPE_LIST;
} else if (clazz.equals(LongTag.class)) {
return NBTConstants.TYPE_LONG;
} else if (clazz.equals(ShortTag.class)) {
return NBTConstants.TYPE_SHORT;
} else if (clazz.equals(StringTag.class)) {
return NBTConstants.TYPE_STRING;
} else if (clazz.equals(IntArrayTag.class)) {
return NBTConstants.TYPE_INT_ARRAY;
} else {
throw new IllegalArgumentException("Invalid tag classs ("
+ clazz.getName() + ").");
}
}
/**
* Gets the class of a type of tag.
*
* @param type the type
* @return The class.
* @throws IllegalArgumentException if the tag type is invalid.
*/
public static Class<? extends Tag> getTypeClass(int type) {
switch (type) {
case NBTConstants.TYPE_END:
return EndTag.class;
case NBTConstants.TYPE_BYTE:
return ByteTag.class;
case NBTConstants.TYPE_SHORT:
return ShortTag.class;
case NBTConstants.TYPE_INT:
return IntTag.class;
case NBTConstants.TYPE_LONG:
return LongTag.class;
case NBTConstants.TYPE_FLOAT:
return FloatTag.class;
case NBTConstants.TYPE_DOUBLE:
return DoubleTag.class;
case NBTConstants.TYPE_BYTE_ARRAY:
return ByteArrayTag.class;
case NBTConstants.TYPE_STRING:
return StringTag.class;
case NBTConstants.TYPE_LIST:
return ListTag.class;
case NBTConstants.TYPE_COMPOUND:
return CompoundTag.class;
case NBTConstants.TYPE_INT_ARRAY:
return IntArrayTag.class;
default:
throw new IllegalArgumentException("Invalid tag type : " + type
+ ".");
}
}
/**
* Get child tag of a NBT structure.
*
* @param items the map to read from
* @param key the key to look for
* @param expected the expected NBT class type
* @return child tag
* @throws IllegalArgumentException
*/
public static <T extends Tag> T getChildTag(Map<String, Tag> items, String key, Class<T> expected) throws IllegalArgumentException {
if (!items.containsKey(key)) {
throw new IllegalArgumentException("Missing a \"" + key + "\" tag");
}
Tag tag = items.get(key);
if (!expected.isInstance(tag)) {
throw new IllegalArgumentException(key + " tag is not of tag type " + expected.getName());
}
return expected.cast(tag);
}
}

View File

@ -0,0 +1,63 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A tag that has a name.
*/
public class NamedTag {
private final String name;
private final Tag tag;
/**
* Create a new named tag.
*
* @param name the name
* @param tag the tag
*/
public NamedTag(String name, Tag tag) {
checkNotNull(name);
checkNotNull(tag);
this.name = name;
this.tag = tag;
}
/**
* Get the name of the tag.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Get the tag.
*
* @return the tag
*/
public Tag getTag() {
return tag;
}
}

View File

@ -0,0 +1,49 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* The {@code TAG_Short} tag.
*/
public final class ShortTag extends Tag {
private final short value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public ShortTag(short value) {
super();
this.value = value;
}
@Override
public Short getValue() {
return value;
}
@Override
public String toString() {
return "TAG_Short(" + value + ")";
}
}

View File

@ -0,0 +1,52 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* The {@code TAG_String} tag.
*/
public final class StringTag extends Tag {
private final String value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public StringTag(String value) {
super();
checkNotNull(value);
this.value = value;
}
@Override
public String getValue() {
return value;
}
@Override
public String toString() {
return "TAG_String(" + value + ")";
}
}

View File

@ -0,0 +1,34 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.java.sk89q.jnbt;
/**
* Represents a NBT tag.
*/
public abstract class Tag {
/**
* Gets the value of this tag.
*
* @return the value
*/
public abstract Object getValue();
}

View File

@ -6,7 +6,8 @@ public enum CurrencyType
{
Tokens(" Tokens", Material.EMERALD),
Coins(" Coins", Material.DOUBLE_PLANT),
Gems(" Gems", Material.EMERALD);
Gems(" Gems", Material.EMERALD),
Gold(" Gold", Material.GOLD_NUGGET);
private String _prefix;
private Material _displayMaterial;

View File

@ -26,7 +26,7 @@ public enum Rank
//Media
YOUTUBE("YouTube", ChatColor.RED),
YOUTUBE_SMALL("MooTube", ChatColor.DARK_PURPLE),
YOUTUBE_SMALL("YT", ChatColor.DARK_PURPLE),
TWITCH("Twitch", ChatColor.DARK_PURPLE),
//Player
@ -116,4 +116,12 @@ public enum Rank
{
return _donor;
}
public String getRawTag()
{
if (Name.equalsIgnoreCase("ALL"))
return "";
return Name;
}
}

View File

@ -1,4 +1,4 @@
package mineplex.core.data;
package mineplex.core.common.block;
import org.bukkit.block.Block;
import org.bukkit.Material;

View File

@ -0,0 +1,104 @@
package mineplex.core.common.block.schematic;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
public class Schematic
{
private final short _width;
private final short _height;
private final short _length;
private final short[] _blocks;
private final byte[] _blockData;
public Schematic(short width, short height, short length, short[] blocks, byte[] blockData)
{
_width = width;
_height = height;
_length = length;
_blocks = blocks;
_blockData = blockData;
}
public void paste(Location originLocation)
{
int startX = originLocation.getBlockX();
int startY = originLocation.getBlockY();
int startZ = originLocation.getBlockZ();
for (int x = 0; x < _width; x++)
{
for (int y = 0; y < _height; y++)
{
for (int z = 0; z < _length; z++)
{
int index = getIndex(x, y, z);
Block block = originLocation.getWorld().getBlockAt(startX + x, startY + y, startZ + z);
// some blocks were giving me negative id's in the schematic (like stairs)
// not sure why but the math.abs is my simple fix
int materialId = Math.abs(_blocks[index]);
Material material = Material.getMaterial(materialId);
if (material == null)
{
System.out.println(materialId + " data: " + _blockData[index]);
continue;
}
block.setTypeIdAndData(materialId, _blockData[index], false);
}
}
}
}
public int getSize()
{
return _blocks.length;
}
public int getIndex(int x, int y, int z)
{
return y * _width * _length + z * _width + x;
}
public short getBlock(int x, int y, int z)
{
return _blocks[getIndex(x, y, z)];
}
public byte getData(int x, int y, int z)
{
return _blockData[getIndex(x, y, z)];
}
public short getWidth()
{
return _width;
}
public short getHeight()
{
return _height;
}
public short getLength()
{
return _length;
}
public short[] getBlocks()
{
return _blocks;
}
public byte[] getBlockData()
{
return _blockData;
}
@Override
public String toString()
{
return String.format("width: %d, length: %d, height: %d, blockLength: %d, blockDataLength: %d", _width, _length, _height, _blocks.length, _blockData.length);
}
}

View File

@ -0,0 +1,120 @@
package mineplex.core.common.block.schematic;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import mineplex.core.common.block.BlockData;
import mineplex.core.common.util.Callback;
public class SchematicRunnable implements Runnable
{
private JavaPlugin _plugin;
private boolean _started;
private BukkitTask _task;
private List<BlockData> _changedBlocks;
private Callback<List<BlockData>> _callback;
private Schematic _schematic;
private Block _startBlock;
private int _currentX = 0;
private int _currentY = 0;
private int _currentZ = 0;
private int _blocksPerTick = 1000;
public SchematicRunnable(JavaPlugin plugin, Schematic schematic, Block startBlock, Callback<List<BlockData>> callback)
{
_plugin = plugin;
_changedBlocks = new ArrayList<BlockData>(schematic.getSize());
_started = false;
_callback = callback;
_schematic = schematic;
_startBlock = startBlock;
}
public void start()
{
if (!_started)
{
_task = Bukkit.getScheduler().runTaskTimer(_plugin, this, 1, 1);
_started = true;
}
}
public void pause()
{
if (_started)
{
_task.cancel();
_started = false;
}
}
public void setBlocksPerTick(int blocksPerTick)
{
_blocksPerTick = blocksPerTick;
}
@Override
public void run()
{
for (int i = 0; i < _blocksPerTick; i++)
{
setBlock(_startBlock.getRelative(_currentX, _currentY, _currentZ), _currentX, _currentY, _currentZ);
_currentX++;
if (_currentX >= _schematic.getWidth())
{
_currentX = 0;
_currentZ++;
if (_currentZ >= _schematic.getLength())
{
_currentZ = 0;
_currentY++;
if (_currentY >= _schematic.getHeight())
{
// We are done
System.out.println("Finished importing schematic with setblockrunnable!");
if (_callback != null)
_callback.run(_changedBlocks);
_task.cancel();
return;
}
}
}
}
}
private void setBlock(Block block, int x, int y, int z)
{
int materialId = _schematic.getBlock(x, y, z);
byte data = _schematic.getData(x, y, z);
Material material = Material.getMaterial(materialId);
if (material == null)
{
System.out.println("Failed to find material with id: " + materialId);
return;
}
if (block.getTypeId() == materialId && block.getData() == data)
return;
BlockData blockData = new BlockData(block);
_changedBlocks.add(blockData);
block.setTypeIdAndData(materialId, data, false);
}
}

View File

@ -0,0 +1,76 @@
package mineplex.core.common.block.schematic;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import com.java.sk89q.jnbt.ByteArrayTag;
import com.java.sk89q.jnbt.CompoundTag;
import com.java.sk89q.jnbt.NBTInputStream;
import com.java.sk89q.jnbt.NamedTag;
import com.java.sk89q.jnbt.ShortTag;
import com.java.sk89q.jnbt.Tag;
public class UtilSchematic
{
public static Schematic loadSchematic(File file) throws IOException
{
FileInputStream fis = new FileInputStream(file);
NBTInputStream nbtStream = new NBTInputStream(new GZIPInputStream(fis));
NamedTag rootTag = nbtStream.readNamedTag();
nbtStream.close();
if (!rootTag.getName().equals("Schematic"))
return null;
CompoundTag schematicTag = (CompoundTag) rootTag.getTag();
Map<String, Tag> schematic = schematicTag.getValue();
short width = getChildTag(schematic, "Width", ShortTag.class).getValue();
short height = getChildTag(schematic, "Height", ShortTag.class).getValue();
short length = getChildTag(schematic, "Length", ShortTag.class).getValue();
byte[] blockId = getChildTag(schematic, "Blocks", ByteArrayTag.class).getValue();
byte[] addId = new byte[0];
short[] blocks = new short[blockId.length];
byte[] blockData = getChildTag(schematic, "Data", ByteArrayTag.class).getValue();
if (schematic.containsKey("AddBlocks"))
{
addId = getChildTag(schematic, "AddBlocks", ByteArrayTag.class).getValue();
}
for (int index = 0; index < blockId.length; index++)
{
if ((index >> 1) >= addId.length)
blocks[index] = (short) (blockId[index] & 0xFF);
else
{
if ((index & 1) == 0)
blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (blockId[index] & 0xFF));
else
blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (blockId[index] & 0xFF));
}
}
return new Schematic(width, height, length, blocks, blockData);
}
private static <T extends Tag> T getChildTag(Map<String, Tag> items, String key, Class<T> expected)
{
Tag tag = items.get(key);
return expected.cast(tag);
}
public static void main(String[] args) throws IOException
{
File file = new File("test.schematic");
System.out.println(file.getAbsoluteFile());
Schematic m = UtilSchematic.loadSchematic(file);
System.out.println(m);
}
}

View File

@ -0,0 +1,78 @@
package mineplex.core.common.player;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
public class PlayerSnapshot
{
private Location _location;
private ItemStack[] _armor;
private ItemStack[] _items;
private double _health;
private int _hunger;
private float _saturation;
private float _exhaustion;
private int _experience;
private Vector _velocity;
private PlayerSnapshot(Location location, ItemStack[] armor, ItemStack[] items, double health, int hunger, float saturation, float exhaustion, int experience, Vector velocity)
{
_location = location;
_armor = armor;
_items = items;
_health = health;
_hunger = hunger;
_saturation = saturation;
_exhaustion = exhaustion;
_experience = experience;
_velocity = velocity;
}
public void applySnapshot(Player player)
{
player.teleport(_location);
player.getInventory().setArmorContents(_armor);
player.getInventory().setContents(_items);
player.setHealth(_health);
player.setFoodLevel(_hunger);
player.setSaturation(_saturation);
player.setExhaustion(_exhaustion);
player.setVelocity(_velocity);
player.setTotalExperience(_experience);
}
public static PlayerSnapshot getSnapshot(Player player)
{
Location location = player.getLocation();
// Inventory
ItemStack[] bArmor = player.getInventory().getArmorContents();
ItemStack[] armor = new ItemStack[bArmor.length];
for (int i = 0; i < bArmor.length; i++)
{
armor[i] = bArmor[i];
}
ItemStack[] bItems = player.getInventory().getContents();
ItemStack[] items = new ItemStack[bItems.length];
for (int i = 0; i < bItems.length; i++)
{
items[i] = bItems[i];
}
// Health
double health = player.getHealth();
int hunger = player.getFoodLevel();
float saturation = player.getSaturation();
float exhaustion = player.getExhaustion();
int experience = player.getTotalExperience();
Vector velocity = player.getVelocity();
return new PlayerSnapshot(location, armor, items, health, hunger, saturation, exhaustion, experience, velocity);
}
}

View File

@ -10,6 +10,7 @@ public class C
public static String BoldStrike = "§l§m";
public static String Line = "§n";
public static String Italics = "§o";
public static String Reset = "§r";
public static String cAqua = "" + ChatColor.AQUA;
public static String cBlack = "" + ChatColor.BLACK;
@ -87,22 +88,26 @@ public class C
public static String chat = "" + ChatColor.WHITE;
public static String xBorderlands = "" + ChatColor.GOLD;
public static String xWilderness = "" + ChatColor.YELLOW;
public static String xWilderness = "" + ChatColor.GRAY;
public static String xMid = "" + ChatColor.WHITE;
public static String xNone = "" + ChatColor.GRAY;
public static ChatColor xNone = ChatColor.YELLOW;
public static ChatColor xAdmin = ChatColor.WHITE;
public static ChatColor xSafe = ChatColor.AQUA;
public static ChatColor xNeutral = ChatColor.YELLOW;
public static ChatColor xSelf = ChatColor.AQUA;
public static ChatColor xAlly = ChatColor.GREEN;
public static ChatColor xEnemy = ChatColor.YELLOW;
public static ChatColor xWar = ChatColor.RED;
public static ChatColor xEnemy = ChatColor.RED;
public static ChatColor xWarWinning = ChatColor.LIGHT_PURPLE;
public static ChatColor xWarLosing = ChatColor.RED;
public static ChatColor xPillage = ChatColor.LIGHT_PURPLE;
public static ChatColor xdNeutral = ChatColor.GOLD;
public static ChatColor xdSelf = ChatColor.DARK_AQUA;
public static ChatColor xdAlly = ChatColor.DARK_GREEN;
public static ChatColor xdEnemy = ChatColor.GOLD;
public static ChatColor xdWar = ChatColor.DARK_RED;
public static ChatColor xdEnemy = ChatColor.DARK_RED;
public static ChatColor xdWarWinning = ChatColor.DARK_PURPLE;
public static ChatColor xdWarLosing = ChatColor.DARK_RED;
public static ChatColor xdPillage = ChatColor.DARK_PURPLE;
}

View File

@ -0,0 +1,132 @@
package mineplex.core.common.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class NautArrayList<Elem>
{
private ArrayList<Elem> _wrappedArrayList = new ArrayList<Elem>();
public boolean add(Elem elem)
{
return _wrappedArrayList.add(elem);
}
public void add(int index, Elem elem)
{
_wrappedArrayList.add(index, elem);
}
public boolean addAll(Collection<? extends Elem> elements)
{
return _wrappedArrayList.addAll(elements);
}
public boolean addAll(int index, Collection<? extends Elem> elements)
{
return _wrappedArrayList.addAll(index, elements);
}
public void clear()
{
_wrappedArrayList.clear();
}
public boolean contains(Elem elem)
{
return _wrappedArrayList.contains(elem);
}
public boolean containsAll(Collection<? extends Elem> elements)
{
return _wrappedArrayList.containsAll(elements);
}
public Elem get(int index)
{
return _wrappedArrayList.get(index);
}
public boolean equals(Object o)
{
return _wrappedArrayList.equals(o);
}
public int hashCode()
{
return _wrappedArrayList.hashCode();
}
public int indexOf(Elem elem)
{
return _wrappedArrayList.indexOf(elem);
}
public boolean isEmpty()
{
return _wrappedArrayList.isEmpty();
}
public Iterator<Elem> iterator()
{
return _wrappedArrayList.iterator();
}
public int lastIndexOf(Elem elem)
{
return _wrappedArrayList.lastIndexOf(elem);
}
public ListIterator<Elem> listIterator()
{
return _wrappedArrayList.listIterator();
}
public ListIterator<Elem> listIterator(int index)
{
return _wrappedArrayList.listIterator(index);
}
public Elem remove(int index)
{
return _wrappedArrayList.remove(index);
}
public boolean remove(Elem element)
{
return _wrappedArrayList.remove(element);
}
public boolean removeAll(Collection<? extends Elem> elements)
{
return _wrappedArrayList.removeAll(elements);
}
public boolean retainAll(Collection<? extends Elem> elements)
{
return _wrappedArrayList.retainAll(elements);
}
public Elem set(int index, Elem element)
{
return _wrappedArrayList.set(index, element);
}
public int size()
{
return _wrappedArrayList.size();
}
public List<Elem> subList(int begin, int end)
{
return _wrappedArrayList.subList(begin, end);
}
public Object[] toArray()
{
return _wrappedArrayList.toArray();
}
}

View File

@ -1,6 +1,8 @@
package mineplex.core.common.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
@ -8,15 +10,24 @@ import java.util.TreeSet;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.util.EulerAngle;
import org.bukkit.util.Vector;
import net.minecraft.server.v1_8_R3.EnumDirection;
public class UtilAlg
{
public static TreeSet<String> sortKey(Set<String> toSort)
{
TreeSet<String> sortedSet = new TreeSet<String>();
for (String cur : toSort)
return sortSet(toSort, null);
}
public static <T> TreeSet<T> sortSet(Collection<T> toSort, Comparator<T> comparator)
{
TreeSet<T> sortedSet = new TreeSet<T>(comparator);
for (T cur : toSort)
sortedSet.add(cur);
return sortedSet;
@ -39,7 +50,7 @@ public class UtilAlg
public static Vector getTrajectory(Vector from, Vector to)
{
return to.subtract(from).normalize();
return to.clone().subtract(from).normalize();
}
public static Vector getTrajectory2d(Entity from, Entity to)
@ -54,7 +65,7 @@ public class UtilAlg
public static Vector getTrajectory2d(Vector from, Vector to)
{
return to.subtract(from).setY(0).normalize();
return to.clone().subtract(from).setY(0).normalize();
}
public static boolean HasSight(Location from, Player to)
@ -407,6 +418,55 @@ public class UtilAlg
return bestLoc;
}
public static Vector calculateVelocity(Vector from, Vector to, double heightGain, Entity entity)
{
if (entity instanceof LivingEntity)
{
return calculateVelocity(from, to, heightGain, 1.15);
}
else
{
return calculateVelocity(from, to, heightGain, 0.115);
}
}
public static Vector calculateVelocity(Vector from, Vector to, double heightGain)
{
return calculateVelocity(from, to, heightGain, 0.115);
}
public static Vector calculateVelocity(Vector from, Vector to, double heightGain, double gravity)
{
// Block locations
int endGain = to.getBlockY() - from.getBlockY();
double dx1 = to.getBlockX() - from.getBlockX();
double dz1 = to.getBlockZ() - from.getBlockZ();
double horizDist = Math.sqrt(dx1 * dx1 + dz1 * dz1);
// Height gain
double maxGain = heightGain > (endGain + heightGain) ? heightGain : (endGain + heightGain);
// Solve quadratic equation for velocity
double a = -horizDist * horizDist / (4 * maxGain);
double b = horizDist;
double c = -endGain;
double slope = -b / (2 * a) - Math.sqrt(b * b - 4 * a * c) / (2 * a);
// Vertical velocity
double vy = Math.sqrt(maxGain * gravity);
// Horizontal velocity
double vh = vy / slope;
// Calculate horizontal direction
int dx = to.getBlockX() - from.getBlockX();
int dz = to.getBlockZ() - from.getBlockZ();
double mag = Math.sqrt(dx * dx + dz * dz);
double dirx = dx / mag;
double dirz = dz / mag;
// Horizontal velocity components
double vx = vh * dirx;
double vz = vh * dirz;
return new Vector(vx, vy, vz);
}
public static Location getNearestCornerLocation(Location near, Block block)
{
ArrayList<Location> corners = new ArrayList<Location>();
@ -439,4 +499,15 @@ public class UtilAlg
return value;
}
public static EulerAngle vectorToEuler(Vector vector)
{
//JUST MAKE SURE THE ARMOR STAND ISNT ROTATED.
return new EulerAngle(
Math.toRadians(UtilAlg.GetPitch(vector)),
Math.toRadians(UtilAlg.GetYaw(vector)),
0);
}
}

View File

@ -29,11 +29,11 @@ import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftCreature;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftLivingEntity;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
@ -291,6 +291,8 @@ public class UtilEnt
creatureMap.put("WitherSkull", EntityType.WITHER_SKULL);
creatureMap.put("Wolf", EntityType.WOLF);
creatureMap.put("Zombie", EntityType.ZOMBIE);
creatureMap.put("Guardian", EntityType.GUARDIAN);
creatureMap.put("Rabbit", EntityType.RABBIT);
creatureMap.put("Item", EntityType.DROPPED_ITEM);
}
@ -457,6 +459,28 @@ public class UtilEnt
return ents;
}
public static HashMap<Entity, Double> getAllInRadius(Location loc, double dR)
{
HashMap<Entity, Double> ents = new HashMap<Entity, Double>();
for (Entity cur : loc.getWorld().getEntities())
{
if (UtilPlayer.isSpectator(cur))
continue;
//Loc
double offset = UtilMath.offset(loc, cur.getLocation());
if (offset < dR)
{
ents.put(cur, 1 - (offset/dR));
continue;
}
}
return ents;
}
public static boolean hitBox(Location loc, LivingEntity ent, double mult, EntityType disguise)
{
if (disguise != null)
@ -480,7 +504,7 @@ public class UtilEnt
}
else if (UtilMath.offset2d(loc, player.getLocation()) < 0.6 * mult)
{
if (loc.getY() > player.getLocation().getY() && loc.getY() < player.getEyeLocation().getY())
if (loc.getY() >= player.getLocation().getY() - 0.2*mult && loc.getY() <= player.getEyeLocation().getY() + 0.2*mult)
{
return true;
}
@ -508,10 +532,27 @@ public class UtilEnt
}
public static boolean isGrounded(Entity ent)
{
if(!(ent instanceof Player)) {
return ent.isOnGround();
}
AxisAlignedBB box = ((CraftEntity)ent).getHandle().getBoundingBox().shrink(0.05, 0, 0.05);
Location bottom_corner_1 = new Location(ent.getWorld(), box.a, ent.getLocation().getY()-0.05, box.c);
Location bottom_corner_2 = new Location(ent.getWorld(), box.d, ent.getLocation().getY()-0.05, box.f);
for(Block b : UtilBlock.getInBoundingBox(bottom_corner_1, bottom_corner_2)){
if(UtilBlock.solid(b)) return true;
}
return false;
}
public static boolean isGrounded(Entity ent, Location loc)
{
AxisAlignedBB box = ((CraftEntity)ent).getHandle().getBoundingBox();
Location bottom_corner_1 = new Location(ent.getWorld(), box.a, ent.getLocation().getY()-0.1, box.c);
Location bottom_corner_2 = new Location(ent.getWorld(), box.d, ent.getLocation().getY()-0.1, box.f);
Location bottom_corner_1 = new Location(ent.getWorld(), box.a, loc.getY()-0.1, box.c);
Location bottom_corner_2 = new Location(ent.getWorld(), box.d, loc.getY()-0.1, box.f);
for(Block b : UtilBlock.getInBoundingBox(bottom_corner_1, bottom_corner_2)){
if(UtilBlock.solid(b)) return true;
@ -616,6 +657,11 @@ public class UtilEnt
return CreatureLook(ent, UtilAlg.GetPitch(vec), UtilAlg.GetYaw(vec));
}
public static boolean CreatureLook(Entity ent, Vector target)
{
return CreatureLook(ent, UtilAlg.GetPitch(target), UtilAlg.GetYaw(target));
}
public static void setFakeHead(Entity ent, boolean fakeHead)
{
net.minecraft.server.v1_8_R3.Entity ec = ((CraftEntity) ent).getHandle();
@ -759,6 +805,20 @@ public class UtilEnt
return null;
}
public static void setAI(LivingEntity entity, boolean ai)
{
if(entity instanceof ArmorStand)
{
((ArmorStand)entity).setGravity(ai);
return;
}
CraftEntity e = (CraftEntity)entity;
if(e.getHandle() instanceof EntityInsentient)
{
((EntityInsentient)e.getHandle()).k(!ai);
}
}
public static boolean inWater(LivingEntity ent)
{
return ent.getLocation().getBlock().getTypeId() == 8 || ent.getLocation().getBlock().getTypeId() == 9;

View File

@ -16,7 +16,8 @@ public class UtilEvent
L_BLOCK,
R,
R_AIR,
R_BLOCK
R_BLOCK,
ANY
}
public static boolean isAction(PlayerInteractEvent event, ActionType action)
@ -39,6 +40,9 @@ public class UtilEvent
if (action == ActionType.R_BLOCK)
return (event.getAction() == Action.RIGHT_CLICK_BLOCK);
if (action == ActionType.ANY)
return event.getAction() != Action.PHYSICAL;
return false;
}

View File

@ -0,0 +1,310 @@
package mineplex.core.common.util;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class UtilFile
{
public static void writePlainFile(File file, String text) throws FileNotFoundException
{
PrintWriter writer = new PrintWriter(file);
writer.print(text);
writer.close();
}
/**
* Will read the specified file, and return the contents, or a null value,
* if an exception is thrown. Will handle all exceptions, and simply ignore
* them and return null. No stack trace printed or anything.
*/
public static String readIgnoreErrors(File file)
{
try
{
return readToStr(file);
}
catch (IOException exception)
{
return null;
}
}
public static String readToStr(File file) throws IOException
{
return new String(readAllBytes(file));
}
public static byte[] readAllBytes(File file) throws IOException
{
return Files.readAllBytes(Paths.get(file.toURI()));
}
public static void writePlainFile(String file, String text) throws FileNotFoundException
{
writePlainFile(new File(file), text);
}
/**
* Will read the specified file, and return the contents, or a null value,
* if an exception is thrown. Will handle all exceptions, and simply ignore
* them and return null. No stack trace printed or anything.
*/
public static String readIgnoreErrors(String file)
{
return readIgnoreErrors(new File(file));
}
public static String readToStr(String file) throws IOException
{
return readToStr(new File(file));
}
public static byte[] readAllBytes(String file) throws IOException
{
return readAllBytes(new File(file));
}
public static void writeDataFile(File file, DataFileChunk... chunks) throws IOException
{
DataOutputStream stream = new DataOutputStream(new FileOutputStream(file));
for (DataFileChunk chunk : chunks)
{
chunk.writeTo(stream);
}
stream.close();
}
public static DataFileReader beginReading(String file) throws FileNotFoundException
{
return beginReading(new File(file));
}
public static DataFileReader beginReading(File file) throws FileNotFoundException
{
return new DataFileReader(file);
}
public static void writeDataFile(String file, DataFileChunk... chunks) throws IOException
{
writeDataFile(new File(file), chunks);
}
public static class DataFileChunk
{
private ChunkType _type;
private Object _value;
public DataFileChunk(ChunkType type, Object value)
{
if (type == null)
{
throw new RuntimeException("ChunkType can NOT be null.");
}
_type = type;
if (!_type.isValid(value))
{
throw new RuntimeException("Invalid value provided for the specified ChunkType.");
}
_value = value;
}
public void writeTo(DataOutputStream stream) throws IOException
{
_type.writeTo(stream, _value);
}
}
public static enum ChunkType
{
STRING(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
String str = (String) value;
INTEGER.writeTo(stream, str.length());
for (char b : str.toCharArray())
{
CHAR.writeTo(stream, b);
}
}
public boolean isValid(Object value)
{
return value.getClass().equals(String.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
int length = (int) INTEGER.readFrom(stream);
StringBuilder string = new StringBuilder();
for (int i = 0; i < length; i++)
{
string.append(CHAR.readFrom(stream));
}
return string.toString();
}
}),
DOUBLE(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
double number = (double) value;
stream.writeDouble(number);
}
public boolean isValid(Object value)
{
return value.getClass().equals(Double.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return stream.readDouble();
}
}),
INTEGER(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
int number = (int) value;
stream.writeInt(number);
}
public boolean isValid(Object value)
{
return value.getClass().equals(Integer.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return stream.readInt();
}
}),
BYTE(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
byte number = (byte) value;
stream.writeByte(number);
}
public boolean isValid(Object value)
{
return value.getClass().equals(Byte.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return stream.readByte();
}
}),
CHAR(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
char number = (char) value;
stream.writeChar(number);
}
public boolean isValid(Object value)
{
return value.getClass().equals(Character.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return stream.readChar();
}
}),
LONG(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
long number = (long) value;
stream.writeLong(number);
}
public boolean isValid(Object value)
{
return value.getClass().equals(Long.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return stream.readLong();
}
});
private ChunkImpl _impl;
ChunkType(ChunkImpl impl)
{
_impl = impl;
}
protected void writeTo(DataOutputStream stream, Object value) throws IOException
{
_impl.writeTo(stream, value);
}
protected boolean isValid(Object value)
{
return value != null && _impl.isValid(value);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return _impl.readFrom(stream);
}
}
public static class DataFileReader
{
private DataInputStream _stream;
public DataFileReader(File file) throws FileNotFoundException
{
_stream = new DataInputStream(new FileInputStream(file));
}
public Object readChunk(ChunkType type) throws IOException
{
return type.readFrom(_stream);
}
public void close() throws IOException
{
_stream.close();
}
}
protected interface ChunkImpl
{
void writeTo(DataOutputStream stream, Object value) throws IOException;
Object readFrom(DataInputStream stream) throws IOException;
boolean isValid(Object value);
}
}

View File

@ -13,6 +13,43 @@ public class UtilGear
private static HashSet<Material> pickSet = new HashSet<Material>();
private static HashSet<Material> diamondSet = new HashSet<Material>();
private static HashSet<Material> goldSet = new HashSet<Material>();
private static HashSet<Material> _armorSet = new HashSet<Material>();
public static boolean isArmor(ItemStack item)
{
if (item == null)
return false;
if (_armorSet.isEmpty())
{
_armorSet.add(Material.LEATHER_HELMET);
_armorSet.add(Material.LEATHER_CHESTPLATE);
_armorSet.add(Material.LEATHER_LEGGINGS);
_armorSet.add(Material.LEATHER_BOOTS);
_armorSet.add(Material.GOLD_HELMET);
_armorSet.add(Material.GOLD_CHESTPLATE);
_armorSet.add(Material.GOLD_LEGGINGS);
_armorSet.add(Material.GOLD_BOOTS);
_armorSet.add(Material.CHAINMAIL_HELMET);
_armorSet.add(Material.CHAINMAIL_CHESTPLATE);
_armorSet.add(Material.CHAINMAIL_LEGGINGS);
_armorSet.add(Material.CHAINMAIL_BOOTS);
_armorSet.add(Material.IRON_HELMET);
_armorSet.add(Material.IRON_CHESTPLATE);
_armorSet.add(Material.IRON_LEGGINGS);
_armorSet.add(Material.IRON_BOOTS);
_armorSet.add(Material.DIAMOND_HELMET);
_armorSet.add(Material.DIAMOND_CHESTPLATE);
_armorSet.add(Material.DIAMOND_LEGGINGS);
_armorSet.add(Material.DIAMOND_BOOTS);
}
return _armorSet.contains(item.getType());
}
public static boolean isAxe(ItemStack item)
{
@ -126,6 +163,10 @@ public class UtilGear
{
goldSet.add(Material.GOLD_SWORD);
goldSet.add(Material.GOLD_AXE);
goldSet.add(Material.GOLD_HELMET);
goldSet.add(Material.GOLD_CHESTPLATE);
goldSet.add(Material.GOLD_LEGGINGS);
goldSet.add(Material.GOLD_BOOTS);
}
return goldSet.contains(item.getType());

View File

@ -2,7 +2,7 @@ package mineplex.core.common.util;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;
import java.util.Random;
@ -24,13 +24,18 @@ public class UtilMath
return Double.valueOf(twoDForm.format(d));
}
public static Random random = new Random();
public static int r(int i)
{
return random.nextInt(i);
}
public static int rRange(int min, int max)
{
return min + r(1 + max - min);
}
public static double offset2d(Entity a, Entity b)
{
return offset2d(a.getLocation().toVector(), b.getLocation().toVector());
@ -60,7 +65,7 @@ public class UtilMath
public static double offset(Vector a, Vector b)
{
return a.subtract(b).length();
return a.clone().subtract(b).length();
}
public static double offsetSquared(Entity a, Entity b)
@ -80,16 +85,35 @@ public class UtilMath
public static double rr(double d, boolean bidirectional)
{
if (bidirectional)
return Math.random() * (2 * d) - d;
if (bidirectional) return Math.random() * (2 * d) - d;
return Math.random() * d;
}
public static <T> T randomElement(T[] array) {
if (array.length == 0)
return null;
public static <T> T randomElement(T[] array)
{
if (array.length == 0) return null;
return array[random.nextInt(array.length)];
}
public static <T> T randomElement(List<T> list)
{
if (list.isEmpty()) return null;
return list.get(random.nextInt(list.size()));
}
public static double clamp(double num, double min, double max)
{
return num < min ? min : (num > max ? max : num);
}
public static long clamp(long num, long min, long max)
{
return num < min ? min : (num > max ? max : num);
}
public static int clamp(int num, int min, int max)
{
return num < min ? min : (num > max ? max : num);
}
}

View File

@ -1,14 +1,12 @@
package mineplex.core.common.util;
import java.lang.reflect.Field;
import mineplex.core.common.util.UtilParticle.ViewDist;
import net.minecraft.server.v1_8_R3.EnumParticle;
import net.minecraft.server.v1_8_R3.PacketPlayOutWorldParticles;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import net.minecraft.server.v1_8_R3.EnumParticle;
import net.minecraft.server.v1_8_R3.PacketPlayOutWorldParticles;
public class UtilParticle
{
@ -243,6 +241,28 @@ public class UtilParticle
return packet;
}
public static void PlayParticle(ParticleType type,Location location, float offsetX, float offsetY,
float offsetZ, float speed, int count, ViewDist dist)
{
PlayParticle(type, location, offsetX, offsetY, offsetZ, speed, count, dist, UtilServer.getPlayers());
}
public static void PlayParticleToAll(ParticleType type, Location location, Vector offset, float speed, int count, ViewDist dist)
{
PlayParticle(type, location, (float) offset.getX(), (float) offset.getY(), (float) offset.getZ(), speed, count, dist, UtilServer.getPlayers());
}
public static void PlayParticle(ParticleType type, Location location, Vector offset, float speed, int count, ViewDist dist, Player... players)
{
PlayParticle(type, location, (float) offset.getX(), (float) offset.getY(), (float) offset.getZ(), speed, count, dist, players);
}
public static void PlayParticleToAll(ParticleType type, Location location, float offsetX, float offsetY, float offsetZ,
float speed, int count, ViewDist dist)
{
PlayParticle(type.particleName, location, offsetX, offsetY, offsetZ, speed, count, dist, UtilServer.getPlayers());
}
public static void PlayParticle(ParticleType type, Location location, float offsetX, float offsetY, float offsetZ,
float speed, int count, ViewDist dist, Player... players)
{

View File

@ -4,13 +4,12 @@ import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import net.minecraft.server.v1_8_R3.EntityPlayer;
import net.minecraft.server.v1_8_R3.Packet;
import net.minecraft.server.v1_8_R3.PlayerConnection;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity;
@ -21,10 +20,23 @@ import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.potion.PotionEffect;
import org.bukkit.util.Vector;
import net.minecraft.server.v1_8_R3.EntityPlayer;
import net.minecraft.server.v1_8_R3.Packet;
import net.minecraft.server.v1_8_R3.PlayerConnection;
public class UtilPlayer
{
private static Random RANDOM = new Random();
// A mapping of player names (Keys) to the system time when they last changed active Hotbar Slot
private static Map<String, Long> _hotbarUpdates = new HashMap<String, Long>();
// The amount of time (in milliseconds) after changin hotbars that you can block
public static final long BLOCKING_HOTBAR_DELAY = 100;
private static boolean hasIntersection(Vector3D p1, Vector3D p2, Vector3D min, Vector3D max)
{
final double epsilon = 0.0001f;
@ -154,6 +166,30 @@ public class UtilPlayer
return hit;
}
/**
* @param player - the player to be checked for blocking status
* @return true, if the {@code player} is blocking and has not recently
* changed hotbar slots (within {@value BLOCKING_HOTBAR_DELAY} milliseconds), false otherwise.
*/
public static boolean isBlocking(Player player)
{
String name = player.getName();
long lastUpdate = _hotbarUpdates.containsKey(name) ? _hotbarUpdates.get(name) : 0;;
long duration = System.currentTimeMillis() - lastUpdate;
return player.isBlocking();// && UtilItem.isSword(player.getItemInHand())
//&& duration >= BLOCKING_HOTBAR_DELAY;
}
/**
* Mark the {@code player} as having changed hotbar slots.
* @param player - the player to be marked
*/
public static void onHotbarChange(Player player)
{
_hotbarUpdates.put(player.getName(), System.currentTimeMillis());
}
/**
* AviodAllies doesn't work. Leaving as a param as it sounds like something you may want in the future.
*/
@ -392,7 +428,12 @@ public class UtilPlayer
return matchList;
}
public static LinkedList<Player> getNearby(Location loc, double maxDist)
public static List<Player> getNearby(Location loc, double maxDist)
{
return getNearby(loc, maxDist, false);
}
public static List<Player> getNearby(Location loc, double maxDist, boolean onlySurvival)
{
LinkedList<Player> nearbyMap = new LinkedList<Player>();
@ -404,8 +445,10 @@ public class UtilPlayer
if (cur.isDead())
continue;
double dist = loc.toVector().subtract(cur.getLocation().toVector()).length();
if (onlySurvival && cur.getGameMode() != GameMode.SURVIVAL)
continue;
double dist = loc.distance(cur.getLocation());
if (dist > maxDist)
continue;
@ -453,7 +496,7 @@ public class UtilPlayer
return best;
}
public static Player getClosest(Location loc, Entity ignore)
public static Player getClosest(Location loc, Entity... ignore)
{
Player best = null;
double bestDist = 0;
@ -466,8 +509,14 @@ public class UtilPlayer
if (cur.isDead())
continue;
if (ignore != null && ignore.equals(cur))
if (ignore != null)
{
for (int i = 0; i < ignore.length; i++)
{
if (cur.equals(ignore[i]))
continue;
}
}
double dist = UtilMath.offset(cur.getLocation(), loc);
@ -499,6 +548,14 @@ public class UtilPlayer
System.out.println("Kicked Client [" + player.getName() + "] for [" + module + " - " + message + "]");
}
public static void kick(Collection<Player> players, String module, String message, boolean log)
{
for (Player player : players)
{
kick(player, module, message, log);
}
}
public static HashMap<Player, Double> getInRadius(Location loc, double dR)
{
HashMap<Player, Double> players = new HashMap<Player, Double>();
@ -590,6 +647,23 @@ public class UtilPlayer
return (((CraftEntity) player).getHandle().getDataWatcher().getByte(0) & 1 << 4) != 0;
}
public static void clearInventory(Player player)
{
player.getInventory().clear();
player.getInventory().setHelmet(null);
player.getInventory().setChestplate(null);
player.getInventory().setLeggings(null);
player.getInventory().setBoots(null);
}
public static void clearPotionEffects(Player player)
{
for (PotionEffect effect : player.getActivePotionEffects())
{
player.removePotionEffect(effect.getType());
}
}
public static void sendPacket(Player player, Packet... packets)
{
PlayerConnection connection = ((CraftPlayer) player).getHandle().playerConnection;
@ -603,6 +677,18 @@ public class UtilPlayer
}
}
/**
* Get a random player within maxDist of the target location
* @param location The center location to look for the player
* @param maxDist The max distance from location that the player can be
* @return A random player that is within maxDist of location, or null if no players apply
*/
public static Player getRandomTarget(Location location, double maxDist)
{
List<Player> nearby = getNearby(location, maxDist, true);
return nearby.size() > 0 ? nearby.get(RANDOM.nextInt(nearby.size())) : null;
}
public static boolean isSpectator(Entity player)
{
if (player instanceof Player)

View File

@ -1,5 +1,11 @@
package mineplex.core.common.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.Sound;
@ -12,6 +18,25 @@ public class UtilServer
return getServer().getOnlinePlayers().toArray(new Player[0]);
}
public static List<Player> getSortedPlayers()
{
return getSortedPlayers(new Comparator<Player>()
{
@Override
public int compare(Player o1, Player o2)
{
return o1.getName().compareTo(o2.getName());
}
});
}
public static List<Player> getSortedPlayers(Comparator<Player> comparator)
{
ArrayList<Player> players = new ArrayList<Player>(getServer().getOnlinePlayers());
Collections.sort(players, comparator);
return players;
}
public static Server getServer()
{
return Bukkit.getServer();
@ -23,6 +48,12 @@ public class UtilServer
UtilPlayer.message(cur, message);
}
public static void broadcast(LinkedList<String> messages)
{
for (Player cur : getPlayers())
UtilPlayer.message(cur, messages);
}
public static void broadcastSpecial(String event, String message)
{
for (Player cur : getPlayers())

View File

@ -1,6 +1,13 @@
package mineplex.core.common.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
public class UtilSkull
{
@ -25,6 +32,19 @@ public class UtilSkull
return 3;
}
public static ItemStack getPlayerHead(String playerName, String itemName, List<String> itemLore)
{
boolean displayHead = !playerName.isEmpty();
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short) 0, displayHead ? (byte) 3 : 0);
SkullMeta meta = ((SkullMeta) skull.getItemMeta());
if (displayHead)
meta.setOwner(playerName);
meta.setDisplayName(itemName);
meta.setLore(itemLore);
skull.setItemMeta(meta);
return skull;
}
public static boolean isPlayerHead(byte data)
{
return data == 3;

View File

@ -3,6 +3,7 @@ package mineplex.core.common.util;
import java.util.Collection;
import org.apache.commons.lang.WordUtils;
import org.bukkit.Material;
public class UtilText {
public static <T> String listToString(Collection<T> inputList, boolean comma) {
@ -95,4 +96,18 @@ public class UtilText {
public static String[] wrap(String text, int lineLength, boolean wrapLongerWords) {
return WordUtils.wrap(text, lineLength, "\00D0", wrapLongerWords).split("\00D0");
}
public static String repeat(String txt, int times)
{
return new String(new byte[times]).replace("\0", txt);
}
public static boolean plural(int x){
return x <= 0 ? true : x > 1;
}
public static String trim(int maxLength, String s) {
return s.length() <= maxLength ? s : s.substring(0, maxLength);
}
}

View File

@ -44,12 +44,33 @@ public class UtilTime
public enum TimeUnit
{
FIT,
DAYS,
HOURS,
MINUTES,
SECONDS,
MILLISECONDS
FIT(1),
DAYS(86400000),
HOURS(3600000),
MINUTES(60000),
SECONDS(1000),
MILLISECONDS(1);
private long _ms;
TimeUnit(long ms)
{
_ms = ms;
}
public long getMilliseconds()
{
return _ms;
}
}
/**
* Convert from one TimeUnit to a different one
*/
public static long convert(long time, TimeUnit from, TimeUnit to)
{
long milleseconds = time * from.getMilliseconds();
return milleseconds / to.getMilliseconds();
}
public static String since(long epoch)

View File

@ -0,0 +1,36 @@
package mineplex.core.common.util;
public class UtilUI
{
public static int[] getIndicesFor(int items, int startingLine, int newLinePadding)
{
return getIndicesFor(items, startingLine, 5, newLinePadding);
}
public static int[] getIndicesFor(int items, int startingLine)
{
return getIndicesFor(items, startingLine, 5, 0);
}
public static int[] getIndicesFor(int items, int startingLine, int itemsPerLine, int newLinePadding)
{
itemsPerLine = UtilMath.clamp(itemsPerLine, 1, 5);
int[] indices = new int[items];
int lines = (int) Math.ceil(items / ((double) itemsPerLine));
for (int line = 0; line < lines; line++)
{
int itemsInCurLine = line == lines - 1 ? items - (line * itemsPerLine) : itemsPerLine;
int startIndex = (startingLine * 9) + ((newLinePadding * 9) * line) + 9 * line - itemsInCurLine + 5;
for (int item = 0; item < itemsInCurLine; item++)
{
indices[(line * itemsPerLine) + item] = startIndex + (item * 2);
}
}
return indices;
}
}

View File

@ -7,6 +7,7 @@ import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.util.Vector;
public class UtilWorld
@ -46,6 +47,54 @@ public class UtilWorld
}
}
public static String blockToStr(Block block)
{
if (block == null)
return "";
return block.getWorld().getName() + "," +
block.getX() + "," +
block.getY() + "," +
block.getZ();
}
public static String blockToStrClean(Block block)
{
if (block == null)
return "";
return "(" + block.getX() + "," +
block.getY() + "," +
block.getZ() + ")";
}
public static Block strToBlock(String string)
{
if (string.length() == 0)
return null;
String[] parts = string.split(",");
try
{
for (World cur : UtilServer.getServer().getWorlds())
{
if (cur.getName().equalsIgnoreCase(parts[0]))
{
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
return cur.getBlockAt(x, y, z);
}
}
}
catch (Exception e)
{
}
return null;
}
public static String locToStr(Location loc)
{
if (loc == null)
@ -65,6 +114,14 @@ public class UtilWorld
return "(" + loc.getBlockX() + ", " + loc.getBlockY() + ", " + loc.getBlockZ() + ")";
}
public static String vecToStrClean(Vector loc)
{
if (loc == null)
return "Null";
return "(" + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ")";
}
public static Location strToLoc(String string)
{
if (string.length() == 0)

View File

@ -13,12 +13,12 @@
<orderEntry type="library" name="jedis" level="project" />
<orderEntry type="library" name="commons-pool2" level="project" />
<orderEntry type="module" module-name="Mineplex.Core.Common" />
<orderEntry type="module" module-name="Classpath.Dummy" />
<orderEntry type="module" module-name="Mineplex.ServerData" />
<orderEntry type="library" name="craftbukkit" level="project" />
<orderEntry type="module" module-name="Mineplex.Database" />
<orderEntry type="library" name="jooq" level="project" />
<orderEntry type="library" name="commons-dbcp2" level="project" />
<orderEntry type="module" module-name="Classpath.Dummy" />
<orderEntry type="library" name="NoCheatPlus" level="project" />
<orderEntry type="module" module-name="Mineplex.PlayerCache" />
</component>

View File

@ -19,13 +19,13 @@ import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
import net.minecraft.server.v1_8_R3.DataWatcher;
import net.minecraft.server.v1_8_R3.DataWatcher.WatchableObject;
import net.minecraft.server.v1_8_R3.MathHelper;
import net.minecraft.server.v1_8_R3.Packet;
import net.minecraft.server.v1_8_R3.PacketPlayInUseEntity;
import net.minecraft.server.v1_8_R3.PacketPlayInUseEntity.EnumEntityUseAction;
import net.minecraft.server.v1_8_R3.PacketPlayOutAttachEntity;
import net.minecraft.server.v1_8_R3.PacketPlayOutEntityDestroy;
import net.minecraft.server.v1_8_R3.PacketPlayOutEntityMetadata;
import net.minecraft.server.v1_8_R3.PacketPlayOutNamedEntitySpawn;
import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntity;
import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntityLiving;
@ -49,8 +49,10 @@ import fr.neatmonster.nocheatplus.hooks.NCPHookManager;
public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
{
private NautHashMap<String, NautHashMap<Integer, Integer>> _entityMap = new NautHashMap<String, NautHashMap<Integer, Integer>>();
private NautHashMap<String, NautHashMap<Integer, Integer[]>> _entityMap = new NautHashMap<String, NautHashMap<Integer, Integer[]>>();
private NautHashMap<String, NautHashMap<Integer, String>> _entityNameMap = new NautHashMap<String, NautHashMap<Integer, String>>();
private NautHashMap<String, NautHashMap<Integer, Integer>> _entityRiding = new NautHashMap<String, NautHashMap<Integer, Integer>>();
private HashSet<String> _loggedIn = new HashSet<String>();
private HashSet<Integer> _ignoreSkulls = new HashSet<Integer>();
@ -63,7 +65,7 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
packetHandler.addPacketHandler(this, true, PacketPlayOutAttachEntity.class, PacketPlayOutEntityDestroy.class,
PacketPlayOutEntityMetadata.class, PacketPlayOutSpawnEntity.class, PacketPlayOutSpawnEntityLiving.class,
PacketPlayInUseEntity.class);
PacketPlayOutNamedEntitySpawn.class, PacketPlayInUseEntity.class, PacketPlayOutAttachEntity.class);
NCPHookManager.addHook(CheckType.MOVING_SURVIVALFLY, this);
NCPHookManager.addHook(CheckType.MOVING_PASSABLE, this);
@ -75,6 +77,7 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
{
_entityMap.remove(event.getPlayer().getName());
_entityNameMap.remove(event.getPlayer().getName());
_entityRiding.remove(event.getPlayer().getName());
_loggedIn.remove(event.getPlayer());
}
@ -167,6 +170,7 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
iterator.remove();
_entityMap.remove(player);
_entityNameMap.remove(player);
_entityRiding.remove(player);
}
}
@ -190,7 +194,7 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
{
if (owner.isOnline() && !_entityMap.containsKey(owner.getName()))
{
_entityMap.put(owner.getName(), new NautHashMap<Integer, Integer>());
_entityMap.put(owner.getName(), new NautHashMap<Integer, Integer[]>());
_entityNameMap.put(owner.getName(), new NautHashMap<Integer, String>());
_loggedIn.add(owner.getName());
}
@ -217,10 +221,15 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
{
if (_entityMap.get(owner.getName()).containsKey(spawnPacket.a))
{
UtilPlayer.sendPacket(owner, new PacketPlayOutEntityDestroy(new int[]
Integer[] ids = _entityMap.get(owner.getName()).get(spawnPacket.a);
int[] newIds = new int[ids.length];
for (int a = 0; a < ids.length; a++)
{
_entityMap.get(owner.getName()).get(spawnPacket.a)
}));
newIds[a] = ids[a];
}
UtilPlayer.sendPacket(owner, new PacketPlayOutEntityDestroy(newIds));
_entityNameMap.get(owner.getName()).remove(spawnPacket.a);
_entityMap.get(owner.getName()).remove(spawnPacket.a);
@ -236,9 +245,59 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
int newId = UtilEnt.getNewEntityId();
_entityNameMap.get(owner.getName()).put(spawnPacket.a, entityName);
_entityMap.get(owner.getName()).put(spawnPacket.a, newId);
_entityMap.get(owner.getName()).put(spawnPacket.a, new Integer[]
{
newId
});
sendProtocolPackets(owner, spawnPacket.a, newId, entityName, verifier, true);
sendProtocolPackets(owner, spawnPacket.a, newId, entityName, verifier, true, -1);
break;
}
}
}
else if (packet instanceof PacketPlayOutNamedEntitySpawn)
{
PacketPlayOutNamedEntitySpawn spawnPacket = (PacketPlayOutNamedEntitySpawn) packet;
for (WatchableObject watchable : (List<WatchableObject>) spawnPacket.i.c())
{
if (watchable.a() == 3 && watchable.b() instanceof Byte && ((Byte) watchable.b()) == 1)
{
if (_entityMap.get(owner.getName()).containsKey(spawnPacket.a))
{
Integer[] ids = _entityMap.get(owner.getName()).get(spawnPacket.a);
int[] newIds = new int[ids.length];
for (int a = 0; a < ids.length; a++)
{
newIds[a] = ids[a];
}
UtilPlayer.sendPacket(owner, new PacketPlayOutEntityDestroy(newIds));
_entityNameMap.get(owner.getName()).remove(spawnPacket.a);
_entityMap.get(owner.getName()).remove(spawnPacket.a);
}
final String entityName = spawnPacket.i.getString(2);
if (entityName.isEmpty())
{
return;
}
int newId = UtilEnt.getNewEntityId();
int newId2 = UtilEnt.getNewEntityId();
_entityNameMap.get(owner.getName()).put(spawnPacket.a, entityName);
_entityMap.get(owner.getName()).put(spawnPacket.a, new Integer[]
{
newId,
newId2
});
sendProtocolPackets(owner, spawnPacket.a, newId2, entityName, verifier, true, newId);
break;
}
}
@ -247,7 +306,7 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
{
PacketPlayOutEntityMetadata metaPacket = (PacketPlayOutEntityMetadata) packet;
if (metaPacket.a != 777777 && !_ignoreSkulls.contains(metaPacket.a))
if (metaPacket.a != 777777 && !_ignoreSkulls.contains(metaPacket.a) && metaPacket.a != owner.getEntityId())
{
boolean isDisplaying = _entityMap.get(owner.getName()).containsKey(metaPacket.a);
String currentName = _entityNameMap.get(owner.getName()).get(metaPacket.a);
@ -279,7 +338,7 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
// If name is still being displayed
if (newDisplay)
{
int newId;
Integer[] newId;
if (isDisplaying) // Sending metadata
{
@ -288,22 +347,28 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
else
// Spawning new entity
{
newId = UtilEnt.getNewEntityId();
newId = new Integer[]
{
UtilEnt.getNewEntityId()
};
_entityMap.get(owner.getName()).put(metaPacket.a, newId);
}
sendProtocolPackets(owner, metaPacket.a, newId, newName, verifier, !isDisplaying);
_entityNameMap.get(owner.getName()).put(metaPacket.a, newName);
sendProtocolPackets(owner, metaPacket.a, newId[0], newName, verifier, !isDisplaying, -1);
}
else
{ // Lets delete it
int id = _entityMap.get(owner.getName()).get(metaPacket.a);
Integer[] ids = _entityMap.get(owner.getName()).get(metaPacket.a);
int[] newIds = new int[ids.length];
UtilPlayer.sendPacket(owner, new PacketPlayOutEntityDestroy(new int[]
for (int a = 0; a < ids.length; a++)
{
id
}));
newIds[a] = ids[a];
}
verifier.bypassProcess(new PacketPlayOutEntityDestroy(newIds));
_entityMap.get(owner.getName()).remove(metaPacket.a);
_entityNameMap.get(owner.getName()).remove(metaPacket.a);
@ -319,10 +384,15 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
{
if (_entityMap.get(owner.getName()).containsKey(id))
{
UtilPlayer.sendPacket(owner, new PacketPlayOutEntityDestroy(new int[]
Integer[] ids = _entityMap.get(owner.getName()).get(id);
int[] newIds = new int[ids.length];
for (int a = 0; a < ids.length; a++)
{
_entityMap.get(owner.getName()).get(id)
}));
newIds[a] = ids[a];
}
UtilPlayer.sendPacket(owner, new PacketPlayOutEntityDestroy(newIds));
_entityMap.get(owner.getName()).remove(id);
_entityNameMap.get(owner.getName()).remove(id);
}
@ -345,9 +415,13 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
{
PacketPlayInUseEntity usePacket = (PacketPlayInUseEntity) packet;
for (Entry<Integer, Integer> entry : _entityMap.get(owner.getName()).entrySet())
loop:
for (Entry<Integer, Integer[]> entry : _entityMap.get(owner.getName()).entrySet())
{
if (entry.getValue() == usePacket.a)
for (int id : entry.getValue())
{
if (id == usePacket.a)
{
PacketPlayInUseEntity newPacket = new PacketPlayInUseEntity();
newPacket.a = entry.getKey();
@ -357,7 +431,63 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
{
((CraftPlayer) owner).getHandle().playerConnection.a(newPacket);
}
break;
break loop;
}
}
}
}
else if (packet instanceof PacketPlayOutAttachEntity)
{
PacketPlayOutAttachEntity attachPacket = (PacketPlayOutAttachEntity) packet;
// c = rider, b = ridden
// When detaching, c is sent, b is -1
// If this attach packet is for a player that has the fix
// If the attach packet isn't ordained by me
if (!_entityMap.containsKey(owner.getName()))
{
return;
}
if (!_entityRiding.containsKey(owner.getName()))
{
_entityRiding.put(owner.getName(), new NautHashMap<Integer, Integer>());
}
int vehicleId = -1;
if (_entityRiding.get(owner.getName()).containsKey(attachPacket.b))
{
vehicleId = _entityRiding.get(owner.getName()).get(attachPacket.b);
}
if (attachPacket.c == -1 && _entityMap.get(owner.getName()).containsKey(vehicleId))
{
Integer[] ids = _entityMap.get(owner.getName()).get(vehicleId);
_entityRiding.get(owner.getName()).remove(attachPacket.b);
sendProtocolPackets(owner, vehicleId, ids[ids.length - 1],
_entityNameMap.get(owner.getName()).get(vehicleId), verifier, true, ids.length > 1 ? ids[0] : -1);
}
else
{
Integer[] ids = _entityMap.get(owner.getName()).get(attachPacket.c);
if (ids != null && ids[0] != attachPacket.b)
{
_entityRiding.get(owner.getName()).put(attachPacket.b, attachPacket.c);
int[] newIds = new int[ids.length];
for (int a = 0; a < ids.length; a++)
{
newIds[a] = ids[a];
}
UtilPlayer.sendPacket(owner, new PacketPlayOutEntityDestroy(newIds));
}
}
}
@ -365,7 +495,7 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
}
private void sendProtocolPackets(final Player owner, final int entityId, final int newEntityId, String entityName,
final PacketVerifier packetList, final boolean newPacket)
final PacketVerifier packetList, final boolean newPacket, final int squidId)
{
CustomTagEvent event = new CustomTagEvent(owner, entityId, entityName);
_plugin.getServer().getPluginManager().callEvent(event);
@ -375,82 +505,47 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
{
public void run()
{
final DataWatcher watcher = new DataWatcher(new DummyEntity(((CraftWorld) owner.getWorld()).getHandle()));
DataWatcher watcher = new DataWatcher(new DummyEntity(((CraftWorld) owner.getWorld()).getHandle()));
watcher.a(0, Byte.valueOf((byte) 0));
watcher.a(0, (byte) (0 | 1 << 5)); // Invisible
watcher.a(1, Short.valueOf((short) 300));
watcher.a(2, "");
watcher.a(3, Byte.valueOf((byte) 0));
watcher.a(2, finalEntityName);
watcher.a(3, (byte) 1);
watcher.a(4, Byte.valueOf((byte) 0));
watcher.a(7, Integer.valueOf(0));
watcher.a(8, Byte.valueOf((byte) 0));
watcher.a(9, Byte.valueOf((byte) 0));
watcher.a(6, Float.valueOf(1.0F));
watcher.a(10, Byte.valueOf((byte) 0));
// Set invisible
int i1 = watcher.getByte(0);
watcher.watch(0, Byte.valueOf((byte) (i1 | 1 << 5)));
// Set small
byte b1 = watcher.getByte(10);
b1 = (byte) (b1 | 0x1);
watcher.watch(10, Byte.valueOf(b1));
watcher.watch(2, finalEntityName);
watcher.watch(3, Byte.valueOf((byte) 1));
watcher.a(10, (byte) (0 | 0x1)); // Small
if (newPacket)
{
if (squidId >= 0)
{
watcher.watch(10, (byte) 16);
DataWatcher squidWatcher = new DataWatcher(new DummyEntity(((CraftWorld) owner.getWorld()).getHandle()));
squidWatcher.a(0, (byte) (0 | 1 << 5));
final PacketPlayOutSpawnEntityLiving spawnPacket = new PacketPlayOutSpawnEntityLiving();
spawnPacket.a = squidId;
spawnPacket.b = (byte) EntityType.SQUID.getTypeId();
spawnPacket.l = squidWatcher;
UtilPlayer.sendPacket(owner, spawnPacket);
PacketPlayOutAttachEntity vehiclePacket = new PacketPlayOutAttachEntity();
vehiclePacket.a = 0;
vehiclePacket.b = spawnPacket.a;
vehiclePacket.c = entityId;
UtilPlayer.sendPacket(owner, vehiclePacket);
}
final PacketPlayOutSpawnEntityLiving spawnPacket = new PacketPlayOutSpawnEntityLiving();
spawnPacket.a = newEntityId;
spawnPacket.b = (byte) 30;
spawnPacket.c = (int) MathHelper.floor(100 * 32);
spawnPacket.d = (int) MathHelper.floor(64 * 32.0D);
spawnPacket.e = (int) MathHelper.floor(100 * 32);
spawnPacket.i = (byte) ((int) (0 * 256.0F / 360.0F));
spawnPacket.j = (byte) ((int) (0 * 256.0F / 360.0F));
spawnPacket.k = (byte) ((int) (0 * 256.0F / 360.0F));
double var2 = 3.9D;
double var4 = 0;
double var6 = 0;
double var8 = 0;
if (var4 < -var2)
{
var4 = -var2;
}
if (var6 < -var2)
{
var6 = -var2;
}
if (var8 < -var2)
{
var8 = -var2;
}
if (var4 > var2)
{
var4 = var2;
}
if (var6 > var2)
{
var6 = var2;
}
if (var8 > var2)
{
var8 = var2;
}
spawnPacket.f = (int) (var4 * 8000.0D);
spawnPacket.g = (int) (var6 * 8000.0D);
spawnPacket.h = (int) (var8 * 8000.0D);
spawnPacket.l = watcher;
@ -459,7 +554,7 @@ public class CustomTagFix extends MiniPlugin implements IPacketHandler, NCPHook
PacketPlayOutAttachEntity vehiclePacket = new PacketPlayOutAttachEntity();
vehiclePacket.a = 0;
vehiclePacket.b = spawnPacket.a;
vehiclePacket.c = entityId;
vehiclePacket.c = squidId >= 0 ? squidId : entityId;
UtilPlayer.sendPacket(owner, vehiclePacket);
}

View File

@ -34,6 +34,7 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent.Result;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
@ -572,4 +573,10 @@ public class CoreClientManager extends MiniPlugin
return client.GetRank().has(rank);
}
public int getCachedClientAccountId(UUID uuid)
{
PlayerInfo playerInfo = PlayerCache.getInstance().getPlayer(uuid);
return playerInfo == null ? -1 : playerInfo.getAccountId();
}
}

View File

@ -28,13 +28,6 @@ public class UpdateRank extends CommandBase<CoreClientManager>
@Override
public void Execute(final Player caller, String[] args)
{
if (!Plugin.Get(caller).GetRank(true).has(caller, Rank.ADMIN, true))
{
return;
}
boolean testServer = Plugin.getPlugin().getConfig().getString("serverstatus.group").equalsIgnoreCase("Testing");
if (args == null)
{
UtilPlayer.message(caller, F.main(Plugin.getName(), "/" + AliasUsed + " joeschmo MODERATOR"));
@ -62,14 +55,6 @@ public class UpdateRank extends CommandBase<CoreClientManager>
final Rank rank = tempRank;
if (rank == Rank.ADMIN || rank == Rank.YOUTUBE || rank == Rank.TWITCH || rank == Rank.MODERATOR || rank == Rank.JNR_DEV || rank == Rank.HELPER || rank == Rank.ALL || rank == Rank.MAPDEV || rank == Rank.SNR_MODERATOR || rank == Rank.SUPPORT)
{
if (!testServer && rank.has(Rank.ADMIN) && !Plugin.hasRank(caller, Rank.LT))
{
UtilPlayer.message(caller, F.main(Plugin.getName(), ChatColor.RED + "" + ChatColor.BOLD + "Insufficient privileges!"));
return;
}
Plugin.getRepository().matchPlayerName(new Callback<List<String>>()
{
public void run(List<String> matches)
@ -137,4 +122,3 @@ public class UpdateRank extends CommandBase<CoreClientManager>
}
}
}
}

View File

@ -277,7 +277,7 @@ public enum Achievement
//Champions
CHAMPIONS_WINS("Champion", 600,
new String[]{"Champions Domination.Wins", "Champions TDM.Wins", "Champions Capture the Flag.Wins"},
new String[]{"Champions Domination.Wins", "Champions TDM.Wins", "Champions CTF.Wins"},
new String[]{"Win 80 games of Dominate, TDM, or CTF"},
new int[]{80},
AchievementCategory.CHAMPIONS),
@ -295,41 +295,47 @@ public enum Achievement
AchievementCategory.CHAMPIONS),
CHAMPIONS_ASSASSINATION("Assassination", 1000,
new String[]{"Champions Domination.Assassination", "Champions TDM.Assassination", "Champions Capture the Flag.Assassination"},
new String[]{"Champions Domination.Assassination", "Champions TDM.Assassination", "Champions CTF.Assassination"},
new String[]{"Kill 40 players with Backstab without", "taking any damage from them"},
new int[]{40},
AchievementCategory.CHAMPIONS),
CHAMPIONS_MASS_ELECTROCUTION("Mass Electrocution", 1200,
new String[]{"Champions Domination.MassElectrocution", "Champions TDM.MassElectrocution", "Champions Capture the Flag.MassElectrocution"},
new String[]{"Champions Domination.MassElectrocution", "Champions TDM.MassElectrocution", "Champions CTF.MassElectrocution"},
new String[]{"Hit 4 enemies with a Lightning Orb"},
new int[]{1},
AchievementCategory.CHAMPIONS),
CHAMPIONS_THE_LONGEST_SHOT("The Longest Shot", 1200,
new String[]{"Champions Domination.TheLongestShot", "Champions TDM.TheLongestShot", "Champions Capture the Flag.TheLongestShot"},
new String[]{"Champions Domination.TheLongestShot", "Champions TDM.TheLongestShot", "Champions CTF.TheLongestShot"},
new String[]{"Kill someone using Longshot who", "is over 64 Blocks away from you"},
new int[]{1},
AchievementCategory.CHAMPIONS),
CHAMPIONS_EARTHQUAKE("Earthquake", 1200,
new String[]{"Champions Domination.Earthquake", "Champions TDM.Earthquake", "Champions Capture the Flag.Earthquake"},
new String[]{"Champions Domination.Earthquake", "Champions TDM.Earthquake", "Champions CTF.Earthquake"},
new String[]{"Launch 5 enemies using Seismic Slam"},
new int[]{1},
AchievementCategory.CHAMPIONS),
CHAMPIONS_CAPTURES("Sticky Fingers", 2500,
new String[]{"Champions Capture the Flag.Captures"},
new String[]{"Champions CTF.Captures"},
new String[]{"Capture the Enemy Flag 20 times"},
new int[]{20},
AchievementCategory.CHAMPIONS),
CHAMPIONS_CLUTCH("Clutch", 600,
new String[]{"Champions Capture the Flag.Clutch"},
new String[]{"Champions CTF.Clutch"},
new String[]{"Kill the Enemy Flag Carrier in Sudden Death"},
new int[]{1},
AchievementCategory.CHAMPIONS),
CHAMPIONS_SPECIAL_WIN("Champion of Champions", 3000,
new String[]{"Champions CTF.SpecialWin"},
new String[]{"Win the game with 5 more captures than the other team"},
new int[]{1},
AchievementCategory.CHAMPIONS),
//Paintball
SUPER_PAINTBALL_WINS("Paintball King", 600,
new String[]{"Super Paintball.Wins"},

View File

@ -78,7 +78,7 @@ public enum AchievementCategory
new StatDisplay[] { StatDisplay.WINS, StatDisplay.GAMES_PLAYED, StatDisplay.GEMS_EARNED },
Material.BOOK_AND_QUILL, 0, GameCategory.CLASSICS, "Extra Tools Kit"),
CHAMPIONS("Champions", new String[] {"Champions Domination", "Champions TDM", "Champions Capture the Flag"},
CHAMPIONS("Champions", new String[] {"Champions Domination", "Champions TDM", "Champions CTF"},
new StatDisplay[] { StatDisplay.WINS, StatDisplay.GAMES_PLAYED, StatDisplay.KILLS, StatDisplay.DEATHS, StatDisplay.GEMS_EARNED, new StatDisplay("Flags Captured", "Captures") },
Material.BEACON, 0, GameCategory.CHAMPIONS, "Extra Class Skills"),

View File

@ -345,7 +345,10 @@ public class AntiHack extends MiniPlugin
}
//Auto-Kick
if (!handled && _clientManager.Get(player).GetRank() != Rank.YOUTUBE && _clientManager.Get(player).GetRank() != Rank.TWITCH)
if (!handled &&
_clientManager.Get(player).GetRank() != Rank.YOUTUBE &&
_clientManager.Get(player).GetRank() != Rank.YOUTUBE_SMALL &&
_clientManager.Get(player).GetRank() != Rank.TWITCH)
{
player.playSound(player.getLocation(), Sound.ENDERDRAGON_GROWL, 2f, 0.5f);

View File

@ -0,0 +1,75 @@
package mineplex.core.blockrestore;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import mineplex.core.common.block.BlockData;
public class BlockDataRunnable implements Runnable
{
private JavaPlugin _plugin;
private boolean _started;
private BukkitTask _task;
private List<BlockData> _changedBlocks;
private Runnable _onComplete;
private int _blocksPerTick;
private Iterator<BlockData> _blockIterator;
public BlockDataRunnable(JavaPlugin plugin, Iterator<BlockData> blockIterator, int blocksPerTick, Runnable onComplete)
{
_plugin = plugin;
_changedBlocks = new ArrayList<BlockData>();
_started = false;
_blocksPerTick = blocksPerTick;
_onComplete = onComplete;
_blockIterator = blockIterator;
}
public void start()
{
if (!_started)
{
_task = Bukkit.getScheduler().runTaskTimer(_plugin, this, 1, 1);
_started = true;
}
}
public void pause()
{
if (_started)
{
_task.cancel();
_started = false;
}
}
public void setBlocksPerTick(int blocksPerTick)
{
_blocksPerTick = blocksPerTick;
}
@Override
public void run()
{
for (int i = 0; i < _blocksPerTick; i++)
{
if (_blockIterator.hasNext())
{
BlockData data = _blockIterator.next();
data.restore();
}
else
{
// We are done
_task.cancel();
_onComplete.run();
return;
}
}
}
}

View File

@ -4,6 +4,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import mineplex.core.MiniPlugin;
import mineplex.core.updater.event.UpdateEvent;
@ -26,28 +27,40 @@ import org.bukkit.plugin.java.JavaPlugin;
public class BlockRestore extends MiniPlugin
{
private HashMap<Block, BlockRestoreData> _blocks = new HashMap<Block, BlockRestoreData>();
private LinkedList<BlockRestoreMap> _restoreMaps;
public BlockRestore(JavaPlugin plugin)
{
super("Block Restore", plugin);
_restoreMaps = new LinkedList<BlockRestoreMap>();
}
@EventHandler(priority=EventPriority.LOW)
public void BlockBreak(BlockBreakEvent event)
public void blockBreak(BlockBreakEvent event)
{
if (Contains(event.getBlock()))
if (contains(event.getBlock()))
{
BlockRestoreData data = _blocks.get(event.getBlock());
if (data != null && data.isRestoreOnBreak())
{
_blocks.remove(event.getBlock());
data.restore();
}
event.setCancelled(true);
}
}
@EventHandler(priority=EventPriority.LOW)
public void blockPlace(BlockPlaceEvent event)
{
if (contains(event.getBlockPlaced()))
event.setCancelled(true);
}
@EventHandler(priority=EventPriority.LOW)
public void BlockPlace(BlockPlaceEvent event)
{
if (Contains(event.getBlockPlaced()))
event.setCancelled(true);
}
@EventHandler(priority=EventPriority.LOW)
public void Piston(BlockPistonExtendEvent event)
public void piston(BlockPistonExtendEvent event)
{
if (event.isCancelled())
return;
@ -60,7 +73,7 @@ public class BlockRestore extends MiniPlugin
if (push.getType() == Material.AIR)
return;
if (Contains(push))
if (contains(push))
{
push.getWorld().playEffect(push.getLocation(), Effect.STEP_SOUND, push.getTypeId());
event.setCancelled(true);
@ -70,7 +83,7 @@ public class BlockRestore extends MiniPlugin
}
@EventHandler
public void ExpireBlocks(UpdateEvent event)
public void expireBlocks(UpdateEvent event)
{
if (event.getType() != UpdateType.TICK)
return;
@ -86,15 +99,16 @@ public class BlockRestore extends MiniPlugin
_blocks.remove(cur);
}
public void Restore(Block block)
public boolean restore(Block block)
{
if (!Contains(block))
return;
if (!contains(block))
return false;
_blocks.remove(block).restore();
return true;
}
public void RestoreAll()
public void restoreAll()
{
for (BlockRestoreData data : _blocks.values())
data.restore();
@ -102,7 +116,7 @@ public class BlockRestore extends MiniPlugin
_blocks.clear();
}
public HashSet<Location> RestoreBlockAround(Material type, Location location, int radius)
public HashSet<Location> restoreBlockAround(Material type, Location location, int radius)
{
HashSet<Location> restored = new HashSet<Location>();
@ -128,27 +142,36 @@ public class BlockRestore extends MiniPlugin
return restored;
}
public void Add(Block block, int toID, byte toData, long expireTime)
public void add(Block block, int toID, byte toData, long expireTime)
{
Add(block, toID, toData, block.getTypeId(), block.getData(), expireTime);
add(block, toID, toData, expireTime, false);
}
public void Add(Block block, int toID, byte toData, int fromID, byte fromData, long expireTime)
public void add(Block block, int toID, byte toData, long expireTime, boolean restoreOnBreak)
{
if (!Contains(block)) GetBlocks().put(block, new BlockRestoreData(block, toID, toData, fromID, fromData, expireTime, 0));
else GetData(block).update(toID, toData, expireTime);
add(block, toID, toData, block.getTypeId(), block.getData(), expireTime, restoreOnBreak);
}
public void Snow(Block block, byte heightAdd, byte heightMax, long expireTime, long meltDelay, int heightJumps)
public void add(Block block, int toID, byte toData, int fromID, byte fromData, long expireTime)
{
add(block, toID, toData, fromID, fromData, expireTime, false);
}
public void add(Block block, int toID, byte toData, int fromID, byte fromData, long expireTime, boolean restoreOnBreak)
{
if (!contains(block)) getBlocks().put(block, new BlockRestoreData(block, toID, toData, fromID, fromData, expireTime, 0, restoreOnBreak));
else getData(block).update(toID, toData, expireTime);
}
public void snow(Block block, byte heightAdd, byte heightMax, long expireTime, long meltDelay, int heightJumps)
{
//Fill Above
if (((block.getTypeId() == 78 && block.getData() >= (byte)7) || block.getTypeId() == 80) && GetData(block) != null)
if (((block.getTypeId() == 78 && block.getData() >= (byte)7) || block.getTypeId() == 80) && getData(block) != null)
{
GetData(block).update(78, heightAdd, expireTime, meltDelay);
getData(block).update(78, heightAdd, expireTime, meltDelay);
if (heightJumps > 0) Snow(block.getRelative(BlockFace.UP), heightAdd, heightMax, expireTime, meltDelay, heightJumps-1);
if (heightJumps == -1) Snow(block.getRelative(BlockFace.UP), heightAdd, heightMax, expireTime, meltDelay, -1);
if (heightJumps > 0) snow(block.getRelative(BlockFace.UP), heightAdd, heightMax, expireTime, meltDelay, heightJumps - 1);
if (heightJumps == -1) snow(block.getRelative(BlockFace.UP), heightAdd, heightMax, expireTime, meltDelay, -1);
return;
}
@ -188,30 +211,59 @@ public class BlockRestore extends MiniPlugin
heightAdd = 0;
//Snow
if (!Contains(block))
GetBlocks().put(block, new BlockRestoreData(block, 78, (byte)Math.max(0, heightAdd-1), block.getTypeId(), block.getData(), expireTime, meltDelay));
if (!contains(block))
getBlocks().put(block, new BlockRestoreData(block, 78, (byte) Math.max(0, heightAdd - 1), block.getTypeId(), block.getData(), expireTime, meltDelay, false));
else
GetData(block).update(78, heightAdd, expireTime, meltDelay);
getData(block).update(78, heightAdd, expireTime, meltDelay);
}
public boolean Contains(Block block)
public boolean contains(Block block)
{
if (GetBlocks().containsKey(block))
if (getBlocks().containsKey(block))
return true;
for (BlockRestoreMap restoreMap : _restoreMaps)
{
if (restoreMap.contains(block))
return true;
}
return false;
}
public BlockRestoreData GetData(Block block)
public BlockRestoreData getData(Block block)
{
if (_blocks.containsKey(block))
return _blocks.get(block);
return null;
}
public HashMap<Block, BlockRestoreData> GetBlocks()
public HashMap<Block, BlockRestoreData> getBlocks()
{
return _blocks;
}
public BlockRestoreMap createMap()
{
BlockRestoreMap map = new BlockRestoreMap(this);
_restoreMaps.add(map);
return map;
}
protected void removeMap(BlockRestoreMap blockRestore)
{
_restoreMaps.remove(blockRestore);
}
@Override
public void disable()
{
// Clear all restore maps
for (BlockRestoreMap restoreMap : _restoreMaps)
{
restoreMap.restoreInstant();
}
restoreAll();
}
}

View File

@ -25,7 +25,9 @@ public class BlockRestoreData
protected HashMap<Location, Byte> _pad = new HashMap<Location, Byte>();
public BlockRestoreData(Block block, int toID, byte toData, int fromID, byte fromData, long expireDelay, long meltDelay)
protected boolean _restoreOnBreak;
public BlockRestoreData(Block block, int toID, byte toData, int fromID, byte fromData, long expireDelay, long meltDelay, boolean restoreOnBreak)
{
_block = block;
@ -41,6 +43,8 @@ public class BlockRestoreData
_meltDelay = meltDelay;
_meltLast = System.currentTimeMillis();
_restoreOnBreak = restoreOnBreak;
//Set
set();
}
@ -151,6 +155,11 @@ public class BlockRestoreData
_block.setTypeIdAndData(_toID, _toData, true);
}
public boolean isRestoreOnBreak()
{
return _restoreOnBreak;
}
public void restore()
{
_block.setTypeIdAndData(_fromID, _fromData, true);

View File

@ -0,0 +1,181 @@
package mineplex.core.blockrestore;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import org.bukkit.Material;
import org.bukkit.block.Block;
import mineplex.core.common.block.BlockData;
public class BlockRestoreMap
{
private BlockRestore _blockRestore;
// The rate at which we restore blocks
private int _blocksPerTick;
// Easy access to all the blocks we have modified
private HashSet<Block> _changedBlocks;
// A hashmap for each level, so we can quickly restore top down
private HashMap<Block, BlockData>[] _blocks;
protected BlockRestoreMap(BlockRestore blockRestore)
{
this(blockRestore, 50);
}
protected BlockRestoreMap(BlockRestore blockRestore, int blocksPerTick)
{
_blockRestore = blockRestore;
_blocksPerTick = blocksPerTick;
_changedBlocks = new HashSet<Block>();
_blocks = new HashMap[256];
// Populate Array
for (int i = 0; i < 256; i++)
{
_blocks[i] = new HashMap<Block, BlockData>();
}
}
public void addBlockData(BlockData blockData)
{
Block block = blockData.Block;
if (!_blocks[block.getY()].containsKey(block))
_blocks[block.getY()].put(block, blockData);
_changedBlocks.add(blockData.Block);
}
public void set(Block block, Material material)
{
set(block, material, (byte) 0);
}
public void set(Block block, Material material, byte toData)
{
set(block, material.getId(), toData);
}
public void set(Block block, int toId, byte toData)
{
addBlockData(new BlockData(block));
block.setTypeIdAndData(toId, toData, false);
}
public boolean contains(Block block)
{
return _changedBlocks.contains(block);
}
public HashSet<Block> getChangedBlocks()
{
return _changedBlocks;
}
/**
* Restore all the blocks changed in this BlockRestoreMap
* NOTE: You should not use the same BlockRestoreMap instance after you run restore.
* You must initialize a new BlockRestoreMap from BlockRestore
*/
public void restore()
{
// The idea behind this is that the runnable will restore blocks over time
// If the server happens to shutdown while the runnable is running, we will still
// restore all our blocks with restoreInstant (as called by BlockRestore)
BlockDataRunnable runnable = new BlockDataRunnable(_blockRestore.getPlugin(), new RestoreIterator(), _blocksPerTick, new Runnable()
{
@Override
public void run()
{
clearMaps();
_blockRestore.removeMap(BlockRestoreMap.this);
}
});
runnable.start();
}
private void clearMaps()
{
for (int i = 0; i < 256; i++)
{
_blocks[i].clear();
}
_changedBlocks.clear();
}
public void restoreInstant()
{
for (int i = 0; i < 256; i++)
{
HashMap<Block, BlockData> map = _blocks[i];
for (BlockData data : map.values())
{
data.restore();
}
}
clearMaps();
}
public int getBlocksPerTick()
{
return _blocksPerTick;
}
public void setBlocksPerTick(int blocksPerTick)
{
_blocksPerTick = blocksPerTick;
}
private class RestoreIterator implements Iterator<BlockData>
{
private Iterator<BlockData> _currentIterator;
private int _currentIndex;
public RestoreIterator()
{
_currentIndex = 255;
updateIterator();
}
private void updateIterator()
{
_currentIterator = _blocks[_currentIndex].values().iterator();
}
@Override
public boolean hasNext()
{
while (!_currentIterator.hasNext() && _currentIndex > 0)
{
_currentIndex--;
updateIterator();
}
return _currentIterator.hasNext();
}
@Override
public BlockData next()
{
while (!_currentIterator.hasNext() && _currentIndex > 0)
{
_currentIndex--;
updateIterator();
}
return _currentIterator.next();
}
@Override
public void remove()
{
_currentIterator.remove();
}
}
}

View File

@ -732,7 +732,7 @@ public class BonusManager extends MiniClientPlugin<BonusClientData> implements I
if (gold > 0)
{
UtilPlayer.message(player, F.main("Carl", "Rewarded " + F.elem(gold + " Gold")));
_donationManager.RewardGold(new Callback<Boolean>()
_donationManager.rewardGold(new Callback<Boolean>()
{
@Override
public void run(Boolean data)

View File

@ -76,7 +76,7 @@ public abstract class CommandBase<PluginType extends MiniPlugin> implements ICom
return null;
}
protected List<String> getMatches(String start, List<String> possibleMatches)
protected List<String> getMatches(String start, Collection<String> possibleMatches)
{
List<String> matches = new ArrayList<String>();

View File

@ -43,6 +43,14 @@ public class MountPage extends ShopPageBase<CosmeticManager, CosmeticShop>
if (slot == 26)
slot = 28;
}
addButton(4, new ShopItem(Material.BED, C.cGray + " \u21FD Go Back", new String[]{}, 1, false), new IButton()
{
public void onClick(Player player, ClickType clickType)
{
getShop().openPageForPlayer(getPlayer(), new Menu(getPlugin(), getShop(), getClientManager(), getDonationManager(), player));
}
});
}
protected void addMount(Mount<?> mount, int slot)
@ -76,12 +84,5 @@ public class MountPage extends ShopPageBase<CosmeticManager, CosmeticShop>
setItem(slot, new ShopItem(mount.GetDisplayMaterial(), mount.GetDisplayData(), (mount.GetCost(CurrencyType.Coins) < 0 ? "" : "Purchase ") + mount.GetName(), itemLore.toArray(new String[itemLore.size()]), 1, true, false));
}
addButton(4, new ShopItem(Material.BED, C.cGray + " \u21FD Go Back", new String[]{}, 1, false), new IButton()
{
public void onClick(Player player, ClickType clickType)
{
getShop().openPageForPlayer(getPlayer(), new Menu(getPlugin(), getShop(), getClientManager(), getDonationManager(), player));
}
});
}
}

View File

@ -83,7 +83,7 @@ public class Creature extends MiniPlugin
return;
}
CreatureSpawnCustomEvent customEvent = new CreatureSpawnCustomEvent(event.getLocation());
CreatureSpawnCustomEvent customEvent = new CreatureSpawnCustomEvent(event.getLocation(), event.getSpawnReason());
_plugin.getServer().getPluginManager().callEvent(customEvent);

View File

@ -112,7 +112,7 @@ public class MobCommand extends MultiCommandBase<Creature>
HashSet<Entity> entSet = new HashSet<Entity>();
for (int i = 0 ; i < count ; i++)
{
entSet.add(Plugin.SpawnEntity(caller.getTargetBlock((Set<Material>) null, 0).getLocation().add(0.5, 1, 0.5), type));
entSet.add(Plugin.SpawnEntity(caller.getTargetBlock((Set<Material>) null, 150).getLocation().add(0.5, 1, 0.5), type));
}
//Search Vars

View File

@ -4,6 +4,7 @@ import org.bukkit.Location;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
public class CreatureSpawnCustomEvent extends Event implements Cancellable
{
@ -11,10 +12,12 @@ public class CreatureSpawnCustomEvent extends Event implements Cancellable
private boolean _cancelled = false;
private Location _location;
private SpawnReason _reason;
public CreatureSpawnCustomEvent(Location location)
public CreatureSpawnCustomEvent(Location location, SpawnReason reason)
{
_location = location;
_reason = reason;
}
public HandlerList getHandlers()
@ -43,4 +46,9 @@ public class CreatureSpawnCustomEvent extends Event implements Cancellable
{
return _location;
}
public SpawnReason getReason()
{
return _reason;
}
}

View File

@ -1,5 +1,6 @@
package mineplex.core.database;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

View File

@ -607,6 +607,22 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
{
entry.getKey().setEntity(entity);
boolean cancel = entry.getValue().length == 0;
for (Player player : entry.getValue())
{
if (player == owner)
{
cancel = true;
break;
}
}
if (cancel)
{
packetInfo.setCancelled(true);
}
disguise(entry.getKey(), false, entry.getValue());
}
}
@ -864,8 +880,6 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
@EventHandler
public void PlayerQuit(PlayerQuitEvent event)
{
undisguise(event.getPlayer());
for (DisguiseBase disguise : _disguisePlayerMap.keySet())
{
_disguisePlayerMap.get(disguise).remove(event.getPlayer());
@ -875,6 +889,8 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
{
_lastRabbitHop.get(disguise).remove(event.getPlayer().getEntityId());
}
undisguise(event.getPlayer());
}
private void prepareChunk(Location loc)
@ -1046,7 +1062,11 @@ public class DisguiseManager extends MiniPlugin implements IPacketHandler
_movePacketMap.remove(entity.getEntityId());
_moveTempMap.remove(entity.getEntityId());
if (entity instanceof Player)
{
_blockedNames.remove(((Player) entity).getName());
}
refreshTrackers(entity, players.toArray(new Player[0]));

View File

@ -0,0 +1,37 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.EntityType;
public class DisguiseCaveSpider extends DisguiseMonster
{
public DisguiseCaveSpider(org.bukkit.entity.Entity entity)
{
super(EntityType.CAVE_SPIDER, entity);
DataWatcher.a(16, new Byte((byte) 0));
}
public boolean bT()
{
return (DataWatcher.getByte(16) & 0x01) != 0;
}
public void a(boolean flag)
{
byte b0 = DataWatcher.getByte(16);
if (flag)
b0 = (byte) (b0 | 0x1);
else
b0 = (byte) (b0 & 0xFFFFFFFE);
DataWatcher.watch(16, Byte.valueOf(b0));
}
protected String getHurtSound()
{
return "mob.spider.say";
}
}

View File

@ -0,0 +1,38 @@
package mineplex.core.disguise.disguises;
import org.bukkit.entity.*;
public class DisguiseGuardian extends DisguiseCreature
{
public DisguiseGuardian(org.bukkit.entity.Entity entity)
{
super(EntityType.GUARDIAN, entity);
DataWatcher.a(16, 0);
DataWatcher.a(17, 0);
}
public void setTarget(int target)
{
DataWatcher.watch(17, target);
}
public void setElder(boolean elder)
{
DataWatcher.watch(16, Integer.valueOf(DataWatcher.getInt(16) | 4));
}
public boolean isElder()
{
return (this.DataWatcher.getInt(16) & 4) != 0;
}
protected String getHurtSound()
{
if (isElder())
{
return "mob.guardian.elder.hit";
}
return "mob.guardian.hit";
}
}

View File

@ -44,6 +44,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
@Override
public void addCommands()
{
// TODO: Re-add commands? Where are command implementations, seen as missing at the moment.
addCommand(new GemCommand(this));
addCommand(new CoinCommand(this));
addCommand(new GoldCommand(this));
@ -62,7 +63,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
//_repository.updateGemsAndCoins(uuid, Get(token.Name).GetGems(), Get(token.Name).getCoins());
}
public void PurchaseUnknownSalesPackage(final Callback<TransactionResponse> callback, final String name, final int accountId, final String packageName, final boolean coinPurchase, final int cost, boolean oneTimePurchase)
public void PurchaseUnknownSalesPackage(final Callback<TransactionResponse> callback, final String name, final int accountId, final String packageName, final CurrencyType currencyType, final int cost, boolean oneTimePurchase)
{
final Donor donor = Bukkit.getPlayerExact(name) != null ? Get(name) : null;
@ -86,14 +87,14 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
if (donor != null)
{
donor.AddUnknownSalesPackagesOwned(packageName);
donor.DeductCost(cost, coinPurchase ? CurrencyType.Coins : CurrencyType.Gems);
donor.DeductCost(cost, currencyType);
}
}
if (callback != null)
callback.run(response);
}
}, name, accountId, packageName, coinPurchase, cost);
}, name, accountId, packageName, currencyType, cost);
}
public void PurchaseKnownSalesPackage(final Callback<TransactionResponse> callback, final String name, final UUID uuid, final int cost, final int salesPackageId)
@ -295,12 +296,17 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
_coinQueue.clear();
}
public void RewardGold(Callback<Boolean> callback, String caller, String name, int accountId, int amount)
public void rewardGold(Callback<Boolean> callback, String caller, Player player, int amount)
{
RewardGold(callback, caller, name, accountId, amount, true);
rewardGold(callback, caller, player.getName(), ClientManager.Get(player).getAccountId(), amount);
}
public void RewardGold(final Callback<Boolean> callback, final String caller, final String name, final int accountId, final int amount, final boolean updateTotal)
public void rewardGold(Callback<Boolean> callback, String caller, String name, int accountId, int amount)
{
rewardGold(callback, caller, name, accountId, amount, true);
}
public void rewardGold(final Callback<Boolean> callback, final String caller, final String name, final int accountId, final int amount, final boolean updateTotal)
{
_repository.rewardGold(new Callback<Boolean>()
{
@ -324,7 +330,7 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
}
if (callback != null)
callback.run(true);
callback.run(success);
}
}, caller, name, accountId, amount);
}
@ -349,27 +355,49 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
}
@EventHandler
public void UpdateGoldQueue(UpdateEvent event)
public void updateGoldQueue(UpdateEvent event)
{
if (event.getType() != UpdateType.SLOWER)
return;
for (Player player : _goldQueue.keySet())
{
String caller = null;
int total = 0;
updateGoldQueue(null, player);
}
//Clean
_goldQueue.clear();
}
public void updateGoldQueue(final Callback<Boolean> callback, final Player player)
{
String tempCaller = null;
int tempTotal = 0;
for (String curCaller : _goldQueue.get(player).keySet())
{
caller = curCaller;
total += _goldQueue.get(player).get(curCaller);
tempCaller = curCaller;
tempTotal += _goldQueue.get(player).get(curCaller);
}
if (caller == null)
continue;
final String caller = tempCaller;
final int total = tempTotal;
//Actually Add Gold
RewardGold(null, caller, player.getName(), ClientManager.Get(player).getAccountId(), total, false);
if (caller == null)
return;
if (player.isOnline() && player.isValid())
rewardGold(callback, caller, player.getName(), ClientManager.Get(player).getAccountId(), total, false);
else
{
Bukkit.getServer().getScheduler().runTaskAsynchronously(getPlugin(), new Runnable()
{
public void run()
{
rewardGold(callback, caller, player.getName(), PlayerCache.getInstance().getPlayer(player.getUniqueId()).getAccountId(), total, false);
}
});
}
System.out.println("Queue Added [" + player + "] with Gold [" + total + "] for [" + caller + "]");
@ -377,10 +405,6 @@ public class DonationManager extends MiniDbClientPlugin<Donor>
_goldQueue.get(player).clear();
}
//Clean
_goldQueue.clear();
}
public void applyKits(String playerName)
{
_repository.applyKits(playerName);

View File

@ -77,6 +77,10 @@ public class Donor
_coins -= cost;
_update = true;
break;
case Gold:
_gold -= cost;
_update = true;
break;
default:
break;
}
@ -90,6 +94,8 @@ public class Donor
return _gems;
case Coins:
return _coins;
case Gold:
return _gold;
case Tokens:
return 0;
default:
@ -145,7 +151,8 @@ public class Donor
public void addGold(int amount)
{
_gold += amount;
_gold = Math.max(0, _gold + amount);
}
public List<CoinTransactionToken> getCoinTransactions()

View File

@ -73,7 +73,7 @@ public class GoldCommand extends CommandBase<DonationManager>
private void rewardGold(final Player caller, final Player target, final String targetName, final int accountId, final int gold)
{
Plugin.RewardGold(new Callback<Boolean>()
Plugin.rewardGold(new Callback<Boolean>()
{
public void run(Boolean completed)
{

View File

@ -1,11 +1,15 @@
package mineplex.core.donation.repository;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.common.CurrencyType;
import mineplex.core.common.util.Callback;
import mineplex.core.database.DBPool;
import mineplex.core.database.DatabaseRunnable;
@ -69,12 +73,12 @@ public class DonationRepository extends RepositoryBase
}), "Error purchasing known sales package in DonationRepository : ");
}
public void PurchaseUnknownSalesPackage(final Callback<TransactionResponse> callback, final String name, final int accountId, final String packageName, final boolean coinPurchase, final int cost)
public void PurchaseUnknownSalesPackage(final Callback<TransactionResponse> callback, final String name, final int accountId, final String packageName, final CurrencyType currencyType, final int cost)
{
final UnknownPurchaseToken token = new UnknownPurchaseToken();
token.AccountName = name;
token.SalesPackageName = packageName;
token.CoinPurchase = coinPurchase;
token.CoinPurchase = currencyType == CurrencyType.Coins;
token.Cost = cost;
token.Premium = false;
@ -84,11 +88,15 @@ public class DonationRepository extends RepositoryBase
{
if (response == TransactionResponse.Success)
{
if (coinPurchase)
if (currencyType == CurrencyType.Coins)
{
executeUpdate(UPDATE_ACCOUNT_COINS, new ColumnInt("coins", -cost), new ColumnInt("id", accountId));
//executeUpdate(INSERT_COIN_TRANSACTION, new ColumnInt("id", accountId), new ColumnVarChar("reason", 100, "Purchased " + packageName), new ColumnInt("coins", -cost));
}
else if (currencyType == CurrencyType.Gold)
{
executeUpdate(UPDATE_ACCOUNT_GOLD, new ColumnInt("gold", -cost), new ColumnInt("id", accountId));
}
}
Bukkit.getServer().getScheduler().runTask(Plugin, new Runnable()
@ -185,12 +193,8 @@ public class DonationRepository extends RepositoryBase
{
public void run()
{
if (executeUpdate(UPDATE_ACCOUNT_GOLD, new ColumnInt("gold", gold), new ColumnInt("id", accountId)) < 1)
{
callback.run(false);
}
else
callback.run(true);
boolean success = executeUpdate(UPDATE_ACCOUNT_GOLD, new ColumnInt("gold", gold), new ColumnInt("id", accountId)) > 0;
callback.run(success);
}
}), "Error updating player gold amount in DonationRepository : ");
}

View File

@ -29,6 +29,7 @@ import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
@ -134,7 +135,7 @@ public class Explosion extends MiniPlugin
else
{
int heightDiff = cur.getLocation().getBlockY() - event.getEntity().getLocation().getBlockY();
_blockRestore.Add(cur, 0, (byte)0, (long) (20000 + (heightDiff*3000) + Math.random()*2900));
_blockRestore.add(cur, 0, (byte) 0, (long) (20000 + (heightDiff * 3000) + Math.random() * 2900));
}
}
@ -175,6 +176,7 @@ public class Explosion extends MiniPlugin
if (Math.random() > Math.min(0.975, chance))
{
FallingBlock fall = cur.getWorld().spawnFallingBlock(cur.getLocation().add(0.5, 0.5, 0.5), blocks.get(cur).getKey(), blocks.get(cur).getValue());
fall.setDropItem(false);
Vector vec = UtilAlg.getTrajectory(fEnt, fall);
if (vec.getY() < 0) vec.setY(vec.getY() * -1);
@ -207,6 +209,13 @@ public class Explosion extends MiniPlugin
}, 1);
}
@EventHandler
public void ExplosionChangeBlock(EntityChangeBlockEvent event)
{
if (_explosionBlocks.contains(event.getEntity()))
event.setCancelled(true);
}
@EventHandler
public void ExplosionBlockUpdate(UpdateEvent event)
{
@ -239,7 +248,7 @@ public class Explosion extends MiniPlugin
{
if (_temporaryDebris)
{
_blockRestore.Add(block, cur.getBlockId(), cur.getBlockData(), 10000);
_blockRestore.add(block, cur.getBlockId(), cur.getBlockData(), 10000);
}
else
{
@ -256,14 +265,6 @@ public class Explosion extends MiniPlugin
}
}
@EventHandler
public void ExplosionItemSpawn(ItemSpawnEvent event)
{
for (FallingBlock block : _explosionBlocks)
if (UtilMath.offset(event.getEntity().getLocation(), block.getLocation()) < 1)
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOW)
public void ExplosionBlocks(EntityExplodeEvent event)
{
@ -347,6 +348,7 @@ public class Explosion extends MiniPlugin
if (Math.random() > Math.min(0.98, chance))
{
FallingBlock fall = cur.getWorld().spawnFallingBlock(cur.getLocation().add(0.5, 0.5, 0.5), blocks.get(cur).getKey(), blocks.get(cur).getValue());
fall.setDropItem(false);
Vector vec = UtilAlg.getTrajectory(fLoc, fall.getLocation());
if (vec.getY() < 0) vec.setY(vec.getY() * -1);

View File

@ -14,6 +14,7 @@ import mineplex.core.common.util.UtilServer;
import mineplex.core.common.util.UtilTime;
import mineplex.core.disguise.DisguiseManager;
import mineplex.core.donation.DonationManager;
import mineplex.core.gadget.event.GadgetActivateEvent;
import mineplex.core.gadget.event.GadgetCollideEntityEvent;
import mineplex.core.gadget.gadgets.ItemBatGun;
import mineplex.core.gadget.gadgets.ItemCoinBomb;
@ -63,6 +64,7 @@ import mineplex.core.gadget.types.OutfitGadget.ArmorSlot;
import mineplex.core.gadget.types.ParticleGadget;
import mineplex.core.inventory.InventoryManager;
import mineplex.core.mount.MountManager;
import mineplex.core.mount.event.MountActivateEvent;
import mineplex.core.pet.PetManager;
import mineplex.core.preferences.PreferencesManager;
import mineplex.core.projectile.ProjectileManager;
@ -91,6 +93,7 @@ public class GadgetManager extends MiniPlugin
private BlockRestore _blockRestore;
private ProjectileManager _projectileManager;
private AchievementManager _achievementManager;
private MountManager _mountManager;
private NautHashMap<GadgetType, List<Gadget>> _gadgets;
@ -99,6 +102,7 @@ public class GadgetManager extends MiniPlugin
private boolean _hideParticles = false;
private int _activeItemSlot = 3;
private boolean _gadgetsEnabled = true;
public GadgetManager(JavaPlugin plugin, CoreClientManager clientManager, DonationManager donationManager, InventoryManager inventoryManager,
MountManager mountManager, PetManager petManager, PreferencesManager preferencesManager,
@ -115,6 +119,7 @@ public class GadgetManager extends MiniPlugin
_blockRestore = blockRestore;
_projectileManager = projectileManager;
_achievementManager = achievementManager;
_mountManager = mountManager;
CreateGadgets();
}
@ -492,6 +497,40 @@ public class GadgetManager extends MiniPlugin
return true;
}
public boolean isGadgetEnabled()
{
return _gadgetsEnabled;
}
public void toggleGadgetEnabled()
{
setGadgetEnabled(!_gadgetsEnabled);
}
public void setGadgetEnabled(boolean enabled)
{
if (_gadgetsEnabled != enabled)
{
_gadgetsEnabled = enabled;
DisableAll();
_mountManager.DisableAll();
}
}
@EventHandler
public void GadgetActivate(GadgetActivateEvent event)
{
if (!_gadgetsEnabled)
event.setCancelled(true);
}
@EventHandler
public void MountActivate(MountActivateEvent event)
{
if (!_gadgetsEnabled)
event.setCancelled(true);
}
@EventHandler
public void chissMeow(PlayerToggleSneakEvent event)
{

View File

@ -30,7 +30,7 @@ public class ItemFirework extends ItemGadget
},
-1,
Material.FIREWORK, (byte)0,
250, new Ammo("Fireworks", "50 Fireworks", Material.FIREWORK, (byte)0, new String[] { C.cWhite + "50 Fireworks for you to launch!" }, 500, 50));
500, new Ammo("Fireworks", "50 Fireworks", Material.FIREWORK, (byte)0, new String[] { C.cWhite + "50 Fireworks for you to launch!" }, 500, 50));
}
@Override

View File

@ -140,7 +140,7 @@ public class ItemMelonLauncher extends ItemGadget implements IThrown
{
Item melon = melonIterator.next();
if (melon.isDead() || !melon.isValid() || melon.getTicksLived() > 400)
if (melon.isDead() || !melon.isValid() || melon.getTicksLived() > 100)
{
melonIterator.remove();
melon.remove();

View File

@ -164,7 +164,7 @@ public class ItemPaintbrush extends ItemGadget
continue;
//Color
Manager.getBlockRestore().Add(block, 35, _brushColor.get(player.getName()), 30000);
Manager.getBlockRestore().add(block, 35, _brushColor.get(player.getName()), 30000);
//Join Dots
if (_brushPrevious.containsKey(player.getName()))
@ -178,7 +178,7 @@ public class ItemPaintbrush extends ItemGadget
if (fixBlock.getType() != Material.WOOL)
continue;
Manager.getBlockRestore().Add(fixBlock, 35, _brushColor.get(player.getName()), 30000);
Manager.getBlockRestore().add(fixBlock, 35, _brushColor.get(player.getName()), 30000);
}
}

View File

@ -61,7 +61,7 @@ public class ItemTNT extends ItemGadget
if (!_tnt.remove(event.getEntity()))
return;
HashMap<Player, Double> players = UtilPlayer.getInRadius(event.getLocation(), 10);
HashMap<Player, Double> players = UtilPlayer.getInRadius(event.getLocation(), 8);
for (Player player : players.keySet())
{
if (Manager.collideEvent(this, player))
@ -70,7 +70,7 @@ public class ItemTNT extends ItemGadget
double mult = players.get(player);
//Knockback
UtilAction.velocity(player, UtilAlg.getTrajectory(event.getLocation(), player.getLocation()), 3 * mult, false, 0, 0.5 + 2 * mult, 10, true);
UtilAction.velocity(player, UtilAlg.getTrajectory(event.getLocation(), player.getLocation()), 1 * mult, false, 0, 0.5 + 0.5 * mult, 10, true);
}
// Simulating explosion to prevent water from being evaporated.

View File

@ -85,7 +85,7 @@ public class MorphBat extends MorphGadget implements IThrown
if (!UtilEvent.isAction(event, ActionType.L))
return;
if (!Recharge.Instance.use(player, GetName(), 100, false, false))
if (!Recharge.Instance.use(player, GetName(), 100, false, false, "Cosmetics"))
return;
//Effect
@ -106,7 +106,7 @@ public class MorphBat extends MorphGadget implements IThrown
if (!IsActive(player))
return;
if (!Recharge.Instance.use(player, "Poop", 4000, true, false))
if (!Recharge.Instance.use(player, "Poop", 4000, true, false, "Cosmetics"))
return;
//Action

View File

@ -76,7 +76,7 @@ public class MorphChicken extends MorphGadget
if (!UtilEvent.isAction(event, ActionType.L))
return;
if (!Recharge.Instance.use(player, GetName(), 100, false, false))
if (!Recharge.Instance.use(player, GetName(), 100, false, false, "Cosmetics"))
return;
Vector offset = player.getLocation().getDirection();

View File

@ -57,7 +57,7 @@ public class MorphCow extends MorphGadget
if (!UtilEvent.isAction(event, ActionType.L))
return;
if (!Recharge.Instance.use(player, GetName(), 2500, false, false))
if (!Recharge.Instance.use(player, GetName(), 2500, false, false, "Cosmetics"))
return;
player.getWorld().playSound(player.getLocation(), Sound.COW_IDLE, 1f, 1f);

Some files were not shown because too many files have changed in this diff Show More