9
0
mirror of https://github.com/HibiscusMC/HMCCosmetics.git synced 2025-12-30 04:19:28 +00:00

initial work

This commit is contained in:
LoJoSho
2022-11-29 20:10:53 -06:00
parent 0e92fa3f05
commit 2792396e26
71 changed files with 186 additions and 64 deletions

View File

@@ -0,0 +1,114 @@
package com.hibiscusmc.hmccosmetics;
import com.hibiscusmc.hmccosmetics.command.CosmeticCommand;
import com.hibiscusmc.hmccosmetics.command.CosmeticCommandTabComplete;
import com.hibiscusmc.hmccosmetics.config.DatabaseSettings;
import com.hibiscusmc.hmccosmetics.config.Settings;
import com.hibiscusmc.hmccosmetics.config.WardrobeSettings;
import com.hibiscusmc.hmccosmetics.config.serializer.ItemSerializer;
import com.hibiscusmc.hmccosmetics.config.serializer.LocationSerializer;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetics;
import com.hibiscusmc.hmccosmetics.database.Database;
import com.hibiscusmc.hmccosmetics.gui.Menus;
import com.hibiscusmc.hmccosmetics.hooks.items.ItemHooks;
import com.hibiscusmc.hmccosmetics.listener.PlayerConnectionListener;
import com.hibiscusmc.hmccosmetics.listener.PlayerGameListener;
import com.hibiscusmc.hmccosmetics.nms.NMSHandlers;
import com.hibiscusmc.hmccosmetics.util.misc.Translation;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.spongepowered.configurate.ConfigurateException;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import java.io.File;
import java.nio.file.Path;
public final class HMCCosmeticsPlugin extends JavaPlugin {
private static HMCCosmeticsPlugin instance;
@Override
public void onEnable() {
// Plugin startup logic
instance = this;
// NMS version check
if (!NMSHandlers.getHandler().getSupported()) {
getLogger().severe("This version is not supported! Consider switching versions?");
getServer().getPluginManager().disablePlugin(this);
return;
}
// File setup
if (!getDataFolder().exists()) {
saveDefaultConfig();
saveResource("translations.yml", false);
saveResource("messages.yml", false);
saveResource("cosmetics/examplecosmetics.yml", false);
saveResource("menus/examplemenu.yml", false);
}
setup();
// Commands
getServer().getPluginCommand("cosmetic").setExecutor(new CosmeticCommand());
getServer().getPluginCommand("cosmetic").setTabCompleter(new CosmeticCommandTabComplete());
// Listener
getServer().getPluginManager().registerEvents(new PlayerConnectionListener(), this);
getServer().getPluginManager().registerEvents(new PlayerGameListener(), this);
// Database
new Database();
}
@Override
public void onDisable() {
for (Player player : Bukkit.getOnlinePlayers()) {
Database.save(player);
}
// Plugin shutdown logic
}
public static HMCCosmeticsPlugin getInstance() {
return instance;
}
public static void setup() {
getInstance().reloadConfig();
// Configuration setup
final File file = Path.of(getInstance().getDataFolder().getPath(), "config.yml").toFile();
final YamlConfigurationLoader loader = YamlConfigurationLoader.
builder().
path(file.toPath()).
defaultOptions(opts ->
opts.serializers(build -> {
build.register(Location.class, LocationSerializer.INSTANCE);
build.register(ItemStack.class, ItemSerializer.INSTANCE);
}))
.build();
try {
Settings.load(loader.load());
WardrobeSettings.load(loader.load().node("wardrobe"));
DatabaseSettings.load(loader.load().node("database-settings"));
} catch (ConfigurateException e) {
throw new RuntimeException(e);
}
// Translation setup
Translation.setup();
// Cosmetics setup
Cosmetics.setup();
// Menus setup
Menus.setup();
// ItemHooks
ItemHooks.setup();
}
}

View File

@@ -0,0 +1,119 @@
package com.hibiscusmc.hmccosmetics.command;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetic;
import com.hibiscusmc.hmccosmetics.cosmetic.CosmeticSlot;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetics;
import com.hibiscusmc.hmccosmetics.database.Database;
import com.hibiscusmc.hmccosmetics.gui.Menu;
import com.hibiscusmc.hmccosmetics.gui.Menus;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import com.hibiscusmc.hmccosmetics.user.CosmeticUsers;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class CosmeticCommand implements CommandExecutor {
// cosmetics apply cosmetics playerName
// 0 1 2
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (args.length == 0) {
// Possble default menu here?
return true;
}
if (args[0].equalsIgnoreCase("reload")) {
HMCCosmeticsPlugin.setup();
sender.sendMessage("Reloaded.");
return true;
}
if (args[0].equalsIgnoreCase("apply")) {
Player player = null;
Cosmetic cosmetic;
if (sender instanceof Player) player = ((Player) sender).getPlayer();
if (args.length >= 3) player = Bukkit.getPlayer(args[2]);
cosmetic = Cosmetics.getCosmetic(args[1]);
if (player == null || cosmetic == null) {
sender.sendMessage("Something was null");
return true;
}
CosmeticUser user = CosmeticUsers.getUser(player);
user.addPlayerCosmetic(cosmetic);
user.updateCosmetic(cosmetic.getSlot());
return true;
}
if (args[0].equalsIgnoreCase("unapply")) {
Player player = null;
Cosmetic cosmetic;
if (sender instanceof Player) player = ((Player) sender).getPlayer();
if (args.length >= 3) player = Bukkit.getPlayer(args[2]);
cosmetic = Cosmetics.getCosmetic(args[1]);
if (player == null || cosmetic == null) {
sender.sendMessage("Something was null");
return true;
}
CosmeticUser user = CosmeticUsers.getUser(player);
CosmeticSlot slot = cosmetic.getSlot();
user.removeCosmeticSlot(cosmetic);
user.updateCosmetic(slot);
return true;
}
if (args[0].equalsIgnoreCase("wardrobe")) {
Player player = null;
if (sender instanceof Player) player = ((Player) sender).getPlayer();
if (args.length >= 3) player = Bukkit.getPlayer(args[2]);
if (player == null) {
sender.sendMessage("Player was null");
return true;
}
CosmeticUser user = CosmeticUsers.getUser(player);
user.toggleWardrobe();
return true;
}
// cosmetic menu exampleMenu playerName
if (args[0].equalsIgnoreCase("menu")) {
if (args.length == 1) return true;
Menu menu = Menus.getMenu(args[1]);
Player player = null;
if (sender instanceof Player) player = ((Player) sender).getPlayer();
if (args.length >= 3) player = Bukkit.getPlayer(args[2]);
if (player == null || menu == null) {
sender.sendMessage("Something was null");
return true;
}
menu.openMenu(CosmeticUsers.getUser(player));
return true;
}
if (args[0].equalsIgnoreCase("dataclear")) {
if (args.length == 1) return true;
Player player = Bukkit.getPlayer(args[1]);
if (player == null) return true;
Database.clearData(player.getUniqueId());
sender.sendMessage("Cleared data for " + player.getName());
}
return true;
}
}

View File

@@ -0,0 +1,63 @@
package com.hibiscusmc.hmccosmetics.command;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetics;
import com.hibiscusmc.hmccosmetics.gui.Menus;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CosmeticCommandTabComplete implements TabCompleter {
@Nullable
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) {
List<String> completions = new ArrayList<>();
if (args.length == 1) {
completions.add("apply");
completions.add("wardrobe");
completions.add("unapply");
completions.add("menu");
completions.add("reload");
completions.add("dataclear");
}
if (args.length >= 2) {
if (args[0].equalsIgnoreCase("apply") || args[0].equalsIgnoreCase("unapply")) {
completions.addAll(applyCommandComplete(args));
} else if (args[0].equalsIgnoreCase("menu")) {
completions.addAll(Menus.getMenuNames());
} else if (args[0].equalsIgnoreCase("dataclear")) {
for (Player player : Bukkit.getOnlinePlayers()) {
completions.add(player.getName());
}
}
}
Collections.sort(completions);
return completions;
}
private static List<String> applyCommandComplete(String[] args) {
List<String> completitions = new ArrayList<>();
if (args.length == 2) {
completitions.addAll(Cosmetics.keys());
} else {
if (args.length == 3) {
for (Player player : Bukkit.getOnlinePlayers()) {
completitions.add(player.getName());
}
}
}
return completitions;
}
}

View File

@@ -0,0 +1,61 @@
package com.hibiscusmc.hmccosmetics.config;
import org.spongepowered.configurate.ConfigurationNode;
public class DatabaseSettings {
//private static final String DATABASE_SETTINGS_PATH = "cosmetic-settings";
private static final String DATABASE_TYPE_PATH = "type";
private static final String MYSQL_DATABASE_SETTINGS = "mysql";
private static final String MYSQL_DATABASE = "database";
private static final String MYSQL_PASSWORD = "password";
private static final String MYSQL_HOST = "host";
private static final String MYSQL_USER = "user";
private static final String MYSQL_PORT = "port";
private static String databaseType;
private static String database;
private static String password;
private static String host;
private static String username;
private static int port;
public static void load(ConfigurationNode source) {
//ConfigurationNode databaseSettings = source.node(DATABASE_SETTINGS_PATH);
databaseType = source.node(DATABASE_TYPE_PATH).getString();
ConfigurationNode mySql = source.node(MYSQL_DATABASE_SETTINGS);
database = mySql.node(MYSQL_DATABASE).getString();
password = mySql.node(MYSQL_PASSWORD).getString();
host = mySql.node(MYSQL_HOST).getString();
username = mySql.node(MYSQL_USER).getString();
port = mySql.node(MYSQL_PORT).getInt();
}
public static String getDatabaseType() {
return databaseType;
}
public static String getDatabase() {
return database;
}
public static String getPassword() {
return password;
}
public static String getHost() {
return host;
}
public static String getUsername() {
return username;
}
public static int getPort() {
return port;
}
}

View File

@@ -0,0 +1,111 @@
package com.hibiscusmc.hmccosmetics.config;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import org.bukkit.util.Vector;
import org.spongepowered.configurate.ConfigurationNode;
public class Settings {
// General Settings
private static final String DEFAULT_MENU = "default-menu";
private static final String CONFIG_VERSION = "config-version";
private static final String COSMETIC_SETTINGS_PATH = "cosmetic-settings";
private static final String REQUIRE_EMPTY_HELMET_PATH = "require-empty-helmet";
private static final String REQUIRE_EMPTY_OFF_HAND_PATH = "require-empty-off-hand";
private static final String REQUIRE_EMPTY_CHEST_PLATE_PATH = "require-empty-chest-plate";
private static final String REQUIRE_EMPTY_PANTS_PATH = "require-empty-pants";
private static final String REQUIRE_EMPTY_BOOTS_PATH = "require-empty-boots";
private static final String BALLOON_OFFSET = "balloon-offset";
private static final String FIRST_PERSON_BACKPACK_MODE = "first-person-backpack-mode";
private static final transient String LOOK_DOWN_PITCH_PATH = "look-down-backpack-remove";
private static final String VIEW_DISTANCE_PATH = "view-distance";
private static final String PARTICLE_COUNT = "particle-count";
private static String defaultMenu;
private static int configVersion;
private static boolean requireEmptyHelmet;
private static boolean requireEmptyOffHand;
private static boolean requireEmptyChestPlate;
private static boolean requireEmptyPants;
private static boolean requireEmptyBoots;
private static int lookDownPitch;
private static int viewDistance;
private static Vector balloonOffset;
public static void load(ConfigurationNode source) {
defaultMenu = source.node(DEFAULT_MENU).getString();
configVersion = source.node(CONFIG_VERSION).getInt(0);
if (configVersion == 0) {
HMCCosmeticsPlugin plugin = HMCCosmeticsPlugin.getInstance();
plugin.getLogger().severe("");
plugin.getLogger().severe("");
plugin.getLogger().severe("Improper Configuration Found (Config Version Does Not Exist!)");
plugin.getLogger().severe("Problems will happen with the plugin! Delete and regenerate a new one!");
plugin.getLogger().severe("");
plugin.getLogger().severe("");
}
ConfigurationNode cosmeticSettings = source.node(COSMETIC_SETTINGS_PATH);
requireEmptyHelmet = cosmeticSettings.node(REQUIRE_EMPTY_HELMET_PATH).getBoolean();
requireEmptyOffHand = cosmeticSettings.node(REQUIRE_EMPTY_OFF_HAND_PATH).getBoolean();
requireEmptyChestPlate = cosmeticSettings.node(REQUIRE_EMPTY_CHEST_PLATE_PATH).getBoolean();
requireEmptyPants = cosmeticSettings.node(REQUIRE_EMPTY_PANTS_PATH).getBoolean();
requireEmptyBoots = cosmeticSettings.node(REQUIRE_EMPTY_BOOTS_PATH).getBoolean();
lookDownPitch = cosmeticSettings.node(LOOK_DOWN_PITCH_PATH).getInt();
viewDistance = cosmeticSettings.node(VIEW_DISTANCE_PATH).getInt();
final var balloonSection = cosmeticSettings.node(BALLOON_OFFSET);
balloonOffset = loadVector(balloonSection);
}
private static Vector loadVector(final ConfigurationNode config) {
return new Vector(config.node("x").getDouble(), config.node("y").getDouble(), config.node("z").getDouble());
}
public static boolean isRequireEmptyHelmet() {
return requireEmptyHelmet;
}
public static boolean isRequireEmptyOffHand() {
return requireEmptyOffHand;
}
public static boolean isRequireEmptyChestPlate() {
return requireEmptyChestPlate;
}
public static boolean isRequireEmptyPants() {
return requireEmptyPants;
}
public static boolean isRequireEmptyBoots() {
return requireEmptyBoots;
}
public static Vector getBalloonOffset() {
if (balloonOffset == null) HMCCosmeticsPlugin.getInstance().getLogger().info("Shits null");
return balloonOffset;
}
public static int getLookDownPitch() {
return lookDownPitch;
}
public static int getViewDistance() {
return viewDistance;
}
public static String getDefaultMenu() {
return defaultMenu;
}
public static int getConfigVersion() {
return configVersion;
}
}

View File

@@ -0,0 +1,136 @@
package com.hibiscusmc.hmccosmetics.config;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.config.serializer.LocationSerializer;
import com.hibiscusmc.hmccosmetics.util.misc.Utils;
import org.bukkit.Location;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
public class WardrobeSettings {
private static final String WARDROBE_PATH = "wardrobe";
private static final String DISABLE_ON_DAMAGE_PATH = "disable-on-damage";
private static final String DISPLAY_RADIUS_PATH = "display-radius";
private static final String PORTABLE_PATH = "portable";
private static final String ALWAYS_DISPLAY_PATH = "always-display";
private static final String STATIC_RADIUS_PATH = "static-radius";
private static final String ROTATION_SPEED_PATH = "rotation-speed";
private static final String SPAWN_DELAY_PATH = "spawn-delay";
private static final String DESPAWN_DELAY_PATH = "despawn-delay";
private static final String APPLY_COSMETICS_ON_CLOSE = "apply-cosmetics-on-close";
private static final String OPEN_SOUND = "open-sound";
private static final String CLOSE_SOUND = "close-sound";
private static final String STATIC_LOCATION_PATH = "wardrobe-location";
private static final String VIEWER_LOCATION_PATH = "viewer-location";
private static final String LEAVE_LOCATION_PATH = "leave-location";
private static final String EQUIP_PUMPKIN_WARDROBE = "equip-pumpkin";
private static final String RETURN_LAST_LOCATION = "return-last-location";
private static boolean disableOnDamage;
private static int displayRadius;
private static boolean portable;
private static boolean alwaysDisplay;
private static int staticRadius;
private static int rotationSpeed;
private static int spawnDelay;
private static int despawnDelay;
private static boolean applyCosmeticsOnClose;
private static boolean equipPumpkin;
private static boolean returnLastLocation;
private static Location wardrobeLocation;
private static Location viewerLocation;
private static Location leaveLocation;
public static void load(ConfigurationNode source) {
disableOnDamage = source.node(DISABLE_ON_DAMAGE_PATH).getBoolean();
displayRadius = source.node(DISPLAY_RADIUS_PATH).getInt();
portable = source.node(PORTABLE_PATH).getBoolean();
staticRadius = source.node(STATIC_RADIUS_PATH).getInt();
alwaysDisplay = source.node(ALWAYS_DISPLAY_PATH).getBoolean();
rotationSpeed = source.node(ROTATION_SPEED_PATH).getInt();
spawnDelay = source.node(SPAWN_DELAY_PATH).getInt();
despawnDelay = source.node(DESPAWN_DELAY_PATH).getInt();
applyCosmeticsOnClose = source.node(APPLY_COSMETICS_ON_CLOSE).getBoolean();
equipPumpkin = source.node(EQUIP_PUMPKIN_WARDROBE).getBoolean();
returnLastLocation = source.node(RETURN_LAST_LOCATION).getBoolean();
try {
wardrobeLocation = LocationSerializer.INSTANCE.deserialize(Location.class, source.node(STATIC_LOCATION_PATH));
HMCCosmeticsPlugin.getInstance().getLogger().info("Wardrobe Location: " + wardrobeLocation);
viewerLocation = LocationSerializer.INSTANCE.deserialize(Location.class, source.node(VIEWER_LOCATION_PATH));
HMCCosmeticsPlugin.getInstance().getLogger().info("Viewer Location: " + viewerLocation);
leaveLocation = Utils.replaceIfNull(LocationSerializer.INSTANCE.deserialize(Location.class, source.node(LEAVE_LOCATION_PATH)), viewerLocation);
} catch (SerializationException e) {
throw new RuntimeException(e);
}
}
public static boolean getDisableOnDamage() {
return disableOnDamage;
}
public static int getDisplayRadius() {
return displayRadius;
}
public static boolean isPortable() {
return portable;
}
public static boolean isAlwaysDisplay() {
return alwaysDisplay;
}
public static int getStaticRadius() {
return staticRadius;
}
public static int getRotationSpeed() {
return rotationSpeed;
}
public static int getSpawnDelay() {
return spawnDelay;
}
public static int getDespawnDelay() {
return despawnDelay;
}
public static boolean isApplyCosmeticsOnClose() {
return applyCosmeticsOnClose;
}
public static boolean isEquipPumpkin() {
return equipPumpkin;
}
public static boolean isReturnLastLocation() {
return returnLastLocation;
}
public static Location getWardrobeLocation() {
return wardrobeLocation.clone();
}
public static Location getViewerLocation() {
return viewerLocation;
}
public static Location getLeaveLocation() {
return leaveLocation;
}
public static boolean inDistanceOfWardrobe(final Location wardrobeLocation, final Location playerLocation) {
if (displayRadius == -1) return true;
if (!wardrobeLocation.getWorld().equals(playerLocation.getWorld())) return false;
return playerLocation.distanceSquared(wardrobeLocation) <= displayRadius * displayRadius;
}
public static boolean inDistanceOfStatic(final Location location) {
if (wardrobeLocation == null) return false;
if (staticRadius == -1) return false;
if (!wardrobeLocation.getWorld().equals(location.getWorld())) return false;
return wardrobeLocation.distanceSquared(location) <= staticRadius * staticRadius;
}
}

View File

@@ -0,0 +1,136 @@
package com.hibiscusmc.hmccosmetics.config.serializer;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.hooks.items.ItemHooks;
import com.hibiscusmc.hmccosmetics.util.builder.ColorBuilder;
import com.hibiscusmc.hmccosmetics.util.misc.StringUtils;
import com.hibiscusmc.hmccosmetics.util.misc.Utils;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.persistence.PersistentDataType;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class ItemSerializer implements TypeSerializer<ItemStack> {
public static final ItemSerializer INSTANCE = new ItemSerializer();
private static final String MATERIAL = "material";
private static final String AMOUNT = "amount";
private static final String NAME = "name";
private static final String UNBREAKABLE = "unbreakable";
private static final String GLOWING = "glowing";
private static final String LORE = "lore";
private static final String MODEL_DATA = "model-data";
private static final String ENCHANTS = "enchants";
private static final String ITEM_FLAGS = "item-flags";
private static final String TEXTURE = "texture";
private static final String OWNER = "owner";
private static final String COLOR = "color";
private static final String RED = "red";
private static final String GREEN = "green";
private static final String BLUE = "blue";
private ItemSerializer() {
}
@Override
public ItemStack deserialize(final Type type, final ConfigurationNode source)
throws SerializationException {
final ConfigurationNode materialNode = source.node(MATERIAL);
final ConfigurationNode amountNode = source.node(AMOUNT);
final ConfigurationNode nameNode = source.node(NAME);
final ConfigurationNode unbreakableNode = source.node(UNBREAKABLE);
final ConfigurationNode glowingNode = source.node(GLOWING);
final ConfigurationNode loreNode = source.node(LORE);
final ConfigurationNode modelDataNode = source.node(MODEL_DATA);
final ConfigurationNode enchantsNode = source.node(ENCHANTS);
final ConfigurationNode itemFlagsNode = source.node(ITEM_FLAGS);
final ConfigurationNode textureNode = source.node(TEXTURE);
final ConfigurationNode ownerNode = source.node(OWNER);
final ConfigurationNode colorNode = source.node(COLOR);
final ConfigurationNode redNode = colorNode.node(RED);
final ConfigurationNode greenNode = colorNode.node(GREEN);
final ConfigurationNode blueNode = colorNode.node(BLUE);
if (materialNode.virtual()) return null;
String material = materialNode.getString();
ItemStack item = ItemHooks.getItem(material);
if (item == null) {
HMCCosmeticsPlugin.getInstance().getLogger().severe("Invalid Material -> " + material);
return new ItemStack(Material.AIR);
}
item.setAmount(amountNode.getInt(1));
ItemMeta itemMeta = item.getItemMeta();
if (!nameNode.virtual()) itemMeta.setDisplayName(StringUtils.parseStringToString(Utils.replaceIfNull(nameNode.getString(), "")));
if (!unbreakableNode.virtual()) itemMeta.setUnbreakable(unbreakableNode.getBoolean());
if (!glowingNode.virtual()) {
itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
itemMeta.addEnchant(Enchantment.LUCK, 1, true);
}
if (!loreNode.virtual()) itemMeta.setLore(Utils.replaceIfNull(loreNode.getList(String.class),
new ArrayList<String>()).
stream().map(StringUtils::parseStringToString).collect(Collectors.toList()));
if (!modelDataNode.virtual()) itemMeta.setCustomModelData(modelDataNode.getInt());
if (!enchantsNode.virtual()) {
for (ConfigurationNode enchantNode : enchantsNode.childrenMap().values()) {
if (Enchantment.getByKey(NamespacedKey.minecraft(enchantNode.key().toString())) == null) continue;
itemMeta.addEnchant(Enchantment.getByKey(NamespacedKey.minecraft(enchantNode.key().toString())), enchantNode.getInt(1), true);
}
}
if (!itemFlagsNode.virtual()) {
for (ConfigurationNode flagNode : itemFlagsNode.childrenMap().values()) {
if (ItemFlag.valueOf(flagNode.key().toString()) == null) continue;
itemMeta.addItemFlags(ItemFlag.valueOf(flagNode.key().toString()));
}
}
if (item.getType() == Material.PLAYER_HEAD) {
SkullMeta skullMeta = (SkullMeta) itemMeta;
if (!ownerNode.virtual()) {
skullMeta.setOwningPlayer(Bukkit.getOfflinePlayer(ownerNode.getString()));
}
if (!textureNode.virtual()) {
Bukkit.getUnsafe().modifyItemStack(item, "{SkullOwner:{Id:[I;0,0,0,0],Properties:{textures:[{Value:\""
+ textureNode.getString() + "\"}]}}}");
itemMeta = skullMeta;
}
}
if (!colorNode.virtual()) {
if (ColorBuilder.canBeColored(item.getType())) {
itemMeta = ColorBuilder.color(itemMeta, Color.fromRGB(redNode.getInt(0), greenNode.getInt(0), blueNode.getInt(0)));
}
}
NamespacedKey key = new NamespacedKey(HMCCosmeticsPlugin.getInstance(), source.key().toString());
itemMeta.getPersistentDataContainer().set(key, PersistentDataType.STRING, source.key().toString());
item.setItemMeta(itemMeta);
return item;
}
@Override
public void serialize(final Type type, @Nullable final ItemStack obj, final ConfigurationNode node) throws SerializationException {
}
}

View File

@@ -0,0 +1,46 @@
package com.hibiscusmc.hmccosmetics.config.serializer;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;
import java.lang.reflect.Type;
public class LocationSerializer implements TypeSerializer<Location> {
public static final LocationSerializer INSTANCE = new LocationSerializer();
private static final String WORLD = "world";
private static final String X = "x";
private static final String Y = "y";
private static final String Z = "z";
private static final String PITCH = "pitch";
private static final String YAW = "yaw";
private LocationSerializer() {}
@Override
@Nullable
public Location deserialize(final Type type, final ConfigurationNode source) throws SerializationException {
final World world = Bukkit.getWorld(source.node(WORLD).getString());
if (world == null) return null;
return new Location(
world,
source.node(X).getDouble(),
source.node(Y).getDouble(),
source.node(Z).getDouble(),
source.node(YAW).getFloat(),
source.node(PITCH).getFloat()
);
}
@Override
public void serialize(final Type type, @Nullable final Location obj, final ConfigurationNode node) throws SerializationException {
}
}

View File

@@ -0,0 +1,64 @@
package com.hibiscusmc.hmccosmetics.cosmetic;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import org.spongepowered.configurate.ConfigurationNode;
public class Cosmetic {
private String id;
private String permission;
private CosmeticSlot slot;
private boolean equipable; // This simply means if a player can put it on their body.
protected Cosmetic(String id, ConfigurationNode config) {
this.id = id;
//this.permission = config.node("permission").getString(null);
HMCCosmeticsPlugin.getInstance().getLogger().info("Slot: " + config.node("slot").getString());
setSlot(CosmeticSlot.valueOf(config.node("slot").getString()));
setEquipable(false);
Cosmetics.addCosmetic(this);
}
public String getId() {
return this.id;
}
public String getPermission() {
return this.permission;
}
public CosmeticSlot getSlot() {
return this.slot;
}
public void setSlot(CosmeticSlot slot) {
this.slot = slot;
}
public void setPermission(String permission) {
this.permission = permission;
}
public boolean requiresPermission() {
if (permission == null) return false;
return true;
}
public void setId(String id) {
this.id = id;
}
public void setEquipable(boolean equipable) {
this.equipable = equipable;
}
public boolean isEquipable() {
return equipable;
}
public void update(CosmeticUser user) {
// Override
}
}

View File

@@ -0,0 +1,11 @@
package com.hibiscusmc.hmccosmetics.cosmetic;
public enum CosmeticSlot {
HELMET,
CHESTPLATE,
LEGGINGS,
BOOTS,
OFFHAND,
BACKPACK,
BALLOON
}

View File

@@ -0,0 +1,95 @@
package com.hibiscusmc.hmccosmetics.cosmetic;
import com.google.common.collect.HashBiMap;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.cosmetic.types.CosmeticArmorType;
import com.hibiscusmc.hmccosmetics.cosmetic.types.CosmeticBackpackType;
import com.hibiscusmc.hmccosmetics.cosmetic.types.CosmeticBalloonType;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.ConfigurateException;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import java.io.File;
import java.util.Set;
public class Cosmetics {
private static HashBiMap<String, Cosmetic> COSMETICS = HashBiMap.create();
public static void addCosmetic(Cosmetic cosmetic) {
COSMETICS.put(cosmetic.getId(), cosmetic);
}
public static void removeCosmetic(String id) {
COSMETICS.remove(id);
}
public static void removeCosmetic(Cosmetic cosmetic) {
COSMETICS.remove(cosmetic);
}
public static Cosmetic getCosmetic(String id) {
return COSMETICS.get(id);
}
public static Set<Cosmetic> values() {
return COSMETICS.values();
}
public static Set<String> keys() {
return COSMETICS.keySet();
}
public static boolean hasCosmetic(String id) {
return COSMETICS.containsKey(id);
}
public static boolean hasCosmetic(Cosmetic cosmetic) {
return COSMETICS.containsValue(cosmetic);
}
public static void setup() {
COSMETICS.clear();
File cosmeticFolder = new File(HMCCosmeticsPlugin.getInstance().getDataFolder() + "/cosmetics");
if (!cosmeticFolder.exists()) cosmeticFolder.mkdir();
File[] directoryListing = cosmeticFolder.listFiles();
if (directoryListing == null) return;
for (File child : directoryListing) {
if (child.toString().contains(".yml") || child.toString().contains(".yaml")) {
HMCCosmeticsPlugin.getInstance().getLogger().info("Scanning " + child);
// Loads file
YamlConfigurationLoader loader = YamlConfigurationLoader.builder().path(child.toPath()).build();
CommentedConfigurationNode root;
try {
root = loader.load();
} catch (ConfigurateException e) {
throw new RuntimeException(e);
}
setupCosmetics(root);
}
}
}
private static void setupCosmetics(CommentedConfigurationNode config) {
for (ConfigurationNode cosmeticConfig : config.childrenMap().values()) {
String id = cosmeticConfig.key().toString();
HMCCosmeticsPlugin.getInstance().getLogger().info("Attempting to add " + id);
switch (CosmeticSlot.valueOf(cosmeticConfig.node("slot").getString())) {
case BALLOON -> {
new CosmeticBalloonType(id, cosmeticConfig);
}
case BACKPACK -> {
new CosmeticBackpackType(id, cosmeticConfig);
}
default -> {
new CosmeticArmorType(id, cosmeticConfig);
}
}
//new Cosmetic(id, cosmeticConfig);
}
}
}

View File

@@ -0,0 +1,59 @@
package com.hibiscusmc.hmccosmetics.cosmetic.types;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.config.serializer.ItemSerializer;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetic;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import com.hibiscusmc.hmccosmetics.util.InventoryUtils;
import com.hibiscusmc.hmccosmetics.util.PlayerUtils;
import com.hibiscusmc.hmccosmetics.util.packets.PacketManager;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
public class CosmeticArmorType extends Cosmetic {
private ItemStack itemStack;
private EquipmentSlot equipSlot;
public CosmeticArmorType(String id, ConfigurationNode config) {
super(id, config);
this.itemStack = generateItemStack(config.node("item"));
this.equipSlot = InventoryUtils.getEquipmentSlot(getSlot());
setEquipable(true);
}
@Override
public void update(CosmeticUser user) {
Player player = Bukkit.getPlayer(user.getUniqueId());
PacketManager.equipmentSlotUpdate(player, getSlot(), PlayerUtils.getNearbyPlayers(player));
}
public ItemStack getCosmeticItem() {
return this.itemStack;
}
public EquipmentSlot getEquipSlot() {
return this.equipSlot;
}
private ItemStack generateItemStack(ConfigurationNode config) {
try {
ItemStack item = ItemSerializer.INSTANCE.deserialize(ItemStack.class, config);
if (item == null) {
HMCCosmeticsPlugin.getInstance().getLogger().severe("Unable to create item for " + getId());
return new ItemStack(Material.AIR);
}
return item;
} catch (SerializationException e) {
HMCCosmeticsPlugin.getInstance().getLogger().severe("Fatal error encountered for " + getId() + " regarding Serialization of item");
throw new RuntimeException(e);
}
}
}

View File

@@ -0,0 +1,72 @@
package com.hibiscusmc.hmccosmetics.cosmetic.types;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.config.serializer.ItemSerializer;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetic;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import com.hibiscusmc.hmccosmetics.util.packets.PacketManager;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
public class CosmeticBackpackType extends Cosmetic {
private ItemStack backpackItem;
public CosmeticBackpackType(String id, ConfigurationNode config) {
super(id, config);
this.backpackItem = generateItemStack(config.node("item"));
}
@Override
public void update(CosmeticUser user) {
Player player = Bukkit.getPlayer(user.getUniqueId());
Location loc = player.getLocation().clone();
if (loc.getBlock().getType().equals(Material.NETHER_PORTAL)) {
user.hideBackpack();
return;
}
if (loc.getWorld() != user.getBackpackEntity().getBukkitLivingEntity().getWorld()) {
user.getBackpackEntity().getBukkitLivingEntity().teleport(loc);
}
user.getBackpackEntity().moveTo(loc.getX(), loc.getY(), loc.getZ());
if (player.getPassengers().isEmpty()) {
//HMCCosmeticsPlugin.getInstance().getLogger().info("No passengers");
user.getBackpackEntity().getBukkitLivingEntity().teleport(loc);
player.addPassenger(user.getBackpackEntity().getBukkitEntity());
} else {
//HMCCosmeticsPlugin.getInstance().getLogger().info("Passengers: " + player.getPassengers());
}
user.getBackpackEntity().getBukkitLivingEntity().setRotation(loc.getYaw(), loc.getPitch());
user.showBackpack();
}
public ItemStack getBackpackItem() {
return backpackItem;
}
private ItemStack generateItemStack(ConfigurationNode config) {
try {
ItemStack item = ItemSerializer.INSTANCE.deserialize(ItemStack.class, config);
if (item == null) {
HMCCosmeticsPlugin.getInstance().getLogger().severe("Unable to create item for " + getId());
return new ItemStack(Material.AIR);
}
return item;
} catch (SerializationException e) {
HMCCosmeticsPlugin.getInstance().getLogger().severe("Fatal error encountered for " + getId() + " regarding Serialization of item");
throw new RuntimeException(e);
}
}
}

View File

@@ -0,0 +1,50 @@
package com.hibiscusmc.hmccosmetics.cosmetic.types;
import com.hibiscusmc.hmccosmetics.config.Settings;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetic;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import com.hibiscusmc.hmccosmetics.util.PlayerUtils;
import com.hibiscusmc.hmccosmetics.util.packets.PacketManager;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.spongepowered.configurate.ConfigurationNode;
import java.util.List;
public class CosmeticBalloonType extends Cosmetic {
private String modelName;
public CosmeticBalloonType(String id, ConfigurationNode config) {
super(id, config);
String modelId = config.node("model").getString();
this.modelName = modelId;
}
@Override
public void update(CosmeticUser user) {
Player player = Bukkit.getPlayer(user.getUniqueId());
if (user.isInWardrobe()) return;
final Location actual = player.getLocation().clone().add(Settings.getBalloonOffset());
if (player.getLocation().getWorld() != user.getBalloonEntity().getLocation().getWorld()) {
user.getBalloonEntity().getModelEntity().getBukkitLivingEntity().teleport(actual);
}
user.getBalloonEntity().getModelEntity().moveTo(actual.getX(), actual.getY(), actual.getZ());
List<Player> viewer = PlayerUtils.getNearbyPlayers(player);
viewer.add(player);
PacketManager.sendTeleportPacket(user.getBalloonEntity().getPufferfishBalloonId(), actual, false, viewer);
PacketManager.sendLeashPacket(user.getBalloonEntity().getPufferfishBalloonId(), player.getEntityId(), viewer);
}
public String getModelName() {
return this.modelName;
}
}

View File

@@ -0,0 +1,60 @@
package com.hibiscusmc.hmccosmetics.database;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.config.DatabaseSettings;
import com.hibiscusmc.hmccosmetics.database.types.Data;
import com.hibiscusmc.hmccosmetics.database.types.InternalData;
import com.hibiscusmc.hmccosmetics.database.types.MySQLData;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import com.hibiscusmc.hmccosmetics.user.CosmeticUsers;
import org.bukkit.entity.Player;
import java.util.UUID;
public class Database {
private static Data data;
private static InternalData INTERNAL_DATA = new InternalData();
private static MySQLData MYSQL_DATA = new MySQLData();
public Database() {
String databaseType = DatabaseSettings.getDatabaseType();
data = INTERNAL_DATA; // default
if (databaseType.equalsIgnoreCase("INTERNAL")) {
data = INTERNAL_DATA;
HMCCosmeticsPlugin.getInstance().getLogger().severe("Datatype set to internal data");
}
if (databaseType.equalsIgnoreCase("MySQL")) {
data = MYSQL_DATA;
HMCCosmeticsPlugin.getInstance().getLogger().severe("Datatype set to MySQL data");
}
HMCCosmeticsPlugin.getInstance().getLogger().severe("Database is " + data);
setup();
}
public static void setup() {
data.setup();
}
public static void save(CosmeticUser user) {
data.save(user);
}
public static void save(Player player) {
data.save(CosmeticUsers.getUser(player));
}
public static CosmeticUser get(UUID uniqueId) {
return data.get(uniqueId);
}
public static Data getData() {
return data;
}
public static void clearData(UUID uniqueId) {
data.clear(uniqueId);
}
}

View File

@@ -0,0 +1,58 @@
package com.hibiscusmc.hmccosmetics.database.types;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetic;
import com.hibiscusmc.hmccosmetics.cosmetic.CosmeticSlot;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetics;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class Data {
public void setup() {
// Override
}
public void save(CosmeticUser user) {
// Override
}
@Nullable
public CosmeticUser get(UUID uniqueId) {
// Override
return null;
}
public void clear(UUID uniqueId) {
// Override
}
public String steralizeData(CosmeticUser user) {
String data = "";
for (Cosmetic cosmetic : user.getCosmetic()) {
String input = cosmetic.getSlot() + "=" + cosmetic.getId();
data = data + "," + input;
}
return data;
}
public Map<CosmeticSlot, Cosmetic> desteralizedata(String raw) {
Map<CosmeticSlot, Cosmetic> cosmetics = new HashMap<>();
String[] rawData = raw.split(",");
for (String a : rawData) {
if (a == null || a.isEmpty()) continue;
String[] splitData = a.split("=");
CosmeticSlot slot = null;
Cosmetic cosmetic = null;
if (CosmeticSlot.valueOf(splitData[0]) != null) slot = CosmeticSlot.valueOf(splitData[0]);
if (Cosmetics.hasCosmetic(splitData[1])) cosmetic = Cosmetics.getCosmetic(splitData[1]);
if (slot == null || cosmetic == null) continue;
cosmetics.put(slot, cosmetic);
}
return cosmetics;
}
}

View File

@@ -0,0 +1,56 @@
package com.hibiscusmc.hmccosmetics.database.types;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetic;
import com.hibiscusmc.hmccosmetics.cosmetic.CosmeticSlot;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetics;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Player;
import org.bukkit.persistence.PersistentDataType;
import java.util.Map;
import java.util.UUID;
public class InternalData extends Data {
NamespacedKey key = new NamespacedKey(HMCCosmeticsPlugin.getInstance(), "cosmetics");
@Override
public void setup() {
// Nothing
}
@Override
public void save(CosmeticUser user) {
Player player = Bukkit.getPlayer(user.getUniqueId());
player.getPersistentDataContainer().set(key, PersistentDataType.STRING, steralizeData(user));
}
@Override
public CosmeticUser get(UUID uniqueId) {
Player player = Bukkit.getPlayer(uniqueId);
CosmeticUser user = new CosmeticUser(uniqueId);
if (!player.getPersistentDataContainer().has(key, PersistentDataType.STRING)) return user;
String rawData = player.getPersistentDataContainer().get(key, PersistentDataType.STRING);
Map<CosmeticSlot, Cosmetic> a = desteralizedata(rawData);
for (CosmeticSlot slot : a.keySet()) {
user.addPlayerCosmetic(a.get(slot));
//HMCCosmeticsPlugin.getInstance().getLogger().info("Retrieved " + player.getName() + " | slot " + slot + " | cosmetic " + Cosmetics.getCosmetic(player.getPersistentDataContainer().get(key, PersistentDataType.STRING)));
}
return user;
}
@Override
public void clear(UUID uniqueId) {
Player player = Bukkit.getPlayer(uniqueId);
if (player.getPersistentDataContainer().has(key, PersistentDataType.STRING)) {
player.getPersistentDataContainer().remove(key);
}
}
}

View File

@@ -0,0 +1,166 @@
package com.hibiscusmc.hmccosmetics.database.types;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.config.DatabaseSettings;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetic;
import com.hibiscusmc.hmccosmetics.cosmetic.CosmeticSlot;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import org.bukkit.Bukkit;
import java.sql.*;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
public class MySQLData extends Data {
// Connection Information
private String host;
private String user;
private String database;
private String password;
private int port;
private Connection connection;
@Override
public void setup() {
host = DatabaseSettings.getHost();
user = DatabaseSettings.getUsername();
database = DatabaseSettings.getDatabase();
password = DatabaseSettings.getPassword();
port = DatabaseSettings.getPort();
HMCCosmeticsPlugin plugin = HMCCosmeticsPlugin.getInstance();
try {
openConnection();
connection.prepareStatement("CREATE TABLE IF NOT EXISTS `COSMETICDATABASE` " +
"(UUID varchar(200) PRIMARY KEY, " +
"COSMETICS MEDIUMTEXT " +
");");
} catch (SQLException e) {
plugin.getLogger().severe("");
plugin.getLogger().severe("");
plugin.getLogger().severe("MySQL DATABASE CAN NOT BE REACHED.");
plugin.getLogger().severe("CHECK CONFIG FOR ERRORS");
plugin.getLogger().severe("");
plugin.getLogger().severe("SAFETY SHUTTING DOWN SERVER");
plugin.getLogger().severe("");
plugin.getLogger().severe("");
Bukkit.shutdown();
throw new RuntimeException(e);
}
}
@Override
public void save(CosmeticUser user) {
Bukkit.getScheduler().runTaskAsynchronously(HMCCosmeticsPlugin.getInstance(), () -> {
try {
PreparedStatement preparedSt = preparedStatement("REPLACE INTO COSMETICDATABASE(UUID,COSMETICS) VALUES(?,?);");
preparedSt.setString(1, user.getUniqueId().toString());
preparedSt.setString(2, steralizeData(user));
preparedSt.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}
});
}
@Override
public CosmeticUser get(UUID uniqueId) {
CosmeticUser user = new CosmeticUser(uniqueId);
Bukkit.getScheduler().runTaskAsynchronously(HMCCosmeticsPlugin.getInstance(), () -> {
try {
PreparedStatement preparedStatement = preparedStatement("SELECT COUNT(UUID) FROM COSMETICDATABASE WHERE UUID = ?;");
preparedStatement.setString(1, uniqueId.toString());
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
if (rs.getInt(1) == 0) { // Not in the system
// nothing
} else {
PreparedStatement preState2 = preparedStatement("SELECT * FROM COSMETICDATABASE WHERE UUID = ?;");
preState2.setString(1, uniqueId.toString());
ResultSet rs2 = preState2.executeQuery();
if (rs2.next()) {
String rawData = rs.getString("COSMETICS");
Map<CosmeticSlot, Cosmetic> cosmetics = desteralizedata(rawData);
for (Cosmetic cosmetic : cosmetics.values()) {
user.addPlayerCosmetic(cosmetic);
}
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
});
return user;
}
@Override
public void clear(UUID unqiueId) {
// TODO
}
private void openConnection() throws SQLException {
if (connection != null && !connection.isClosed()) {
return;
}
Bukkit.getScheduler().runTaskAsynchronously(HMCCosmeticsPlugin.getInstance(), () -> {
//close Connection if still active
if (connection != null) {
close();
}
//connect to database host
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, setupProperties());
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
});
connection = DriverManager.getConnection("jdbc:mysql://" + DatabaseSettings.getHost() + ":" + DatabaseSettings.getPort() + "/" + DatabaseSettings.getDatabase(), setupProperties());
}
public void close() {
Bukkit.getScheduler().runTaskAsynchronously(HMCCosmeticsPlugin.getInstance(), () -> {
try {
connection.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
});
}
private Properties setupProperties() {
Properties props = new Properties();
props.put("user", user);
props.put("password", password);
props.put("autoReconnect", "true");
return props;
}
private boolean isConnectionOpen() throws SQLException{
if (connection == null || connection.isClosed()) {
return false;
} else {
return true;
}
}
public PreparedStatement preparedStatement(String query) {
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(query);
} catch (SQLException e) {
e.printStackTrace();
}
return ps;
}
}

View File

@@ -0,0 +1,105 @@
package com.hibiscusmc.hmccosmetics.entities;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.config.Settings;
import com.ticxo.modelengine.api.ModelEngineAPI;
import com.ticxo.modelengine.api.model.ActiveModel;
import com.ticxo.modelengine.api.model.ModeledEntity;
import net.minecraft.world.entity.Entity;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import java.util.UUID;
// This includes the Pufferfish (The Pufferfish that's what the player leashes to) and the model (MEGEntity)
public class BalloonEntity {
private final int balloonID;
private final UUID uniqueID;
private final MEGEntity modelEntity;
public BalloonEntity(Location location) {
this.uniqueID = UUID.randomUUID();
this.balloonID = Entity.nextEntityId();
this.modelEntity = new MEGEntity(location.add(Settings.getBalloonOffset()));
}
public void spawnModel(final String id) {
HMCCosmeticsPlugin.getInstance().getLogger().info("Attempting Spawning for " + id);
if (ModelEngineAPI.api.getModelRegistry().getBlueprint(id) == null) {
HMCCosmeticsPlugin.getInstance().getLogger().warning("Invalid Model Engine Blueprint " + id);
return;
}
ModeledEntity modeledEntity = ModelEngineAPI.getOrCreateModeledEntity(modelEntity.getBukkitEntity());
ActiveModel model = ModelEngineAPI.createActiveModel(ModelEngineAPI.getBlueprint(id));
modeledEntity.addModel(model, false);
}
public void remove() {
final ModeledEntity entity = ModelEngineAPI.api.getModeledEntity(modelEntity.getUUID());
if (entity == null) return;
for (final Player player : entity.getRangeManager().getPlayerInRange()) {
entity.hideFromPlayer(player);
}
//ModelEngineAPI.removeModeledEntity(megEntity.getUniqueId());
entity.destroy();
}
public void addPlayerToModel(final Player player, final String id) {
final ModeledEntity model = ModelEngineAPI.api.getModeledEntity(modelEntity.getUUID());
if (model == null) {
spawnModel(id);
return;
}
if (model.getRangeManager().getPlayerInRange().contains(player)) return;
model.showToPlayer(player);
}
public void removePlayerFromModel(final Player player) {
final ModeledEntity model = ModelEngineAPI.api.getModeledEntity(modelEntity.getUUID());
if (model == null) return;
model.hideFromPlayer(player);
}
public MEGEntity getModelEntity() {
return this.modelEntity;
}
public int getPufferfishBalloonId() {
return balloonID;
}
public UUID getPufferfishBalloonUniqueId() {
return uniqueID;
}
public UUID getModelUnqiueId() {
return modelEntity.getUUID();
}
public int getModelId() {
return modelEntity.getId();
}
public Location getLocation() {
return this.modelEntity.getBukkitEntity().getLocation();
}
public boolean isAlive() {
return this.modelEntity.isAlive();
}
public void setLocation(Location location) {
//this.megEntity.teleportTo(location.getX(), location.getY(), location.getZ());
this.modelEntity.getBukkitEntity().teleport(location);
}
public void setVelocity(Vector vector) {
this.modelEntity.getBukkitEntity().setVelocity(vector);
}
}

View File

@@ -0,0 +1,23 @@
package com.hibiscusmc.hmccosmetics.entities;
import net.minecraft.world.entity.decoration.ArmorStand;
import net.minecraft.world.level.Level;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_19_R1.CraftWorld;
public class InvisibleArmorstand extends ArmorStand {
public InvisibleArmorstand(Level world, double x, double y, double z) {
super(world, x, y, z);
}
public InvisibleArmorstand(Location loc) {
super(((CraftWorld) loc.getWorld()).getHandle(), loc.getX(), loc.getY(), loc.getZ());
this.setPos(loc.getX(), loc.getY(), loc.getZ());
setInvisible(true);
setInvulnerable(true);
setMarker(true);
getBukkitLivingEntity().setCollidable(false);
persist = false;
}
}

View File

@@ -0,0 +1,27 @@
package com.hibiscusmc.hmccosmetics.entities;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.ambient.Bat;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.craftbukkit.v1_19_R1.CraftWorld;
import org.bukkit.persistence.PersistentDataType;
public class MEGEntity extends Bat {
public MEGEntity(Location loc) {
super(EntityType.BAT, ((CraftWorld) loc.getWorld()).getHandle());
this.setPos(loc.getX(), loc.getY(), loc.getZ());
HMCCosmeticsPlugin.getInstance().getLogger().info("Spawned MEGEntity at " + loc);
getBukkitLivingEntity().setInvisible(true);
getBukkitLivingEntity().setInvulnerable(true); // NOTE - CREATIVE PLAYERS CAN DESTROY IT STILL
getBukkitLivingEntity().setAI(false);
getBukkitLivingEntity().setGravity(false);
getBukkitLivingEntity().setSilent(true);
getBukkitLivingEntity().setCollidable(false);
persist = false;
getBukkitEntity().getPersistentDataContainer().set(new NamespacedKey(HMCCosmeticsPlugin.getInstance(), "cosmeticMob"), PersistentDataType.SHORT, Short.valueOf("1"));
}
}

View File

@@ -0,0 +1,157 @@
package com.hibiscusmc.hmccosmetics.gui;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.config.serializer.ItemSerializer;
import com.hibiscusmc.hmccosmetics.gui.type.Types;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import com.hibiscusmc.hmccosmetics.util.misc.Adventure;
import com.hibiscusmc.hmccosmetics.util.misc.Placeholder;
import dev.triumphteam.gui.builder.item.ItemBuilder;
import dev.triumphteam.gui.guis.Gui;
import dev.triumphteam.gui.guis.GuiItem;
import net.kyori.adventure.text.Component;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import java.util.ArrayList;
import java.util.List;
public class Menu {
private String id;
private String title;
private int rows;
private ConfigurationNode config;
public Menu(String id, ConfigurationNode config) {
this.id = id;
this.config = config;
title = config.node("title").getString("chest");
rows = config.node("rows").getInt(1);
Menus.addMenu(this);
}
public String getId() {
return id;
}
public String getTitle() {
return this.title;
}
public int getRows() {
return this.getRows();
}
public void openMenu(CosmeticUser user) {
Player player = user.getPlayer();
final Component component = Adventure.MINI_MESSAGE.deserialize(Placeholder.applyPapiPlaceholders(player, this.title));
Gui gui = Gui.gui().
title(component).
rows(this.rows).
create();
gui.setDefaultClickAction(event -> event.setCancelled(true));
gui = getItems(user, gui);
gui.open(player);
}
private Gui getItems(CosmeticUser user, Gui gui) {
Player player = user.getPlayer();
for (ConfigurationNode config : config.node("items").childrenMap().values()) {
List<String> slotString = null;
try {
slotString = config.node("slots").getList(String.class);
} catch (SerializationException e) {
continue;
}
if (slotString == null) {
HMCCosmeticsPlugin.getInstance().getLogger().info("Unable to get valid slot for " + config.key().toString());
continue;
}
List<Integer> slots = getSlots(slotString);
if (slots == null) {
HMCCosmeticsPlugin.getInstance().getLogger().info("Slot is null for " + config.key().toString());
continue;
}
ItemStack item;
try {
item = ItemSerializer.INSTANCE.deserialize(ItemStack.class, config.node("item"));
//item = config.node("item").get(ItemStack.class);
} catch (SerializationException e) {
throw new RuntimeException(e);
}
if (item == null) {
HMCCosmeticsPlugin.getInstance().getLogger().info("something went wrong! " + item);
continue;
}
if (item.hasItemMeta()) {
List<String> processedLore = new ArrayList<>();
for (String loreLine : item.getItemMeta().getLore()) {
processedLore.add(loreLine.replaceAll("%allowed%", "allowed?"));
// TODO apply placeholders here
}
ItemMeta itemMeta = item.getItemMeta();
itemMeta.setLore(processedLore);
item.setItemMeta(itemMeta);
}
GuiItem guiItem = ItemBuilder.from(item).asGuiItem();
guiItem.setAction(event -> {
if (config.node("type").virtual()) return;
String type = config.node("type").getString();
if (Types.isType(type)) Types.getType(type).run(user, config);
for (int i : slots) {
gui.updateItem(i, guiItem);
}
});
HMCCosmeticsPlugin.getInstance().getLogger().info("Added " + slots + " as " + guiItem + " in the menu");
gui.setItem(slots, guiItem);
}
return gui;
}
private List<Integer> getSlots(List<String> slotString) {
List<Integer> slots = new ArrayList<>();
for (String a : slotString) {
if (a.contains("-")) {
String[] split = a.split("-");
int min = Integer.valueOf(split[0]);
int max = Integer.valueOf(split[1]);
slots.addAll(getSlots(min, max));
} else {
slots.add(Integer.valueOf(a));
}
}
return slots;
}
private List<Integer> getSlots(int small, int max) {
List<Integer> slots = new ArrayList<>();
for (int i = small; i <= max; i++) slots.add(i);
return slots;
}
}

View File

@@ -0,0 +1,73 @@
package com.hibiscusmc.hmccosmetics.gui;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import org.apache.commons.io.FilenameUtils;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.ConfigurateException;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
public class Menus {
private static HashMap<String, Menu> MENUS = new HashMap<>();
public static void addMenu(Menu menu) {
MENUS.put(menu.getId(), menu);
}
public static Menu getMenu(String id) {
return MENUS.get(id);
}
public static Collection<Menu> getMenu() {
return MENUS.values();
}
public static boolean hasMenu(String id) {
return MENUS.containsKey(id);
}
public static boolean hasMenu(Menu menu) {
return MENUS.containsValue(menu);
}
public static List<String> getMenuNames() {
List<String> names = new ArrayList<>();
for (Menu menu : MENUS.values()) {
names.add(menu.getId());
}
return names;
}
public static void setup() {
MENUS.clear();
File cosmeticFolder = new File(HMCCosmeticsPlugin.getInstance().getDataFolder() + "/menus");
if (!cosmeticFolder.exists()) cosmeticFolder.mkdir();
File[] directoryListing = cosmeticFolder.listFiles();
if (directoryListing == null) return;
for (File child : directoryListing) {
if (child.toString().contains(".yml") || child.toString().contains(".yaml")) {
HMCCosmeticsPlugin.getInstance().getLogger().info("Scanning " + child);
// Loads file
YamlConfigurationLoader loader = YamlConfigurationLoader.builder().path(child.toPath()).build();
CommentedConfigurationNode root;
try {
root = loader.load();
} catch (ConfigurateException e) {
throw new RuntimeException(e);
}
new Menu(FilenameUtils.removeExtension(child.getName()), root);
}
}
}
}

View File

@@ -0,0 +1,21 @@
package com.hibiscusmc.hmccosmetics.gui.action;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
public class Action {
private String id;
public Action(String id) {
this.id = id.toUpperCase();
Actions.addAction(this);
}
public String getId() {
return this.id;
}
public void run(CosmeticUser user, String raw) {
// Override
}
}

View File

@@ -0,0 +1,49 @@
package com.hibiscusmc.hmccosmetics.gui.action;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.gui.action.actions.ActionConsoleCommand;
import com.hibiscusmc.hmccosmetics.gui.action.actions.ActionMenu;
import com.hibiscusmc.hmccosmetics.gui.action.actions.ActionMessage;
import com.hibiscusmc.hmccosmetics.gui.action.actions.ActionPlayerCommand;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import org.apache.commons.lang.StringUtils;
import java.util.HashMap;
import java.util.List;
public class Actions {
private static HashMap<String, Action> actions = new HashMap<>();
// [ID]
private static ActionMessage ACTION_MESSAGE = new ActionMessage();
private static ActionMenu ACTION_MENU = new ActionMenu();
private static ActionPlayerCommand ACTION_CONSOLE_COMMAND = new ActionPlayerCommand();
private static ActionConsoleCommand ACTION_PLAYER_COMMAND = new ActionConsoleCommand();
public static Action getAction(String id) {
return actions.get(id);
}
public static boolean isAction(String id) {
return actions.containsKey(id);
}
public static void addAction(Action action) {
actions.put(action.getId(), action);
}
public static void runActions(CosmeticUser user, List<String> raw) {
for (String a : raw) {
String id = StringUtils.substringBetween(a, "[", "]").toUpperCase();
String message = StringUtils.substringAfter(a, "] ");
HMCCosmeticsPlugin.getInstance().getLogger().info("ID is " + id + " // Message is " + message);
if (isAction(id)) {
getAction(id).run(user, message);
} else {
HMCCosmeticsPlugin.getInstance().getLogger().info("Possible ids: " + actions.keySet());
}
}
}
}

View File

@@ -0,0 +1,18 @@
package com.hibiscusmc.hmccosmetics.gui.action.actions;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.gui.action.Action;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
public class ActionConsoleCommand extends Action {
public ActionConsoleCommand() {
super("console-command");
}
@Override
public void run(CosmeticUser user, String raw) {
HMCCosmeticsPlugin.getInstance().getServer().dispatchCommand(user.getPlayer(), raw);
}
}

View File

@@ -0,0 +1,20 @@
package com.hibiscusmc.hmccosmetics.gui.action.actions;
import com.hibiscusmc.hmccosmetics.gui.Menu;
import com.hibiscusmc.hmccosmetics.gui.Menus;
import com.hibiscusmc.hmccosmetics.gui.action.Action;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
public class ActionMenu extends Action {
public ActionMenu() {
super("menu");
}
@Override
public void run(CosmeticUser user, String raw) {
if (!Menus.hasMenu(raw)) return;
Menu menu = Menus.getMenu(raw);
menu.openMenu(user);
}
}

View File

@@ -0,0 +1,16 @@
package com.hibiscusmc.hmccosmetics.gui.action.actions;
import com.hibiscusmc.hmccosmetics.gui.action.Action;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
public class ActionMessage extends Action {
public ActionMessage() {
super("message");
}
@Override
public void run(CosmeticUser user, String raw) {
user.getPlayer().sendMessage(raw);
}
}

View File

@@ -0,0 +1,16 @@
package com.hibiscusmc.hmccosmetics.gui.action.actions;
import com.hibiscusmc.hmccosmetics.gui.action.Action;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
public class ActionPlayerCommand extends Action {
public ActionPlayerCommand() {
super("player-command");
}
@Override
public void run(CosmeticUser user, String raw) {
user.getPlayer().performCommand(raw);
}
}

View File

@@ -0,0 +1,22 @@
package com.hibiscusmc.hmccosmetics.gui.type;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import org.spongepowered.configurate.ConfigurationNode;
public class Type {
private String id;
public Type(String id) {
this.id = id;
Types.addType(this);
}
public String getId() {
return this.id;
}
public void run(CosmeticUser user, ConfigurationNode config) {
// Override
}
}

View File

@@ -0,0 +1,26 @@
package com.hibiscusmc.hmccosmetics.gui.type;
import com.hibiscusmc.hmccosmetics.gui.type.types.TypeCosmetic;
import com.hibiscusmc.hmccosmetics.gui.type.types.TypeEmpty;
import java.util.HashMap;
public class Types {
private static HashMap<String, Type> types = new HashMap<>();
private static TypeCosmetic TYPE_COSMETIC = new TypeCosmetic();
private static TypeEmpty TYPE_EMPTY = new TypeEmpty();
public static Type getType(String id) {
return types.get(id);
}
public static boolean isType(String id) {
return types.containsKey(id);
}
public static void addType(Type type) {
types.put(type.getId(), type);
}
}

View File

@@ -0,0 +1,53 @@
package com.hibiscusmc.hmccosmetics.gui.type.types;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetic;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetics;
import com.hibiscusmc.hmccosmetics.gui.action.Actions;
import com.hibiscusmc.hmccosmetics.gui.type.Type;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import java.util.ArrayList;
import java.util.List;
public class TypeCosmetic extends Type {
public TypeCosmetic() {
super("cosmetic");
}
@Override
public void run(CosmeticUser user, ConfigurationNode config) {
if (config.node("cosmetic").virtual()) return;
String cosmeticName = config.node("cosmetic").getString();
Cosmetic cosmetic = Cosmetics.getCosmetic(cosmeticName);
if (cosmetic == null) return;
List<String> actionStrings = new ArrayList<>();
ConfigurationNode actionConfig = config.node("actions");
try {
if (!actionConfig.node("any").virtual()) actionStrings.addAll(actionConfig.node("any").getList(String.class));
if (user.getCosmetic(cosmetic.getSlot()) == cosmetic) {
if (!actionConfig.node("on-unequip").virtual()) actionStrings.addAll(actionConfig.node("on-unequip").getList(String.class));
HMCCosmeticsPlugin.getInstance().getLogger().info("on-unequip");
user.removeCosmeticSlot(cosmetic);
} else {
if (!actionConfig.node("on-equip").virtual()) actionStrings.addAll(actionConfig.node("on-equip").getList(String.class));
HMCCosmeticsPlugin.getInstance().getLogger().info("on-equip");
user.addPlayerCosmetic(cosmetic);
}
Actions.runActions(user, actionStrings);
} catch (SerializationException e) {
throw new RuntimeException(e);
}
//user.toggleCosmetic(cosmetic);
user.updateCosmetic(cosmetic.getSlot());
}
}

View File

@@ -0,0 +1,43 @@
package com.hibiscusmc.hmccosmetics.gui.type.types;
import com.hibiscusmc.hmccosmetics.gui.action.Actions;
import com.hibiscusmc.hmccosmetics.gui.type.Type;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException;
import java.util.ArrayList;
import java.util.List;
public class TypeEmpty extends Type {
// This can be used as an example for making your own types.
public TypeEmpty() {
super("empty");
// This is an empty type, meaning, when a menu item has a type of "empty" it will run the code in the method run.
}
// This is the code that's run when the item is clicked.
@Override
public void run(CosmeticUser user, ConfigurationNode config) {
List<String> actionStrings = new ArrayList<>(); // List where we keep the actions the server will execute.
ConfigurationNode actionConfig = config.node("actions"); // Configuration node that actions are under.
// We have to encase it in try catch for configurate serialization
try {
// This gets the actions with the item. We can add more, such as with the Cosmetic type, an equip and unequip action set.
// We add that to a List of Strings, before running those actions through the server. This is not the area where we deal
// with actions, mearly what should be done for each item.
if (!actionConfig.node("any").virtual()) actionStrings.addAll(actionConfig.node("any").getList(String.class));
// We run the actions once we got the raw strings from the config.
Actions.runActions(user, actionStrings);
} catch (SerializationException e) {
throw new RuntimeException(e);
}
}
// That's it! Now, add it as a static in another one of your classes (such as your main class) and you are good to go.
// If you need help with that, check the Types class.
}

View File

@@ -0,0 +1,54 @@
package com.hibiscusmc.hmccosmetics.hooks;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import com.hibiscusmc.hmccosmetics.user.CosmeticUsers;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
public class PAPIHook extends PlaceholderExpansion {
// TODO: Finish this
@Override
public @NotNull String getIdentifier() {
return "HMCCosmetics";
}
@Override
public @NotNull String getAuthor() {
return "HibiscusMC";
}
@Override
public @NotNull String getVersion() {
return HMCCosmeticsPlugin.getInstance().getDescription().getVersion();
}
@Override
public String onRequest(OfflinePlayer player, String params) {
final String[] parts = params.split("_");
if (parts.length == 0) {
return null;
}
CosmeticUser user = CosmeticUsers.getUser(player.getUniqueId());
if (user == null) return null;
if (parts[0].equalsIgnoreCase("using")) {
if (parts.length < 2) return null;
final String id = this.getId(parts, 1);
}
return "";
}
private String getId(final String[] parts, final int fromIndex) {
final StringBuilder builder = new StringBuilder();
for (int i = fromIndex; i < parts.length; i++) {
builder.append(parts[i]);
if (i < parts.length - 1) builder.append("_");
}
return builder.toString();
}
}

View File

@@ -0,0 +1,32 @@
package com.hibiscusmc.hmccosmetics.hooks.items;
import org.bukkit.inventory.ItemStack;
public class ItemHook {
private String id;
private boolean active;
public ItemHook(String id) {
this.id = id;
active = false;
ItemHooks.addItemHook(this);
}
public ItemStack get(String itemid) {
return null;
// Override
}
public String getId() {
return id;
}
public void setActive(boolean active) {
this.active = active;
}
public boolean getActive() {
return this.active;
}
}

View File

@@ -0,0 +1,54 @@
package com.hibiscusmc.hmccosmetics.hooks.items;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
public class ItemHooks {
private static HashMap<String, ItemHook> itemHooks = new HashMap<>();
private static OraxenHook ORAXEN_HOOK = new OraxenHook();
public static ItemHook getItemHook(String id) {
return itemHooks.get(id.toLowerCase());
}
public static boolean isItemHook(String id) {
return itemHooks.containsKey(id.toLowerCase());
}
public static void addItemHook(ItemHook hook) {
itemHooks.put(hook.getId().toLowerCase(), hook);
}
public static void setup() {
for (ItemHook itemHook : itemHooks.values()) {
if (Bukkit.getPluginManager().getPlugin(itemHook.getId()) != null) {
itemHook.setActive(true);
HMCCosmeticsPlugin.getInstance().getLogger().info("Successfully hooked into " + itemHook.getId());
}
}
}
public static ItemStack getItem(String raw) {
if (!raw.contains(":")) {
Material mat = Material.getMaterial(raw);
if (mat == null) return null;
return new ItemStack(mat);
}
// Ex. Oraxen:BigSword
// split[0] is the plugin name
// split[1] is the item name
String[] split = raw.split(":");
if (!isItemHook(split[0])) return null;
ItemHook itemHook = getItemHook(split[0]);
if (!itemHook.getActive()) return null;
ItemStack item = itemHook.get(split[1]);
return item;
}
}

View File

@@ -0,0 +1,17 @@
package com.hibiscusmc.hmccosmetics.hooks.items;
import io.th0rgal.oraxen.api.OraxenItems;
import org.bukkit.inventory.ItemStack;
public class OraxenHook extends ItemHook{
public OraxenHook() {
super("oraxen");
}
public ItemStack get(String itemid) {
return OraxenItems.getItemById(itemid).build();
}
}

View File

@@ -0,0 +1,41 @@
package com.hibiscusmc.hmccosmetics.listener;
import com.hibiscusmc.hmccosmetics.database.Database;
import com.hibiscusmc.hmccosmetics.entities.InvisibleArmorstand;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import com.hibiscusmc.hmccosmetics.user.CosmeticUsers;
import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class PlayerConnectionListener implements Listener {
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
CosmeticUser user = Database.get(event.getPlayer().getUniqueId());
CosmeticUsers.addUser(user);
user.updateCosmetic();
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
CosmeticUser user = CosmeticUsers.getUser(event.getPlayer());
if (user == null) { // Remove any passengers if a user failed to initialize. Bugs can cause this to happen
if (!event.getPlayer().getPassengers().isEmpty()) {
for (Entity entity : event.getPlayer().getPassengers()) {
if (entity instanceof InvisibleArmorstand) {
((InvisibleArmorstand) entity).setHealth(0);
entity.remove();
}
}
}
}
if (user.isInWardrobe()) user.leaveWardrobe();
Database.save(user);
user.despawnBackpack();
user.despawnBalloon();
CosmeticUsers.removeUser(user.getUniqueId());
}
}

View File

@@ -0,0 +1,233 @@
package com.hibiscusmc.hmccosmetics.listener;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.wrappers.EnumWrappers;
import com.comphenix.protocol.wrappers.Pair;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetic;
import com.hibiscusmc.hmccosmetics.cosmetic.CosmeticSlot;
import com.hibiscusmc.hmccosmetics.cosmetic.types.CosmeticArmorType;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import com.hibiscusmc.hmccosmetics.user.CosmeticUsers;
import com.hibiscusmc.hmccosmetics.util.InventoryUtils;
import com.hibiscusmc.hmccosmetics.util.PlayerUtils;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerToggleSneakEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class PlayerGameListener implements Listener {
public PlayerGameListener() {
registerInventoryClickListener();
registerMenuChangeListener();
registerPlayerEquipmentListener();
}
@EventHandler
public void onPlayerClick(@NotNull InventoryClickEvent event) {
if (event.getClick() != ClickType.SHIFT_LEFT && event.getClick() != ClickType.SHIFT_RIGHT) return;
//if (event.getSlotType() != InventoryType.SlotType.ARMOR) return;
CosmeticUser user = CosmeticUsers.getUser(event.getWhoClicked().getUniqueId());
if (user == null) return;
EquipmentSlot slot = getArmorSlot(event.getCurrentItem().getType());
if (slot == null) return;
CosmeticSlot cosmeticSlot = InventoryUtils.BukkitCosmeticSlot(slot);
if (cosmeticSlot == null) return;
if (!user.hasCosmeticInSlot(cosmeticSlot)) return;
Bukkit.getScheduler().runTaskLater(HMCCosmeticsPlugin.getInstance(), () -> {
user.updateCosmetic(cosmeticSlot);
}, 1);
HMCCosmeticsPlugin.getInstance().getLogger().info("Event fired, updated cosmetic " + cosmeticSlot);
}
@EventHandler
public void onPlayerShift(PlayerToggleSneakEvent event) {
CosmeticUser user = CosmeticUsers.getUser(event.getPlayer().getUniqueId());
if (!event.isSneaking()) return;
if (user == null) return;
if (!user.isInWardrobe()) return;
user.leaveWardrobe();
}
@EventHandler
public void onPlayerTeleport(PlayerTeleportEvent event) {
CosmeticUser user = CosmeticUsers.getUser(event.getPlayer().getUniqueId());
if (user.hasCosmeticInSlot(CosmeticSlot.BACKPACK)) {
user.hideBackpack();
user.getBackpackEntity().getBukkitLivingEntity().teleport(event.getTo());
Bukkit.getScheduler().runTaskLater(HMCCosmeticsPlugin.getInstance(), () -> {
user.showBackpack();
}, 2);
}
}
@EventHandler
public void onPlayerLook(PlayerMoveEvent event) {
CosmeticUser user = CosmeticUsers.getUser(event.getPlayer().getUniqueId());
if (user == null) return;
// Really need to look into optimization of this
user.updateCosmetic(CosmeticSlot.BACKPACK);
user.updateCosmetic(CosmeticSlot.BALLOON);
}
private void registerInventoryClickListener() {
ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(HMCCosmeticsPlugin.getInstance(), ListenerPriority.NORMAL, PacketType.Play.Client.WINDOW_CLICK) {
@Override
public void onPacketReceiving(PacketEvent event) {
Player player = event.getPlayer();
int invTypeClicked = event.getPacket().getIntegers().read(0);
int slotClicked = event.getPacket().getIntegers().read(2);
// Must be a player inventory.
if (invTypeClicked != 0) return;
// -999 is when a player clicks outside their inventory. https://wiki.vg/Inventory#Player_Inventory
if (slotClicked == -999) return;
if (!(event.getPlayer() instanceof Player)) return;
CosmeticUser user = CosmeticUsers.getUser(player);
if (user == null) return;
CosmeticSlot cosmeticSlot = InventoryUtils.NMSCosmeticSlot(slotClicked);
if (cosmeticSlot == null) return;
if (!user.hasCosmeticInSlot(cosmeticSlot)) return;
Bukkit.getScheduler().runTaskLater(HMCCosmeticsPlugin.getInstance(), () -> {
user.updateCosmetic(cosmeticSlot);
}, 1);
HMCCosmeticsPlugin.getInstance().getLogger().info("Packet fired, updated cosmetic " + cosmeticSlot);
}
});
}
private void registerMenuChangeListener() {
ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(HMCCosmeticsPlugin.getInstance(), ListenerPriority.NORMAL, PacketType.Play.Server.WINDOW_ITEMS) {
@Override
public void onPacketSending(PacketEvent event) {
HMCCosmeticsPlugin.getInstance().getLogger().info("Menu Initial ");
Player player = event.getPlayer();
if (event.getPlayer() == null) return;
if (!(event.getPlayer() instanceof Player)) return;
int windowID = event.getPacket().getIntegers().read(0);
List<ItemStack> slotData = event.getPacket().getItemListModifier().read(0);
if (windowID != 0) return;
CosmeticUser user = CosmeticUsers.getUser(player);
if (user == null) return;
for (Cosmetic cosmetic : user.getCosmetic()) {
if (!(cosmetic instanceof CosmeticArmorType)) continue;
Bukkit.getScheduler().runTaskLater(HMCCosmeticsPlugin.getInstance(), () -> {
user.updateCosmetic(cosmetic.getSlot());
}, 1);
HMCCosmeticsPlugin.getInstance().getLogger().info("Menu Fired, updated cosmetics " + cosmetic);
}
}
});
}
private void registerPlayerEquipmentListener() {
ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(HMCCosmeticsPlugin.getInstance(), ListenerPriority.NORMAL, PacketType.Play.Server.ENTITY_EQUIPMENT) {
@Override
public void onPacketSending(PacketEvent event) {
//HMCCosmeticsPlugin.getInstance().getLogger().info("equipment packet is activated");
Player player = event.getPlayer(); // Player that's sent
int entityID = event.getPacket().getIntegers().read(0);
// User
CosmeticUser user = CosmeticUsers.getUser(entityID);
if (user == null) {
//HMCCosmeticsPlugin.getInstance().getLogger().info("equipment packet is activated - user null");
return;
}
List<com.comphenix.protocol.wrappers.Pair<EnumWrappers.ItemSlot, ItemStack>> armor = event.getPacket().getSlotStackPairLists().read(0);
for (EquipmentSlot equipmentSlot : EquipmentSlot.values()) {
CosmeticArmorType cosmeticArmor = (CosmeticArmorType) user.getCosmetic(InventoryUtils.BukkitCosmeticSlot(equipmentSlot));
if (cosmeticArmor == null) continue;
Pair<EnumWrappers.ItemSlot, ItemStack> pair = new Pair<>(InventoryUtils.itemBukkitSlot(cosmeticArmor.getEquipSlot()), cosmeticArmor.getCosmeticItem());
armor.add(pair);
}
event.getPacket().getSlotStackPairLists().write(0, armor);
HMCCosmeticsPlugin.getInstance().getLogger().info("Equipment for " + user.getPlayer().getName() + " has been updated for " + player.getName());
}
});
}
@Nullable
private EquipmentSlot getArmorSlot(final Material material) {
for (final EquipmentSlot slot : EquipmentSlot.values()) {
final Set<Material> armorItems = ARMOR_ITEMS.get(slot);
if (armorItems == null) continue;
if (material == null) continue;
if (armorItems.contains(material)) return slot;
}
return null;
}
final static Map<EquipmentSlot, Set<Material>> ARMOR_ITEMS = Map.of(
EquipmentSlot.HEAD, EnumSet.of(
Material.LEATHER_HELMET,
Material.CHAINMAIL_HELMET,
Material.IRON_HELMET,
Material.GOLDEN_HELMET,
Material.DIAMOND_HELMET,
Material.NETHERITE_HELMET,
Material.TURTLE_HELMET
),
EquipmentSlot.CHEST, EnumSet.of(
Material.LEATHER_CHESTPLATE,
Material.CHAINMAIL_CHESTPLATE,
Material.IRON_CHESTPLATE,
Material.GOLDEN_CHESTPLATE,
Material.DIAMOND_CHESTPLATE,
Material.NETHERITE_CHESTPLATE,
Material.ELYTRA
),
EquipmentSlot.LEGS, EnumSet.of(
Material.LEATHER_LEGGINGS,
Material.CHAINMAIL_LEGGINGS,
Material.IRON_LEGGINGS,
Material.GOLDEN_LEGGINGS,
Material.DIAMOND_LEGGINGS,
Material.NETHERITE_LEGGINGS
),
EquipmentSlot.FEET, EnumSet.of(
Material.LEATHER_BOOTS,
Material.CHAINMAIL_BOOTS,
Material.IRON_BOOTS,
Material.GOLDEN_BOOTS,
Material.DIAMOND_BOOTS,
Material.NETHERITE_BOOTS
)
);
}

View File

@@ -0,0 +1,10 @@
package com.hibiscusmc.hmccosmetics.nms;
public interface NMSHandler {
int getNextEntityId();
default boolean getSupported () {
return false;
}
}

View File

@@ -0,0 +1,31 @@
package com.hibiscusmc.hmccosmetics.nms;
import java.lang.reflect.InvocationTargetException;
public class NMSHandlers {
private static final String[] SUPPORTED_VERSION = new String[]{"v1_19_R1"};
private static NMSHandler handler;
public static NMSHandler getHandler() {
if (handler != null) {
return handler;
} else {
setup();
}
return handler;
}
public static void setup() {
if (handler != null) return;
for (String version : SUPPORTED_VERSION) {
try {
//Class.forName("org.bukkit.craftbukkit." + version + ".block.CraftBlock").getName();
handler = (NMSHandler) Class.forName("com.hibiscusmc.hmccosmetics.nms." + version + ".NMSHandler").getConstructor().newInstance();
} catch (ClassNotFoundException | InvocationTargetException | InstantiationException |
IllegalAccessException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
}

View File

@@ -0,0 +1,293 @@
package com.hibiscusmc.hmccosmetics.user;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.config.Settings;
import com.hibiscusmc.hmccosmetics.config.WardrobeSettings;
import com.hibiscusmc.hmccosmetics.cosmetic.Cosmetic;
import com.hibiscusmc.hmccosmetics.cosmetic.CosmeticSlot;
import com.hibiscusmc.hmccosmetics.cosmetic.types.CosmeticArmorType;
import com.hibiscusmc.hmccosmetics.cosmetic.types.CosmeticBackpackType;
import com.hibiscusmc.hmccosmetics.cosmetic.types.CosmeticBalloonType;
import com.hibiscusmc.hmccosmetics.entities.BalloonEntity;
import com.hibiscusmc.hmccosmetics.entities.InvisibleArmorstand;
import com.hibiscusmc.hmccosmetics.util.PlayerUtils;
import com.hibiscusmc.hmccosmetics.util.packets.PacketManager;
import net.minecraft.world.entity.EquipmentSlot;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_19_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_19_R1.inventory.CraftItemStack;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
public class CosmeticUser {
private UUID uniqueId;
private HashMap<CosmeticSlot, Cosmetic> playerCosmetics = new HashMap<>();
private Wardrobe wardrobe;
private InvisibleArmorstand invisibleArmorstand;
private BalloonEntity balloonEntity;
// Cosmetic Settings/Toggles
private boolean hideBackpack;
private HashMap<CosmeticSlot, Color> colors = new HashMap<>();
public CosmeticUser(UUID uuid) {
this.uniqueId = uuid;
}
public UUID getUniqueId() {
return this.uniqueId;
}
public Cosmetic getCosmetic(CosmeticSlot slot) {
return playerCosmetics.get(slot);
}
public Collection<Cosmetic> getCosmetic() {
return playerCosmetics.values();
}
public int getArmorstandId() {
return invisibleArmorstand.getId();
}
public InvisibleArmorstand getBackpackEntity() {
return this.invisibleArmorstand;
}
public BalloonEntity getBalloonEntity() {
return this.balloonEntity;
}
public void addPlayerCosmetic(Cosmetic cosmetic) {
addPlayerCosmetic(cosmetic, null);
}
public void addPlayerCosmetic(Cosmetic cosmetic, Color color) {
playerCosmetics.put(cosmetic.getSlot(), cosmetic);
if (color != null) colors.put(cosmetic.getSlot(), color);
if (cosmetic.getSlot() == CosmeticSlot.BACKPACK) {
CosmeticBackpackType backpackType = (CosmeticBackpackType) cosmetic;
spawnBackpack(backpackType);
}
if (cosmetic.getSlot() == CosmeticSlot.BALLOON) {
CosmeticBalloonType balloonType = (CosmeticBalloonType) cosmetic;
spawnBalloon(balloonType);
}
}
public void toggleCosmetic(Cosmetic cosmetic) {
if (hasCosmeticInSlot(cosmetic.getSlot())) {
removeCosmeticSlot(cosmetic.getSlot());
return;
}
addPlayerCosmetic(cosmetic);
}
public void removeCosmeticSlot(CosmeticSlot slot) {
if (slot == CosmeticSlot.BACKPACK) {
despawnBackpack();
}
if (slot == CosmeticSlot.BALLOON) {
despawnBalloon();
}
colors.remove(slot);
playerCosmetics.remove(slot);
removeArmor(slot);
}
public void removeCosmeticSlot(Cosmetic cosmetic) {
removeCosmeticSlot(cosmetic.getSlot());
}
public boolean hasCosmeticInSlot(CosmeticSlot slot) {
return playerCosmetics.containsKey(slot);
}
public void updateCosmetic(CosmeticSlot slot) {
if (getCosmetic(slot) == null) {
return;
}
getCosmetic(slot).update(this);
return;
}
public void updateCosmetic() {
for (Cosmetic cosmetic : playerCosmetics.values()) {
updateCosmetic(cosmetic.getSlot());
}
}
public ItemStack getUserCosmeticItem(Cosmetic cosmetic) {
ItemStack item = null;
if (cosmetic instanceof CosmeticArmorType) {
CosmeticArmorType cosmetic1 = (CosmeticArmorType) cosmetic;
item = cosmetic1.getCosmeticItem();
}
if (cosmetic instanceof CosmeticBackpackType) {
CosmeticBackpackType cosmetic1 = (CosmeticBackpackType) cosmetic;
item = cosmetic1.getBackpackItem();
}
if (!item.hasItemMeta()) return null;
ItemMeta itemMeta = item.getItemMeta();
if (itemMeta instanceof LeatherArmorMeta) {
if (colors.containsKey(cosmetic.getSlot())) {
((LeatherArmorMeta) itemMeta).setColor(colors.get(cosmetic.getSlot()));
}
}
item.setItemMeta(itemMeta);
return item;
}
public void enterWardrobe() {
if (!WardrobeSettings.inDistanceOfStatic(getPlayer().getLocation())) {
getPlayer().sendMessage("You are to far away!");
return;
}
wardrobe = new Wardrobe(this);
wardrobe.start();
}
public Wardrobe getWardrobe() {
return wardrobe;
}
public void leaveWardrobe() {
wardrobe.end();
wardrobe = null;
}
public boolean isInWardrobe() {
if (wardrobe == null) return false;
return true;
}
public void toggleWardrobe() {
if (isInWardrobe()) {
leaveWardrobe();
} else {
enterWardrobe();
}
}
public void spawnBackpack(CosmeticBackpackType cosmeticBackpackType) {
Player player = Bukkit.getPlayer(getUniqueId());
List<Player> sentTo = PlayerUtils.getNearbyPlayers(player.getLocation());
if (this.invisibleArmorstand != null) return;
this.invisibleArmorstand = new InvisibleArmorstand(player.getLocation());
ItemStack item = getUserCosmeticItem(cosmeticBackpackType);
invisibleArmorstand.setItemSlot(EquipmentSlot.HEAD, CraftItemStack.asNMSCopy(item));
((CraftWorld) player.getWorld()).getHandle().addFreshEntity(invisibleArmorstand, CreatureSpawnEvent.SpawnReason.CUSTOM);
//PacketManager.armorStandMetaPacket(invisibleArmorstand.getBukkitEntity(), sentTo);
//PacketManager.ridingMountPacket(player.getEntityId(), invisibleArmorstand.getId(), sentTo);
player.addPassenger(invisibleArmorstand.getBukkitEntity());
}
public void spawnBalloon(CosmeticBalloonType cosmeticBalloonType) {
Player player = Bukkit.getPlayer(getUniqueId());
List<Player> sentTo = PlayerUtils.getNearbyPlayers(player.getLocation());
Location newLoc = player.getLocation().clone().add(Settings.getBalloonOffset());
if (this.balloonEntity != null) return;
BalloonEntity balloonEntity1 = new BalloonEntity(player.getLocation());
((CraftWorld) player.getWorld()).getHandle().addFreshEntity(balloonEntity1.getModelEntity(), CreatureSpawnEvent.SpawnReason.CUSTOM);
balloonEntity1.spawnModel(cosmeticBalloonType.getModelName());
balloonEntity1.addPlayerToModel(player, cosmeticBalloonType.getModelName());
PacketManager.sendEntitySpawnPacket(newLoc, balloonEntity1.getPufferfishBalloonId(), EntityType.PUFFERFISH, balloonEntity1.getPufferfishBalloonUniqueId(), sentTo);
PacketManager.sendInvisibilityPacket(balloonEntity1.getPufferfishBalloonId(), sentTo);
PacketManager.sendLeashPacket(balloonEntity1.getPufferfishBalloonId(), player.getEntityId(), sentTo);
this.balloonEntity = balloonEntity1;
}
public void despawnBalloon() {
if (this.balloonEntity == null) return;
List<Player> sentTo = PlayerUtils.getNearbyPlayers(getPlayer().getLocation());
PacketManager.sendEntityDestroyPacket(balloonEntity.getPufferfishBalloonId(), sentTo);
this.balloonEntity.remove();
this.balloonEntity = null;
}
public void despawnBackpack() {
Player player = Bukkit.getPlayer(getUniqueId());
if (invisibleArmorstand == null) return;
invisibleArmorstand.getBukkitLivingEntity().setHealth(0);
invisibleArmorstand.remove(net.minecraft.world.entity.Entity.RemovalReason.DISCARDED);
this.invisibleArmorstand = null;
}
public void removeArmor(CosmeticSlot slot) {
PacketManager.equipmentSlotUpdate(getPlayer().getEntityId(), this, slot, PlayerUtils.getNearbyPlayers(getPlayer()));
}
public Player getPlayer() {
return Bukkit.getPlayer(uniqueId);
}
public boolean hasCosmetic(Cosmetic cosmetic) {
if (!cosmetic.requiresPermission()) return true;
if (getPlayer().hasPermission(cosmetic.getPermission())) return true;
return false;
}
public void hidePlayer() {
Player player = getPlayer();
if (player == null) return;
for (final Player p : Bukkit.getOnlinePlayers()) {
p.hidePlayer(HMCCosmeticsPlugin.getInstance(), player);
player.hidePlayer(HMCCosmeticsPlugin.getInstance(), p);
}
}
public void showPlayer() {
Player player = getPlayer();
if (player == null) return;
for (final Player p : Bukkit.getOnlinePlayers()) {
p.showPlayer(HMCCosmeticsPlugin.getInstance(), player);
player.showPlayer(HMCCosmeticsPlugin.getInstance(), p);
}
}
public void hideBackpack() {
if (hideBackpack == true) return;
if (hasCosmeticInSlot(CosmeticSlot.BACKPACK)) {
//CosmeticBackpackType cosmeticBackpackType = (CosmeticBackpackType) getCosmetic(CosmeticSlot.BACKPACK);
getPlayer().removePassenger(invisibleArmorstand.getBukkitEntity());
invisibleArmorstand.getBukkitLivingEntity().getEquipment().clear();
hideBackpack = true;
}
}
public void showBackpack() {
if (hideBackpack == false) return;
if (hasCosmeticInSlot(CosmeticSlot.BACKPACK)) {
CosmeticBackpackType cosmeticBackpackType = (CosmeticBackpackType) getCosmetic(CosmeticSlot.BACKPACK);
getPlayer().addPassenger(invisibleArmorstand.getBukkitEntity());
ItemStack item = getUserCosmeticItem(cosmeticBackpackType);
invisibleArmorstand.setItemSlot(EquipmentSlot.HEAD, CraftItemStack.asNMSCopy(item));
hideBackpack = false;
}
}
}

View File

@@ -0,0 +1,46 @@
package com.hibiscusmc.hmccosmetics.user;
import com.google.common.collect.HashBiMap;
import com.hibiscusmc.hmccosmetics.util.ServerUtils;
import net.minecraft.world.entity.EntityType;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.Nullable;
import java.util.UUID;
public class CosmeticUsers {
private static HashBiMap<UUID, CosmeticUser> COSMETIC_USERS = HashBiMap.create();
public static void addUser(CosmeticUser user) {
if (COSMETIC_USERS.containsKey(user.getUniqueId())) return; // do not add if already exists
COSMETIC_USERS.put(user.getUniqueId(), user);
}
public static void removeUser(UUID uuid) {
COSMETIC_USERS.remove(uuid);
}
public static void removeUser(CosmeticUser user) {
COSMETIC_USERS.remove(user);
}
@Nullable
public static CosmeticUser getUser(UUID uuid) {
return COSMETIC_USERS.get(uuid);
}
@Nullable
public static CosmeticUser getUser(Player player) {
return COSMETIC_USERS.get(player.getUniqueId());
}
@Nullable
public static CosmeticUser getUser(int entityId) {
Entity entity = ServerUtils.getEntity(entityId);
if (entity == null) return null;
if (entity.getType().equals(EntityType.PLAYER)) return null;
return COSMETIC_USERS.get(entity.getUniqueId());
}
}

View File

@@ -0,0 +1,198 @@
package com.hibiscusmc.hmccosmetics.user;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.config.Settings;
import com.hibiscusmc.hmccosmetics.config.WardrobeSettings;
import com.hibiscusmc.hmccosmetics.cosmetic.CosmeticSlot;
import com.hibiscusmc.hmccosmetics.util.ServerUtils;
import com.hibiscusmc.hmccosmetics.util.packets.PacketManager;
import net.minecraft.world.entity.Entity;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
public class Wardrobe {
private int NPC_ID;
private UUID WARDROBE_UUID;
private int ARMORSTAND_ID;
private GameMode originalGamemode;
private CosmeticUser VIEWER;
private Location viewingLocation;
private Location npcLocation;
private Location exitLocation;
private boolean active;
public Wardrobe(CosmeticUser user) {
NPC_ID = Entity.nextEntityId();
ARMORSTAND_ID = Entity.nextEntityId();
WARDROBE_UUID = UUID.randomUUID();
VIEWER = user;
}
public void start() {
Player player = VIEWER.getPlayer();
player.sendMessage("start");
player.sendMessage("NPC ID " + NPC_ID);
player.sendMessage("armorstand id " + ARMORSTAND_ID);
this.originalGamemode = player.getGameMode();
if (WardrobeSettings.isReturnLastLocation()) {
this.exitLocation = player.getLocation().clone();
} else {
this.exitLocation = WardrobeSettings.getLeaveLocation();
}
VIEWER.hidePlayer();
List<Player> viewer = List.of(player);
// Armorstand
PacketManager.sendEntitySpawnPacket(WardrobeSettings.getViewerLocation(), ARMORSTAND_ID, EntityType.ARMOR_STAND, UUID.randomUUID(), viewer);
PacketManager.sendInvisibilityPacket(ARMORSTAND_ID, viewer);
PacketManager.sendLookPacket(ARMORSTAND_ID, WardrobeSettings.getViewerLocation(), viewer);
// Player
PacketManager.gamemodeChangePacket(player, 3);
PacketManager.sendCameraPacket(ARMORSTAND_ID, viewer);
// NPC
PacketManager.sendFakePlayerInfoPacket(player, NPC_ID, WARDROBE_UUID, viewer);
// NPC 2
Bukkit.getScheduler().runTaskLater(HMCCosmeticsPlugin.getInstance(), () -> {
PacketManager.sendFakePlayerSpawnPacket(WardrobeSettings.getWardrobeLocation(), WARDROBE_UUID, NPC_ID, viewer);
HMCCosmeticsPlugin.getInstance().getLogger().info("Spawned Fake Player on " + WardrobeSettings.getWardrobeLocation());
}, 4);
// Location
PacketManager.sendLookPacket(NPC_ID, WardrobeSettings.getWardrobeLocation(), viewer);
PacketManager.sendRotationPacket(NPC_ID, WardrobeSettings.getWardrobeLocation(), true, viewer);
// Misc
if (VIEWER.hasCosmeticInSlot(CosmeticSlot.BACKPACK)) {
PacketManager.ridingMountPacket(NPC_ID, VIEWER.getBackpackEntity().getId(), viewer);
}
if (VIEWER.hasCosmeticInSlot(CosmeticSlot.BALLOON)) {
PacketManager.sendLeashPacket(VIEWER.getBalloonEntity().getPufferfishBalloonId(), player.getEntityId(), viewer);
PacketManager.sendLeashPacket(VIEWER.getBalloonEntity().getPufferfishBalloonId(), NPC_ID, viewer);
PacketManager.sendTeleportPacket(VIEWER.getBalloonEntity().getPufferfishBalloonId(), WardrobeSettings.getWardrobeLocation(), false, viewer);
PacketManager.sendTeleportPacket(VIEWER.getBalloonEntity().getModelId(), WardrobeSettings.getWardrobeLocation().add(Settings.getBalloonOffset()), false, viewer);
}
this.active = true;
update();
}
public void end() {
this.active = false;
Player player = VIEWER.getPlayer();
player.sendMessage("end");
player.sendMessage("NPC ID " + NPC_ID);
player.sendMessage("armorstand id " + ARMORSTAND_ID);
List<Player> viewer = List.of(player);
// NPC
PacketManager.sendEntityDestroyPacket(NPC_ID, viewer); // Success
PacketManager.sendRemovePlayerPacket(player, player.getUniqueId(), viewer); // Success
// Player
PacketManager.sendCameraPacket(player.getEntityId(), viewer);
PacketManager.gamemodeChangePacket(player, ServerUtils.convertGamemode(this.originalGamemode)); // Success
// Armorstand
PacketManager.sendEntityDestroyPacket(ARMORSTAND_ID, viewer); // Sucess
//PacketManager.sendEntityDestroyPacket(player.getEntityId(), viewer); // Success
player.setGameMode(this.originalGamemode);
VIEWER.showPlayer();
if (VIEWER.hasCosmeticInSlot(CosmeticSlot.BACKPACK)) {
PacketManager.ridingMountPacket(player.getEntityId(), VIEWER.getBackpackEntity().getId(), viewer);
}
if (VIEWER.hasCosmeticInSlot(CosmeticSlot.BALLOON)) {
PacketManager.sendLeashPacket(VIEWER.getBalloonEntity().getPufferfishBalloonId(), player.getEntityId(), viewer);
}
if (exitLocation == null) {
player.teleport(player.getWorld().getSpawnLocation());
} else {
player.teleport(exitLocation);
}
if (!player.isOnline()) return;
VIEWER.updateCosmetic();
}
public void update() {
final AtomicInteger data = new AtomicInteger();
BukkitRunnable runnable = new BukkitRunnable() {
@Override
public void run() {
if (active == false) {
HMCCosmeticsPlugin.getInstance().getLogger().info("Active is false");
this.cancel();
return;
}
HMCCosmeticsPlugin.getInstance().getLogger().info("Update ");
List<Player> viewer = List.of(VIEWER.getPlayer());
Location location = WardrobeSettings.getWardrobeLocation().clone();
int yaw = data.get();
location.setYaw(yaw);
PacketManager.sendLookPacket(NPC_ID, location, viewer);
VIEWER.updateCosmetic();
int rotationSpeed = WardrobeSettings.getRotationSpeed();
location.setYaw(getNextYaw(yaw - 30, rotationSpeed));
PacketManager.sendRotationPacket(NPC_ID, location, true, viewer);
int nextyaw = getNextYaw(yaw, rotationSpeed);
data.set(nextyaw);
for (CosmeticSlot slot : CosmeticSlot.values()) {
PacketManager.equipmentSlotUpdate(NPC_ID, VIEWER, slot, viewer);
}
if (VIEWER.hasCosmeticInSlot(CosmeticSlot.BACKPACK)) {
PacketManager.sendTeleportPacket(VIEWER.getArmorstandId(), location, false, viewer);
PacketManager.ridingMountPacket(NPC_ID, VIEWER.getBackpackEntity().getId(), viewer);
VIEWER.getBackpackEntity().getBukkitEntity().setRotation(nextyaw, 0);
}
if (VIEWER.hasCosmeticInSlot(CosmeticSlot.BALLOON)) {
PacketManager.sendTeleportPacket(VIEWER.getBalloonEntity().getPufferfishBalloonId(), WardrobeSettings.getWardrobeLocation(), false, viewer);
VIEWER.getBalloonEntity().getModelEntity().getBukkitLivingEntity().teleport(WardrobeSettings.getWardrobeLocation().add(Settings.getBalloonOffset()));
//PacketManager.sendLeashPacket(VIEWER.getBalloonEntity().getPufferfishBalloonId(), NPC_ID, viewer);
}
}
};
runnable.runTaskTimer(HMCCosmeticsPlugin.getInstance(), 0, 2);
}
private static int getNextYaw(final int current, final int rotationSpeed) {
int nextYaw = current + rotationSpeed;
if (nextYaw > 179) {
nextYaw = (current + rotationSpeed) - 358;
return nextYaw;
}
return nextYaw;
}
public int getArmorstandId() {
return ARMORSTAND_ID;
}
}

View File

@@ -0,0 +1,128 @@
package com.hibiscusmc.hmccosmetics.util;
import com.comphenix.protocol.wrappers.EnumWrappers;
import com.hibiscusmc.hmccosmetics.cosmetic.CosmeticSlot;
import org.bukkit.inventory.EquipmentSlot;
import org.jetbrains.annotations.Nullable;
public class InventoryUtils {
/**
* Converts from the Bukkit item slots to ProtocolLib item slots. Will produce a null if an improper bukkit item slot is sent through
* @param slot The BUKKIT item slot to convert.
* @return The ProtocolLib item slot that is returned
*/
public static EnumWrappers.ItemSlot itemBukkitSlot(final EquipmentSlot slot) {
return switch (slot) {
case HEAD -> EnumWrappers.ItemSlot.HEAD;
case CHEST -> EnumWrappers.ItemSlot.CHEST;
case LEGS -> EnumWrappers.ItemSlot.LEGS;
case FEET -> EnumWrappers.ItemSlot.FEET;
case HAND -> EnumWrappers.ItemSlot.MAINHAND;
case OFF_HAND -> EnumWrappers.ItemSlot.OFFHAND;
};
}
private static int getPacketArmorSlot(final EquipmentSlot slot) {
return switch (slot) {
case HEAD -> 5;
case CHEST -> 6;
case LEGS -> 7;
case FEET -> 8;
case OFF_HAND -> 45;
default -> -1;
};
}
@Nullable
public static EquipmentSlot getPacketArmorSlot(final int slot) {
return switch (slot) {
case 5 -> EquipmentSlot.HEAD;
case 6 -> EquipmentSlot.CHEST;
case 7 -> EquipmentSlot.LEGS;
case 8 -> EquipmentSlot.FEET;
case 45 -> EquipmentSlot.OFF_HAND;
default -> null;
};
}
public static CosmeticSlot BukkitCosmeticSlot(EquipmentSlot slot) {
return switch (slot) {
case OFF_HAND -> CosmeticSlot.OFFHAND;
case FEET -> CosmeticSlot.BOOTS;
case LEGS -> CosmeticSlot.LEGGINGS;
case CHEST -> CosmeticSlot.CHESTPLATE;
case HEAD -> CosmeticSlot.HELMET;
default -> null;
};
}
public static CosmeticSlot BukkitCosmeticSlot(int slot) {
switch (slot) {
case 39 -> {
return CosmeticSlot.HELMET;
}
case 38 -> {
return CosmeticSlot.CHESTPLATE;
}
case 37 -> {
return CosmeticSlot.LEGGINGS;
}
case 36 -> {
return CosmeticSlot.BOOTS;
}
case 40 -> {
return CosmeticSlot.OFFHAND;
}
default -> {
return null;
}
}
}
public static CosmeticSlot NMSCosmeticSlot(int slot) {
switch (slot) {
case 5 -> {
return CosmeticSlot.HELMET;
}
case 6 -> {
return CosmeticSlot.CHESTPLATE;
}
case 7 -> {
return CosmeticSlot.LEGGINGS;
}
case 8 -> {
return CosmeticSlot.BOOTS;
}
case 45 -> {
return CosmeticSlot.OFFHAND;
}
default -> {
return null;
}
}
}
public static EquipmentSlot getEquipmentSlot(CosmeticSlot slot) {
switch (slot) {
case HELMET -> {
return EquipmentSlot.HEAD;
}
case CHESTPLATE -> {
return EquipmentSlot.CHEST;
}
case LEGGINGS -> {
return EquipmentSlot.LEGS;
}
case BOOTS -> {
return EquipmentSlot.FEET;
}
case OFFHAND -> {
return EquipmentSlot.OFF_HAND;
}
default -> {
return null;
}
}
}
}

View File

@@ -0,0 +1,37 @@
package com.hibiscusmc.hmccosmetics.util;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import com.comphenix.protocol.wrappers.WrappedSignedProperty;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class PlayerUtils {
public static WrappedSignedProperty getSkin(Player player) {
WrappedSignedProperty skinData = WrappedGameProfile.fromPlayer(player).getProperties()
.get("textures").stream().findAny().orElse(null);
if (skinData == null) {
return null;
}
return new WrappedSignedProperty("textures", skinData.getValue(), skinData.getSignature());
}
public static List<Player> getNearbyPlayers(Player player) {
return getNearbyPlayers(player.getLocation());
}
public static List<Player> getNearbyPlayers(Location location) {
List<Player> players = new ArrayList<>();
for (Entity entity : location.getWorld().getNearbyEntities(location, 32, 32, 32)) {
if (entity instanceof Player) {
players.add((Player) entity);
}
}
return players;
}
}

View File

@@ -0,0 +1,40 @@
package com.hibiscusmc.hmccosmetics.util;
import net.minecraft.server.level.ServerLevel;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.craftbukkit.v1_19_R1.CraftServer;
import org.jetbrains.annotations.Nullable;
public class ServerUtils {
/**
* Converts a bukkit gamemode into an integer for use in packets
* @param gamemode Bukkit gamemode to convert.
* @return int of the gamemode
*/
public static int convertGamemode(final GameMode gamemode) {
return switch (gamemode) {
case SURVIVAL -> 0;
case CREATIVE -> 1;
case ADVENTURE -> 2;
case SPECTATOR -> 3;
};
}
@Nullable
public static org.bukkit.entity.Entity getEntity(int entityId) {
net.minecraft.world.entity.Entity entity = getNMSEntity(entityId);
if (entity == null) return null;
return entity.getBukkitEntity();
}
@Nullable
public static net.minecraft.world.entity.Entity getNMSEntity(int entityId) {
for (ServerLevel world : ((CraftServer) Bukkit.getServer()).getHandle().getServer().getAllLevels()) {
net.minecraft.world.entity.Entity entity = world.getEntity(entityId);
if (entity == null) return null;
return entity;
}
return null;
}
}

View File

@@ -0,0 +1,38 @@
package com.hibiscusmc.hmccosmetics.util.builder;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.PotionMeta;
public class ColorBuilder {
public static boolean canBeColored(final Material material) {
return canBeColored(new ItemStack(material));
}
public static boolean canBeColored(final ItemStack itemStack) {
final ItemMeta itemMeta = itemStack.getItemMeta();
return (itemMeta instanceof LeatherArmorMeta ||
itemMeta instanceof PotionMeta);
}
/**
* @param color armor color
* @return this
*/
public static ItemMeta color(ItemMeta itemMeta, final Color color) {
if (itemMeta instanceof final PotionMeta meta) {
meta.setColor(color);
}
if (itemMeta instanceof final LeatherArmorMeta meta) {
meta.setColor(color);
}
return itemMeta;
}
}

View File

@@ -0,0 +1,256 @@
package com.hibiscusmc.hmccosmetics.util.builder;
import com.hibiscusmc.hmccosmetics.util.misc.Placeholder;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ItemBuilder {
protected Material material;
protected int amount;
protected ItemMeta itemMeta;
/**
* @param material builder material
*/
ItemBuilder(final Material material) {
this.material = material;
this.itemMeta = Bukkit.getItemFactory().getItemMeta(material);
}
/**
* @param itemStack builder ItemStack
*/
ItemBuilder(final ItemStack itemStack) {
this.material = itemStack.getType();
this.itemMeta = itemStack.hasItemMeta() ? itemStack.getItemMeta()
: Bukkit.getItemFactory().getItemMeta(this.material);
}
/**
* @param material builder material
* @return
*/
public static ItemBuilder from(final Material material) {
return new ItemBuilder(material);
}
/**
* @param itemStack builder ItemStack
* @return
*/
public static ItemBuilder from(final ItemStack itemStack) {
return new ItemBuilder(itemStack);
}
/**
* @param amount ItemStack amount
* @return this
*/
public ItemBuilder amount(final int amount) {
this.amount = Math.min(Math.max(1, amount), 64);
return this;
}
/**
* @param name ItemStack name
* @return this
*/
public ItemBuilder name(final String name) {
if (this.itemMeta == null) {
return this;
}
this.itemMeta.setDisplayName(name);
return this;
}
/**
* Sets placeholders to the item's name
*
* @param placeholders placeholders
*/
public ItemBuilder namePlaceholders(final Map<String, String> placeholders) {
if (this.itemMeta == null) {
return this;
}
final String name = Placeholder.
applyPlaceholders(this.itemMeta.getDisplayName(), placeholders);
this.itemMeta.setDisplayName(name);
return this;
}
/**
* @param lore ItemStack lore
* @return this
*/
public ItemBuilder lore(final List<String> lore) {
if (this.itemMeta == null) {
return this;
}
this.itemMeta.setLore(lore);
return this;
}
/**
* Sets placeholders to the item's lore
*
* @param placeholders placeholders
*/
public ItemBuilder lorePlaceholders(final Map<String, String> placeholders) {
if (this.itemMeta == null) {
return this;
}
final List<String> lore = new ArrayList<>();
final List<String> previousLore = this.itemMeta.getLore();
if (previousLore == null) {
return this;
}
for (final String line : previousLore) {
lore.add(Placeholder.applyPlaceholders(
line, placeholders
));
}
this.itemMeta.setLore(lore);
return this;
}
public ItemBuilder papiPlaceholders(final Player player) {
this.lorePapiPlaceholders(player);
this.namePapiPlaceholders(player);
return this;
}
private void lorePapiPlaceholders(final Player player) {
if (this.itemMeta == null) {
return;
}
final List<String> newLore = new ArrayList<>();
final List<String> lore = this.itemMeta.getLore();
if (lore == null) {
return;
}
for (final String line : this.itemMeta.getLore()) {
newLore.add(Placeholder.applyPapiPlaceholders(player, line));
}
this.itemMeta.setLore(newLore);
}
private void namePapiPlaceholders(final Player player) {
if (this.itemMeta == null) {
return;
}
this.itemMeta.setDisplayName(
Placeholder.applyPapiPlaceholders(
player,
this.itemMeta.getDisplayName()
)
);
}
/**
* @param unbreakable whether the ItemStack is unbreakable
* @return this
*/
public ItemBuilder unbreakable(final boolean unbreakable) {
if (this.itemMeta == null) {
return this;
}
this.itemMeta.setUnbreakable(unbreakable);
return this;
}
public ItemBuilder glow(final boolean glow) {
if (this.itemMeta == null) {
return this;
}
if (glow) {
this.itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
this.itemMeta.addEnchant(Enchantment.LUCK, 1, true);
}
return this;
}
/**
* @param enchantments enchants to be added to the ItemStack
* @param ignoreLeveLRestrictions whether to ignore enchantment level restrictions
* @return this
*/
public ItemBuilder enchants(final Map<Enchantment, Integer> enchantments,
boolean ignoreLeveLRestrictions) {
if (this.itemMeta == null) {
return this;
}
enchantments.forEach((enchantment, level) -> this.itemMeta.addEnchant(enchantment, level,
ignoreLeveLRestrictions));
return this;
}
/**
* @param itemFlags ItemStack ItemFlags
* @return this
*/
public ItemBuilder itemFlags(final Set<ItemFlag> itemFlags) {
if (this.itemMeta == null) {
return this;
}
this.itemMeta.addItemFlags(itemFlags.toArray(new ItemFlag[0]));
return this;
}
/**
* @param modelData ItemStack modelData
* @return this
*/
public ItemBuilder modelData(final int modelData) {
if (this.itemMeta == null) {
return this;
}
this.itemMeta.setCustomModelData(modelData);
return this;
}
/**
* @return built ItemStack
*/
public ItemStack build() {
final ItemStack itemStack = new ItemStack(this.material, Math.max(this.amount, 1));
itemStack.setItemMeta(itemMeta);
return itemStack;
}
}

View File

@@ -0,0 +1,18 @@
package com.hibiscusmc.hmccosmetics.util.misc;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.standard.StandardTags;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
public class Adventure {
public static final LegacyComponentSerializer SERIALIZER = LegacyComponentSerializer.builder()
.hexColors()
.useUnusualXRepeatedCharacterHexFormat()
.build();
public static final MiniMessage MINI_MESSAGE = MiniMessage.builder().tags(
StandardTags.defaults()
).
build();
}

View File

@@ -0,0 +1,74 @@
package com.hibiscusmc.hmccosmetics.util.misc;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import org.checkerframework.checker.nullness.qual.Nullable;
public class Keys {
static HMCCosmeticsPlugin plugin = HMCCosmeticsPlugin.getInstance();
public static final NamespacedKey ITEM_KEY = new NamespacedKey(plugin, "cosmetic");
public static final NamespacedKey TOKEN_KEY = new NamespacedKey(plugin, "token-key");
public static void setKey(final ItemStack itemStack) {
final ItemMeta itemMeta = itemStack.getItemMeta();
if (itemMeta == null) {
return;
}
itemMeta.getPersistentDataContainer().set(ITEM_KEY, PersistentDataType.BYTE, (byte) 1);
itemStack.setItemMeta(itemMeta);
}
public static <T, Z> void setKey(
final ItemStack itemStack,
final NamespacedKey key,
final PersistentDataType<T, Z> type,
final Z value) {
final ItemMeta itemMeta = itemStack.getItemMeta();
if (itemMeta == null) {
return;
}
itemMeta.getPersistentDataContainer().set(key, type, value);
itemStack.setItemMeta(itemMeta);
}
public static boolean hasKey(final ItemStack itemStack) {
final ItemMeta itemMeta = itemStack.getItemMeta();
if (itemMeta == null) {
return false;
}
return itemMeta.getPersistentDataContainer().has(ITEM_KEY, PersistentDataType.BYTE);
}
public static <T, Z> boolean hasKey(final ItemStack itemStack, final NamespacedKey key, final PersistentDataType<T, Z> type) {
final ItemMeta itemMeta = itemStack.getItemMeta();
if (itemMeta == null) {
return false;
}
return itemMeta.getPersistentDataContainer().has(key, type);
}
@Nullable
public static <T, Z> Z getValue(final ItemStack itemStack, final NamespacedKey key, final PersistentDataType<T, Z> type) {
final ItemMeta itemMeta = itemStack.getItemMeta();
if (itemMeta == null) {
return null;
}
return itemMeta.getPersistentDataContainer().get(key, type);
}
}

View File

@@ -0,0 +1,44 @@
package com.hibiscusmc.hmccosmetics.util.misc;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
public class Placeholder {
public static final String PREFIX = "%prefix%";
public static final String TYPE = "%type%";
public static final String ITEM = "%item%";
public static final String FILE = "%file%";
public static final String PLAYER = "%player%";
public static final String ENABLED = "%enabled%";
public static final String ALLOWED = "%allowed%";
public static final String ID = "%id%";
/**
* @param message message being translated
* @param placeholders placeholders applied
* @return message with placeholders applied
*/
public static String applyPlaceholders(String message, final Map<String, String> placeholders) {
for (final Map.Entry<String, String> entry : placeholders.entrySet()) {
message = message.replace(entry.getKey(), Translation.translate(entry.getValue()));
}
return message;
}
public static String applyPapiPlaceholders(@Nullable final Player player,
final String message) {
/*
if (HookManager.getInstance().isEnabled(PAPIHook.class)) {
return HookManager.getInstance().getPapiHook().parse(player, message);
}
*/
return message;
}
}

View File

@@ -0,0 +1,33 @@
package com.hibiscusmc.hmccosmetics.util.misc;
import net.kyori.adventure.text.Component;
public class StringUtils {
/**
* @param parsed message to be parsed
* @return MiniMessage parsed string
*/
public static Component parse(final String parsed) {
return Adventure.MINI_MESSAGE.deserialize(parsed);
}
public static String parseStringToString(final String parsed) {
return Adventure.SERIALIZER.serialize(Adventure.MINI_MESSAGE.deserialize(parsed));
}
public static String formatArmorItemType(String type) {
type = type.toLowerCase();
final String[] parts = type.split(" ");
final String firstPart = parts[0].substring(0, 1).toUpperCase() + parts[0].substring(1);
if (parts.length == 1) {
return firstPart;
}
return firstPart + parts[1].substring(0, 1).toUpperCase() + parts[1].substring(1);
}
}

View File

@@ -0,0 +1,47 @@
package com.hibiscusmc.hmccosmetics.util.misc;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class Translation {
public static final String TRUE = "true";
public static final String FALSE = "false";
public static final String NONE = "none";
private static final String FILE_NAME = "translations.yml";
private static final String TRANSLATION_PATH = "translations";
private static Map<String, String> translations;
public static String translate(final String key) {
return translations.getOrDefault(key, null);
}
public static void setup() {
final File file = new File(HMCCosmeticsPlugin.getInstance().getDataFolder(), FILE_NAME);
if (!file.exists()) {
HMCCosmeticsPlugin.getInstance().saveResource(FILE_NAME, false);
}
if (translations == null) {
translations = new HashMap<>();
}
final FileConfiguration config = YamlConfiguration.loadConfiguration(file);
final ConfigurationSection section = config.getConfigurationSection(TRANSLATION_PATH);
if (section == null) {
return;
}
for (final String key : section.getKeys(false)) {
translations.put(key, section.getString(key));
}
}
}

View File

@@ -0,0 +1,118 @@
package com.hibiscusmc.hmccosmetics.util.misc;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
public class Utils {
/**
* @param original Object to be checked if null
* @param replacement Object returned if original is null
* @return original if not null, otherwise replacement
*/
public static <T> T replaceIfNull(final @Nullable T original, final @NotNull T replacement) {
return replaceIfNull(original, replacement, t -> {
});
}
@SafeVarargs
public static <T> T replaceIf(final @Nullable T original, final T replacement, final @Nullable T... checks) {
for (final T check : checks) {
if (original == check) return replacement;
}
return original;
}
public static <T> T replaceIf(final @Nullable T original, final T replacement, final Predicate<T> predicate) {
if (predicate.test(original)) return replacement;
return original;
}
/**
* @param original Object to be checked if null
* @param replacement Object returned if original is null
* @param consumer accepts the original object, can be used for logging
* @return original if not null, otherwise replacement
*/
public static <T> T replaceIfNull(final @Nullable T original, final T replacement,
final @NotNull Consumer<T> consumer) {
if (original == null) {
consumer.accept(replacement);
return replacement;
}
consumer.accept(original);
return original;
}
/**
* @param t object being checked
* @param consumer accepted if t is not null
* @param <T> type
*/
public static <T> void doIfNotNull(final @Nullable T t, final @NotNull Consumer<T> consumer) {
if (t == null) {
return;
}
consumer.accept(t);
}
/**
* @param t object being checked
* @param function applied if t is not null
* @param <T> type
* @return
*/
public static <T> Optional<T> returnIfNotNull(final @Nullable T t,
final @NotNull Function<T, T> function) {
if (t == null) {
return Optional.empty();
}
return Optional.of(function.apply(t));
}
/**
* @param enumAsString Enum value as a string to be parsed
* @param enumClass enum type enumAsString is to be converted to
* @param defaultEnum default value to be returned
* @return enumAsString as an enum, or default enum if it could not be parsed
*/
public static <E extends Enum<E>> E stringToEnum(final @NotNull String enumAsString,
final @NotNull Class<E> enumClass,
E defaultEnum) {
return stringToEnum(enumAsString, enumClass, defaultEnum, e -> {
});
}
/**
* @param enumAsString Enum value as a string to be parsed
* @param enumClass enum type enumAsString is to be converted to
* @param defaultEnum default value to be returned
* @param consumer accepts the returned enum, can be used for logging
* @return enumAsString as an enum, or default enum if it could not be parsed
*/
public static <E extends Enum<E>> E stringToEnum(final @NotNull String enumAsString,
@NotNull final Class<E> enumClass,
final E defaultEnum,
final @NotNull Consumer<E> consumer) {
try {
final E value = Enum.valueOf(enumClass, enumAsString);
consumer.accept(value);
return value;
} catch (final IllegalArgumentException exception) {
consumer.accept(defaultEnum);
return defaultEnum;
}
}
}

View File

@@ -0,0 +1,22 @@
package com.hibiscusmc.hmccosmetics.util.packets;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketContainer;
import net.minecraft.network.protocol.Packet;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ServerPlayerConnection;
import org.bukkit.craftbukkit.v1_19_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
public class BasePacket {
public static void sendPacket(Player player, Packet<?> packet) {
ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle();
ServerPlayerConnection connection = serverPlayer.connection;
connection.send(packet);
}
public static void sendPacket(Player player, PacketContainer packet) {
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false);
}
}

View File

@@ -0,0 +1,399 @@
package com.hibiscusmc.hmccosmetics.util.packets;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.*;
import com.hibiscusmc.hmccosmetics.HMCCosmeticsPlugin;
import com.hibiscusmc.hmccosmetics.cosmetic.CosmeticSlot;
import com.hibiscusmc.hmccosmetics.cosmetic.types.CosmeticArmorType;
import com.hibiscusmc.hmccosmetics.user.CosmeticUser;
import com.hibiscusmc.hmccosmetics.user.CosmeticUsers;
import com.hibiscusmc.hmccosmetics.util.InventoryUtils;
import com.hibiscusmc.hmccosmetics.util.PlayerUtils;
import com.hibiscusmc.hmccosmetics.util.packets.wrappers.WrapperPlayServerNamedEntitySpawn;
import com.hibiscusmc.hmccosmetics.util.packets.wrappers.WrapperPlayServerPlayerInfo;
import com.mojang.datafixers.util.Pair;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import net.minecraft.network.protocol.game.ClientboundGameEventPacket;
import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.item.ItemStack;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_19_R1.CraftEquipmentSlot;
import org.bukkit.craftbukkit.v1_19_R1.inventory.CraftItemStack;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
public class PacketManager extends BasePacket {
public static void sendEntitySpawnPacket(
final Location location,
final int entityId,
final EntityType entityType,
final UUID uuid,
final List<Player> sendTo
) {
PacketContainer packet = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY);
packet.getModifier().writeDefaults();
packet.getUUIDs().write(0, uuid);
packet.getIntegers().write(0, entityId);
packet.getEntityTypeModifier().write(0, entityType);
packet.getDoubles().
write(0, location.getX()).
write(1, location.getY()).
write(2, location.getZ());
for (Player p : sendTo) sendPacket(p, packet);
}
public static void gamemodeChangePacket(
Player player,
int gamemode
) {
sendPacket(player, new ClientboundGameEventPacket(ClientboundGameEventPacket.CHANGE_GAME_MODE, (float) gamemode));
HMCCosmeticsPlugin.getInstance().getLogger().info("Gamemode Change sent to " + player + " to be " + gamemode);
}
public static void ridingMountPacket(
int mountId,
int passengerId,
List<Player> sendTo
) {
PacketContainer packet = new PacketContainer(PacketType.Play.Server.MOUNT);
packet.getIntegers().write(0, mountId);
packet.getIntegerArrays().write(0, new int[]{passengerId});
for (Player p : sendTo) sendPacket(p, packet);
}
public static void equipmentSlotUpdate(
Player player,
CosmeticSlot cosmetic,
List<Player> sendTo
) {
CosmeticUser user = CosmeticUsers.getUser(player.getUniqueId());
equipmentSlotUpdate(player.getEntityId(), user, cosmetic, sendTo);
}
public static void equipmentSlotUpdate(
CosmeticUser user,
CosmeticSlot cosmeticSlot,
List<Player> sendTo
) {
equipmentSlotUpdate(user.getPlayer().getEntityId(), user, cosmeticSlot, sendTo);
}
public static void equipmentSlotUpdate(
int entityId,
CosmeticUser user,
CosmeticSlot cosmeticSlot,
List<Player> sendTo
) {
EquipmentSlot nmsSlot = null;
ItemStack nmsItem = null;
if (cosmeticSlot == CosmeticSlot.BACKPACK || cosmeticSlot == CosmeticSlot.BALLOON) return;
if (!(user.getCosmetic(cosmeticSlot) instanceof CosmeticArmorType)) {
nmsSlot = CraftEquipmentSlot.getNMS(InventoryUtils.getEquipmentSlot(cosmeticSlot));
nmsItem = CraftItemStack.asNMSCopy(new org.bukkit.inventory.ItemStack(Material.AIR));
Pair<EquipmentSlot, ItemStack> pair = new Pair<>(nmsSlot, nmsItem);
List<Pair<EquipmentSlot, ItemStack>> pairs = Collections.singletonList(pair);
ClientboundSetEquipmentPacket packet = new ClientboundSetEquipmentPacket(entityId, pairs);
for (Player p : sendTo) sendPacket(p, packet);
return;
}
CosmeticArmorType cosmeticArmor = (CosmeticArmorType) user.getCosmetic(cosmeticSlot);
// Converting EquipmentSlot and ItemStack to NMS ones.
nmsSlot = CraftEquipmentSlot.getNMS(cosmeticArmor.getEquipSlot());
nmsItem = CraftItemStack.asNMSCopy(user.getUserCosmeticItem(cosmeticArmor));
if (nmsSlot == null) return;
Pair<EquipmentSlot, ItemStack> pair = new Pair<>(nmsSlot, nmsItem);
List<Pair<EquipmentSlot, ItemStack>> pairs = Collections.singletonList(pair);
ClientboundSetEquipmentPacket packet = new ClientboundSetEquipmentPacket(entityId, pairs);
for (Player p : sendTo) sendPacket(p, packet);
}
public static void armorStandMetaPacket(
Entity entity,
List<Player> sendTo
) {
PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA);
packet.getModifier().writeDefaults();
packet.getIntegers().write(0, entity.getEntityId());
WrappedDataWatcher metadata = new WrappedDataWatcher();
if (metadata == null) return;
// 0x10 & 0x20
metadata.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(0, WrappedDataWatcher.Registry.get(Byte.class)), (byte) 0x20);
metadata.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(15, WrappedDataWatcher.Registry.get(Byte.class)), (byte) 0x10);
packet.getWatchableCollectionModifier().write(0, metadata.getWatchableObjects());
for (Player p : sendTo) sendPacket(p, packet);
}
public static void sendInvisibilityPacket(
int entityId,
List<Player> sendTo
) {
PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA);
packet.getModifier().writeDefaults();
packet.getIntegers().write(0, entityId);
WrappedDataWatcher wrapper = new WrappedDataWatcher();
wrapper.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(0, WrappedDataWatcher.Registry.get(Byte.class)), (byte) 0x20);
packet.getWatchableCollectionModifier().write(0, wrapper.getWatchableObjects());
for (Player p : sendTo) sendPacket(p, packet);
}
public static void sendLookPacket(
int entityId,
Location location,
List<Player> sendTo
) {
PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_HEAD_ROTATION);
packet.getIntegers().write(0, entityId);
packet.getBytes().write(0, (byte) (location.getYaw() * 256.0F / 360.0F));
for (Player p : sendTo) sendPacket(p, packet);
}
public static void sendRotationPacket(
int entityId,
Location location,
boolean onGround,
List<Player> sendTo
) {
float ROTATION_FACTOR = 256.0F / 360.0F;
float yaw = location.getYaw() * ROTATION_FACTOR;
float pitch = location.getPitch() * ROTATION_FACTOR;
PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_LOOK);
packet.getIntegers().write(0, entityId);
packet.getBytes().write(0, (byte) yaw);
packet.getBytes().write(1, (byte) pitch);
//Bukkit.getLogger().info("DEBUG: Yaw: " + (location.getYaw() * ROTATION_FACTOR) + " | Original Yaw: " + location.getYaw());
packet.getBooleans().write(0, onGround);
for (Player p : sendTo) sendPacket(p, packet);
}
public static void sendRotationPacket(
int entityId,
int yaw,
boolean onGround,
List<Player> sendTo
) {
float ROTATION_FACTOR = 256.0F / 360.0F;
float yaw2 = yaw * ROTATION_FACTOR;
PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_LOOK);
packet.getIntegers().write(0, entityId);
packet.getBytes().write(0, (byte) yaw2);
packet.getBytes().write(1, (byte) 0);
//Bukkit.getLogger().info("DEBUG: Yaw: " + (location.getYaw() * ROTATION_FACTOR) + " | Original Yaw: " + location.getYaw());
packet.getBooleans().write(0, onGround);
for (Player p : sendTo) sendPacket(p, packet);
}
/**
* Mostly to deal with backpacks, this deals with entities riding other entities.
* @param mountId The entity that is the "mount", ex. a player
* @param passengerId The entity that is riding the mount, ex. a armorstand for a backpack
* @param sendTo Whom to send the packet to
*/
public static void sendRidingPacket(
final int mountId,
final int passengerId,
final List<Player> sendTo
) {
PacketContainer packet = new PacketContainer(PacketType.Play.Server.MOUNT);
packet.getIntegers().write(0, mountId);
packet.getIntegerArrays().write(0, new int[]{passengerId});
for (final Player p : sendTo) {
sendPacket(p, packet);
}
}
/**
* Destroys an entity from a player
* @param entityId The entity to delete for a player
* @param sendTo The players the packet should be sent to
*/
public static void sendEntityDestroyPacket(final int entityId, List<Player> sendTo) {
PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY);
packet.getModifier().write(0, new IntArrayList(new int[]{entityId}));
for (final Player p : sendTo) sendPacket(p, packet);
}
/**
* Sends a camera packet
* @param entityId The Entity ID that camera will go towards
* @param sendTo The players that will be sent this packet
*/
public static void sendCameraPacket(final int entityId, List<Player> sendTo) {
PacketContainer packet = new PacketContainer(PacketType.Play.Server.CAMERA);
packet.getIntegers().write(0, entityId);
for (final Player p : sendTo) sendPacket(p, packet);
HMCCosmeticsPlugin.getInstance().getLogger().info(sendTo + " | " + entityId + " has had a camera packet on them!");
}
/**
*
* @param location Location of the fake player.
* @param uuid UUID of the fake player. Should be random.
* @param entityId The entityID that the entity will take on.
* @param sendTo Who should it send the packet to?
*/
public static void sendFakePlayerSpawnPacket(
final Location location,
final UUID uuid,
final int entityId,
final List<Player> sendTo
) {
WrapperPlayServerNamedEntitySpawn wrapper = new WrapperPlayServerNamedEntitySpawn();
wrapper.setEntityID(entityId);
wrapper.setPlayerUUID(uuid);
wrapper.setPosition(location.toVector());
wrapper.setPitch(location.getPitch());
wrapper.setYaw(location.getYaw());
for (final Player p : sendTo) sendPacket(p, wrapper.getHandle());
}
/**
* Creates a fake player entity.
* @param skinnedPlayer The original player it bases itself off of.
* @param uuid UUID of the fake entity.
* @param sendTo Whom to send the packet to
*/
public static void sendFakePlayerInfoPacket(
final Player skinnedPlayer,
final int entityId,
final UUID uuid,
final List<Player> sendTo
) {
WrapperPlayServerPlayerInfo info = new WrapperPlayServerPlayerInfo();
info.setAction(EnumWrappers.PlayerInfoAction.ADD_PLAYER);
String name = "Mannequin-" + entityId;
while (name.length() > 16) {
name = name.substring(16);
}
WrappedGameProfile wrappedGameProfile = new WrappedGameProfile(uuid, name);
WrappedSignedProperty skinData = PlayerUtils.getSkin(skinnedPlayer);
if (skinData != null) wrappedGameProfile.getProperties().put("textures", skinData);
info.setData(List.of(new PlayerInfoData(wrappedGameProfile, 0, EnumWrappers.NativeGameMode.CREATIVE, WrappedChatComponent.fromText(name))));
for (final Player p : sendTo) sendPacket(p, info.getHandle());
}
/**
* Generates the overlay packet for entities.
* @param playerId The entity the packet is about
* @param sendTo Whom is sent the packet.
*/
public static void sendPlayerOverlayPacket(
final int playerId,
final List<Player> sendTo
) {
/*
0x01 = Is on fire
0x02 = Is courching
0x04 = Unusued
0x08 = Sprinting
0x10 = Is swimming
0x20 = Invisibile
0x40 = Is Glowing
0x80 = Is flying with an elytra
https://wiki.vg/Entity_metadata#Entity
*/
final byte mask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x40;
PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA);
packet.getModifier().writeDefaults();
packet.getIntegers().write(0, playerId);
WrappedDataWatcher wrapper = new WrappedDataWatcher();
wrapper.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(17, WrappedDataWatcher.Registry.get(Byte.class)), mask);
wrapper.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(15, WrappedDataWatcher.Registry.get(Byte.class)), (byte) 0x10);
packet.getWatchableCollectionModifier().write(0, wrapper.getWatchableObjects());
for (final Player p : sendTo) {
sendPacket(p, packet);
}
}
/**
* Removes a fake player from being seen by players.
* @param player Which gameprofile to wrap for removing the player.
* @param uuid What is the fake player UUID
* @param sendTo Whom to send the packet to
*/
public static void sendRemovePlayerPacket(
final Player player,
final UUID uuid,
final List<Player> sendTo
) {
WrapperPlayServerPlayerInfo info = new WrapperPlayServerPlayerInfo();
info.setAction(EnumWrappers.PlayerInfoAction.REMOVE_PLAYER);
String name = "Mannequin-" + player.getEntityId();
while (name.length() > 16) {
name = name.substring(16);
}
info.setData(List.of(new PlayerInfoData(new WrappedGameProfile(uuid, player.getName()), 0, EnumWrappers.NativeGameMode.CREATIVE, WrappedChatComponent.fromText(name))));
for (final Player p : sendTo) sendPacket(p, info.getHandle());
}
/**
* Sends a leash packet, useful for balloons!
* @param leashedEntity Entity being leashed (ex. a horse)
* @param entityId Entity this is affecting (ex. a player)
* @param sendTo Whom to send the packet to
*/
public static void sendLeashPacket(
final int leashedEntity,
final int entityId,
final List<Player> sendTo
) {
for (final Player p : sendTo) {
PacketContainer packet = new PacketContainer(PacketType.Play.Server.ATTACH_ENTITY);
packet.getIntegers().write(0, leashedEntity);
packet.getIntegers().write(1, entityId);
sendPacket(p, packet);
}
}
/**
* Used when a player is sent 8+ blocks.
* @param entityId Entity this affects
* @param location Location a player is being teleported to
* @param onGround If the packet is on the ground
* @param sendTo Whom to send the packet to
*/
public static void sendTeleportPacket(
final int entityId,
final Location location,
boolean onGround,
final List<Player> sendTo
) {
PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_TELEPORT);
packet.getIntegers().write(0, entityId);
packet.getDoubles().write(0, location.getX());
packet.getDoubles().write(1, location.getY());
packet.getDoubles().write(2, location.getZ());
packet.getBytes().write(0, (byte) (location.getYaw() * 256.0F / 360.0F));
packet.getBytes().write(1, (byte) (location.getPitch() * 256.0F / 360.0F));
packet.getBooleans().write(0, onGround);
for (final Player p : sendTo) {
sendPacket(p, packet);
}
}
}

View File

@@ -0,0 +1,92 @@
package com.hibiscusmc.hmccosmetics.util.packets.wrappers;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketContainer;
import com.google.common.base.Objects;
import org.bukkit.entity.Player;
// Courtesy of Packet Wrapper
public class AbstractPacket {
// The packet we will be modifying
protected PacketContainer handle;
/**
* Constructs a new strongly typed wrapper for the given packet.
*
* @param handle - handle to the raw packet data.
* @param type - the packet type.
*/
protected AbstractPacket(PacketContainer handle, PacketType type) {
// Make sure we're given a valid packet
if (handle == null)
throw new IllegalArgumentException("Packet handle cannot be NULL.");
if (!Objects.equal(handle.getType(), type))
throw new IllegalArgumentException(handle.getHandle()
+ " is not a packet of type " + type);
this.handle = handle;
}
/**
* Retrieve a handle to the raw packet data.
*
* @return Raw packet data.
*/
public PacketContainer getHandle() {
return handle;
}
/**
* Send the current packet to the given receiver.
*
* @param receiver - the receiver.
* @throws RuntimeException If the packet cannot be sent.
*/
public void sendPacket(Player receiver) {
ProtocolLibrary.getProtocolManager().sendServerPacket(receiver,
getHandle());
}
/**
* Send the current packet to all online players.
*/
public void broadcastPacket() {
ProtocolLibrary.getProtocolManager().broadcastServerPacket(getHandle());
}
/**
* Simulate receiving the current packet from the given sender.
*
* @param sender - the sender.
* @throws RuntimeException If the packet cannot be received.
* @deprecated Misspelled. recieve to receive
* @see #receivePacket(Player)
*/
@Deprecated
public void recievePacket(Player sender) {
try {
ProtocolLibrary.getProtocolManager().receiveClientPacket(sender,
getHandle());
} catch (Exception e) {
throw new RuntimeException("Cannot recieve packet.", e);
}
}
/**
* Simulate receiving the current packet from the given sender.
*
* @param sender - the sender.
* @throws RuntimeException if the packet cannot be received.
*/
public void receivePacket(Player sender) {
try {
ProtocolLibrary.getProtocolManager().receiveClientPacket(sender,
getHandle());
} catch (Exception e) {
throw new RuntimeException("Cannot receive packet.", e);
}
}
}

View File

@@ -0,0 +1,164 @@
package com.hibiscusmc.hmccosmetics.util.packets.wrappers;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.util.Vector;
import java.util.UUID;
public class WrapperPlayServerNamedEntitySpawn extends AbstractPacket {
public static final PacketType TYPE =
PacketType.Play.Server.NAMED_ENTITY_SPAWN;
public WrapperPlayServerNamedEntitySpawn() {
super(new PacketContainer(TYPE), TYPE);
handle.getModifier().writeDefaults();
}
public WrapperPlayServerNamedEntitySpawn(PacketContainer packet) {
super(packet, TYPE);
}
/**
* Retrieve Entity ID.
* <p>
* Notes: entity's ID
*
* @return The current Entity ID
*/
public int getEntityID() {
return handle.getIntegers().read(0);
}
/**
* Set Entity ID.
*
* @param value - new value.
*/
public void setEntityID(int value) {
handle.getIntegers().write(0, value);
}
/**
* Retrieve the entity of the painting that will be spawned.
*
* @param world - the current world of the entity.
* @return The spawned entity.
*/
public Entity getEntity(World world) {
return handle.getEntityModifier(world).read(0);
}
/**
* Retrieve the entity of the painting that will be spawned.
*
* @param event - the packet event.
* @return The spawned entity.
*/
public Entity getEntity(PacketEvent event) {
return getEntity(event.getPlayer().getWorld());
}
/**
* Retrieve Player UUID.
* <p>
* Notes: player's UUID
*
* @return The current Player UUID
*/
public UUID getPlayerUUID() {
return handle.getUUIDs().read(0);
}
/**
* Set Player UUID.
*
* @param value - new value.
*/
public void setPlayerUUID(UUID value) {
handle.getUUIDs().write(0, value);
}
/**
* Retrieve the position of the spawned entity as a vector.
*
* @return The position as a vector.
*/
public Vector getPosition() {
return new Vector(getX(), getY(), getZ());
}
/**
* Set the position of the spawned entity using a vector.
*
* @param position - the new position.
*/
public void setPosition(Vector position) {
setX(position.getX());
setY(position.getY());
setZ(position.getZ());
}
public double getX() {
return handle.getDoubles().read(0);
}
public void setX(double value) {
handle.getDoubles().write(0, value);
}
public double getY() {
return handle.getDoubles().read(1);
}
public void setY(double value) {
handle.getDoubles().write(1, value);
}
public double getZ() {
return handle.getDoubles().read(2);
}
public void setZ(double value) {
handle.getDoubles().write(2, value);
}
/**
* Retrieve the yaw of the spawned entity.
*
* @return The current Yaw
*/
public float getYaw() {
return (handle.getBytes().read(0) * 360.F) / 256.0F;
}
/**
* Set the yaw of the spawned entity.
*
* @param value - new yaw.
*/
public void setYaw(float value) {
handle.getBytes().write(0, (byte) (value * 256.0F / 360.0F));
}
/**
* Retrieve the pitch of the spawned entity.
*
* @return The current pitch
*/
public float getPitch() {
return (handle.getBytes().read(1) * 360.F) / 256.0F;
}
/**
* Set the pitch of the spawned entity.
*
* @param value - new pitch.
*/
public void setPitch(float value) {
handle.getBytes().write(1, (byte) (value * 256.0F / 360.0F));
}
}

View File

@@ -0,0 +1,37 @@
package com.hibiscusmc.hmccosmetics.util.packets.wrappers;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.EnumWrappers.PlayerInfoAction;
import com.comphenix.protocol.wrappers.PlayerInfoData;
import java.util.List;
public class WrapperPlayServerPlayerInfo extends AbstractPacket {
public static final PacketType TYPE = PacketType.Play.Server.PLAYER_INFO;
public WrapperPlayServerPlayerInfo() {
super(new PacketContainer(TYPE), TYPE);
handle.getModifier().writeDefaults();
}
public WrapperPlayServerPlayerInfo(PacketContainer packet) {
super(packet, TYPE);
}
public PlayerInfoAction getAction() {
return handle.getPlayerInfoAction().read(0);
}
public void setAction(PlayerInfoAction value) {
handle.getPlayerInfoAction().write(0, value);
}
public List<PlayerInfoData> getData() {
return handle.getPlayerInfoDataLists().read(0);
}
public void setData(List<PlayerInfoData> value) {
handle.getPlayerInfoDataLists().write(0, value);
}
}