### Java Cloud Command Framework Setup and Examples Source: https://context7.com/bergerhealer/bkcommonlib/llms.txt Demonstrates setting up the Cloud Command Framework with PaperCommandManager and AnnotationParser. Includes examples for 'give', 'teleport', and 'world' commands with argument parsing, default values, permissions, and suggestions. ```java import org.incendo.cloud.annotations.Argument; import org.incendo.cloud.annotations.Command; import org.incendo.cloud.annotations.CommandDescription; import org.incendo.cloud.annotations.Permission; import org.incendo.cloud.annotations.suggestion.Suggestions; import org.incendo.cloud.context.CommandContext; import org.incendo.cloud.paper.PaperCommandManager; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class CloudCommandExample { public void setupCommands(JavaPlugin plugin) { // Create command manager PaperCommandManager manager = PaperCommandManager.createNative( plugin, CommandExecutionCoordinator.simpleCoordinator() ); // Parse and register annotated commands AnnotationParser parser = new AnnotationParser<>(manager, CommandSender.class); parser.parse(this); } @Command("myplugin give [amount]") @CommandDescription("Give an item to a player") @Permission("myplugin.give") public void giveCommand( CommandSender sender, @Argument("player") Player target, @Argument("item") Material item, @Argument(value = "amount", defaultValue = "1") int amount ) { ItemStack stack = new ItemStack(item, amount); target.getInventory().addItem(stack); sender.sendMessage("Gave " + amount + " " + item.name() + " to " + target.getName()); } @Command("myplugin teleport ") @CommandDescription("Teleport a player to another player") @Permission("myplugin.teleport") public void teleportCommand( CommandSender sender, @Argument("player") Player player, @Argument("destination") Player destination ) { player.teleport(destination.getLocation()); sender.sendMessage("Teleported " + player.getName() + " to " + destination.getName()); } @Suggestions("worlds") public List worldSuggestions(CommandContext context, String input) { return Bukkit.getWorlds().stream() .map(World::getName) .filter(name -> name.toLowerCase().startsWith(input.toLowerCase())) .collect(Collectors.toList()); } @Command("myplugin world ") @CommandDescription("Teleport to a world") public void worldCommand( Player player, @Argument(value = "world", suggestions = "worlds") String worldName ) { World world = Bukkit.getWorld(worldName); if (world != null) { player.teleport(world.getSpawnLocation()); } } } ``` -------------------------------- ### CraftInventory Constructor and Get Handle Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/org/bukkit/craftbukkit/inventories.txt Defines the CraftInventory class, its constructor that takes an NMS IInventory, and a method to retrieve the IInventoryHandle. ```java class CraftInventory extends org.bukkit.inventory.Inventory { public (org.bukkit.inventory.Inventory) CraftInventory((Object) IInventory nmsIInventory); protected final (IInventoryHandle) IInventory handleField:inventory; public (IInventoryHandle) IInventory getHandle:getInventory(); } ``` -------------------------------- ### Get Map Dimensions and Pixels (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/network/protocol_packet_map.txt Provides methods to get the start X/Y coordinates, width, height, and pixel data of a map. It also includes a check for the presence of pixel data. ```Java public int getStartX() { return instance#startx; } public int getStartY() { return instance#starty; } public int getWidth() { return instance#width; } public int getHeight() { return instance#height; } public boolean hasPixels() { byte[] pixels = instance#pixels; return pixels != null; } public byte[] getPixels() { return instance#pixels; } ``` -------------------------------- ### Initialize Server Common Library (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/world/level_block.txt This Java snippet shows the bootstrap initialization for the common library within the server environment. It calls `CommonBootstrap.initServer()` to set up necessary components. ```Java #bootstrap com.bergerkiller.bukkit.common.internal.CommonBootstrap.initServer(); ``` -------------------------------- ### Get Start Y Coordinate (Java) - Version Specific Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/network/protocol_packet_map.txt Retrieves the starting Y coordinate for the map's pixel data. The implementation is version-dependent, accessing the color patch data if available, otherwise returning 0. ```Java #if version >= 1.20.5 public int getStartY() { WorldMap$PatchData data = instance#getColorPatch(); return (data == null) ? 0 : data.startY(); } #elseif version >= 1.17 #require net.minecraft.world.level.saveddata.maps.WorldMap$PatchData public final readonly int startY; public int getStartY() { WorldMap$PatchData colorPatch = instance#colorPatch; return (colorPatch == null) ? 0 : colorPatch#startY; } #endif ``` -------------------------------- ### Get Start X Coordinate (Java) - Version Specific Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/network/protocol_packet_map.txt Retrieves the starting X coordinate for the map's pixel data. The implementation is version-dependent, accessing the color patch data if available, otherwise returning 0. ```Java #if version >= 1.20.5 public int getStartX() { WorldMap$PatchData data = instance#getColorPatch(); return (data == null) ? 0 : data.startX(); } #elseif version >= 1.17 #require net.minecraft.world.level.saveddata.maps.WorldMap$PatchData public final readonly int startX; public int getStartX() { WorldMap$PatchData colorPatch = instance#colorPatch; return (colorPatch == null) ? 0 : colorPatch#startX; } #endif ``` -------------------------------- ### Add BKCommonLib Repository (Kotlin) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/CLOUD_HOWTO.md Configures the Maven repository to host BKCommonLib. This is the first step in Gradle integration. ```kotlin repositories { maven("https://ci.mg-dev.eu/plugin/repository/everything/") } ``` -------------------------------- ### Add BKCommonLib Repository (Groovy) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/CLOUD_HOWTO.md Configures the Maven repository to host BKCommonLib. This is the first step in Gradle integration using Groovy DSL. ```groovy repositories { mavenCentral() maven { url = "https://ci.mg-dev.eu/plugin/repository/everything" } } ``` -------------------------------- ### Get Color Patch Data (Java) - Version Specific Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/network/protocol_packet_map.txt Retrieves the color patch data for the map, with implementation details varying based on the Minecraft version. This includes accessing the start coordinates, dimensions, and pixel data. ```Java #if version >= 1.20.5 #require net.minecraft.network.protocol.game.PacketPlayOutMap public WorldMap$PatchData getColorPatch() { return (WorldMap$PatchData) instance.colorPatch().orElse(null); } #elseif version >= 1.17 #require net.minecraft.network.protocol.game.PacketPlayOutMap private final net.minecraft.world.level.saveddata.maps.WorldMap$PatchData colorPatch; public WorldMap$PatchData getColorPatch() { return instance#colorPatch; } #endif ``` -------------------------------- ### Profiler Begin - World (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/world/level_world.txt Starts a profiling section with a given label. This method adapts to different Minecraft versions, using the appropriate profiler interface and methods like 'push', 'enter', or 'a' based on version checks. ```Java public void method_profiler_begin(String label) { #if version >= 1.21.2 net.minecraft.util.profiling.GameProfilerFiller profiler = net.minecraft.util.profiling.Profiler.get(); profiler.push(label); #elseif version >= 1.19 net.minecraft.util.profiling.GameProfilerFiller profiler = instance.getProfiler(); if (profiler != null) { profiler.push(label); } #elseif version >= 1.18 instance.getProfiler().push(label); #elseif version >= 1.14 instance.getMethodProfiler().enter(label); #elseif exists net.minecraft.util.profiling.MethodProfiler public void enter(String label) instance.methodProfiler.enter(label); #else instance.methodProfiler.a(label); #endif } ``` -------------------------------- ### ChunkFutureProvider Examples: Async Chunk Operations Source: https://context7.com/bergerhealer/bkcommonlib/llms.txt Demonstrates how to use ChunkFutureProvider to perform asynchronous operations related to chunk loading, unloading, and neighbour chunk access. It shows how to wait for all neighbours to load, access specific neighbours, and read block data from potentially unloaded chunks. ```java import com.bergerkiller.bukkit.common.chunk.ChunkFutureProvider; import com.bergerkiller.bukkit.common.chunk.ChunkFutureProvider.ChunkNeighbourList; import com.bergerlonger.bukkit.common.chunk.ChunkFutureProvider.ChunkStateListener; import com.bergerkiller.bukkit.common.chunk.ChunkFutureProvider.ChunkStateTracker; import org.bukkit.Chunk; import org.bukkit.event.EventHandler; import org.bukkit.event.world.ChunkLoadEvent; public class ChunkFutureExample implements Listener { private ChunkFutureProvider provider; public void initialize(Plugin plugin) { // Get main-thread provider (use ofThreadSafe for cross-thread use) provider = ChunkFutureProvider.of(plugin); } @EventHandler public void onChunkLoad(ChunkLoadEvent event) { Chunk chunk = event.getChunk(); // Wait for all 8 neighbours to be loaded ChunkNeighbourList neighbours = ChunkNeighbourList.neighboursOf(chunk, 1); provider.whenAllNeighboursLoaded(chunk, neighbours) .thenAccept(this::processChunkWithNeighbours); // Wait for a specific neighbour chunk provider.whenNeighbourLoaded(chunk, chunk.getX() + 1, chunk.getZ()) .thenAccept(neighbourChunk -> { // Access neighbour safely without sync chunk loading System.out.println("Neighbour loaded: " + neighbourChunk); }); // Read block data from potentially unloaded chunk Block targetBlock = chunk.getWorld().getBlockAt(chunk.getX() * 16 + 20, 64, chunk.getZ() * 16); provider.readNeighbourBlockData(chunk, targetBlock) .thenAccept(blockData -> { System.out.println("Block type: " + blockData.getType()); }); } public void trackChunkState(World world, int chunkX, int chunkZ) { // Track load/unload state with callbacks ChunkStateTracker tracker = provider.trackLoaded(world, chunkX, chunkZ, new ChunkStateListener() { @Override public void onRegistered(ChunkStateTracker tracker) { System.out.println("Tracking started, loaded: " + tracker.isLoaded()); } @Override public void onLoaded(ChunkStateTracker tracker) { System.out.println("Chunk loaded: " + tracker.getChunk()); } @Override public void onUnloaded(ChunkStateTracker tracker) { System.out.println("Chunk unloaded"); } @Override public void onCancelled(ChunkStateTracker tracker) { System.out.println("Tracking cancelled"); } }); // Cancel tracking when no longer needed tracker.cancel(); } private void processChunkWithNeighbours(Chunk chunk) { // Safely access neighbouring chunks without sync loading System.out.println("Processing chunk with all neighbours loaded"); } } ``` -------------------------------- ### Get Entity Chunk Coordinates Y (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/entity/entity.txt Retrieves the Y-coordinate of the chunk the entity is in. It gets the entity's block position and then shifts it right by 4 bits to get the chunk coordinate. This implementation is for Minecraft 1.18 and above. ```Java public int getChunkY() { BlockPosition blockPosition = instance.blockPosition(); return blockPosition.getY() >> 4; } ``` -------------------------------- ### SoftDependency Example in Java Source: https://github.com/bergerhealer/bkcommonlib/blob/master/README.md Demonstrates how to use the SoftDependency library to lazily handle third-party plugin dependencies. It shows initialization, enabling, and disabling callbacks. ```java public class MyPlugin extends JavaPlugin { private final SoftDependency myDependency = new SoftDependency(this, "my_dependency") { @Override protected MyDependencyPlugin initialize(Plugin plugin) { return MyDependencyPlugin.class.cast(plugin); } @Override protected void onEnable() { getLogger().info("Support for MyDependency enabled!"); } @Override protected void onDisable() { getLogger().info("Support for MyDependency disabled!"); } }; // Can use myDependency.get() anywhere, returns non-null if enabled. } ``` -------------------------------- ### Get Entity Chunk Coordinates Z (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/entity/entity.txt Retrieves the Z-coordinate of the chunk the entity is in. It gets the entity's block position and then shifts it right by 4 bits to get the chunk coordinate. This implementation is for Minecraft 1.18 and above. ```Java public int getChunkZ() { BlockPosition blockPosition = instance.blockPosition(); return blockPosition.getZ() >> 4; } ``` -------------------------------- ### Create CraftEntity Instance Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/org/bukkit/craftbukkit/entity.txt Creates a new CraftEntity instance, linking it to a Bukkit Server and a Minecraft EntityHandle. This is a static factory method used for entity instantiation. ```java package org.bukkit.craftbukkit.entity; import org.bukkit.craftbukkit.CraftServer; import com.bergerkiller.generated.net.minecraft.world.entity.EntityHandle; class CraftEntity { protected (EntityHandle) net.minecraft.world.entity.Entity entityHandle:entity; public static (org.bukkit.entity.Entity) CraftEntity createCraftEntity:getEntity((org.bukkit.Server) CraftServer server, (EntityHandle) net.minecraft.world.entity.Entity entity); public void setHandle((EntityHandle) net.minecraft.world.entity.Entity entity) public (Object) net.minecraft.world.entity.Entity getHandle(); } ``` -------------------------------- ### Get Entity Chunk Coordinates X (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/entity/entity.txt Retrieves the X-coordinate of the chunk the entity is in. It gets the entity's block position and then shifts it right by 4 bits to get the chunk coordinate. This implementation is for Minecraft 1.18 and above. ```Java public int getChunkX() { BlockPosition blockPosition = instance.blockPosition(); return blockPosition.getX() >> 4; } ``` -------------------------------- ### Configure BKCommonLib BOM and Dependencies Source: https://github.com/bergerhealer/bkcommonlib/blob/master/CLOUD_HOWTO.md This configuration sets the BKCommonLib version and imports the BKCommonLib-bom. This allows automatic management of BKCommonLib and its cloud dependencies. Dependencies can then be added without specifying versions. ```xml 1.21.1-v1 com.bergerkiller.bukkit BKCommonLib-bom ${project.bkcommonlib.version} pom import com.bergerkiller.bukkit BKCommonLib provided org.incendo cloud-paper provided org.incendo cloud-annotations provided org.incendo cloud-minecraft-extras provided ``` -------------------------------- ### Get Slot Index from PacketPlayInSetCreativeSlot (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/network/protocol_packets_other.txt Retrieves the slot index from a PacketPlayInSetCreativeSlot. The method used to get this index is version-dependent (1.20.5, 1.18, 1.13, and older). ```Java #if version >= 1.20.5 public int getSlotIndex() { return (int) instance.slotNum(); } #else #select version >= #case 1.18: public int getSlotIndex:getSlotNum(); #case 1.13: public int getSlotIndex:b(); #case else: public int getSlotIndex:a(); #endselect #endif ``` -------------------------------- ### Mountiplex Template Engine Example Source: https://github.com/bergerhealer/bkcommonlib/blob/master/README.md Illustrates the use of Mountiplex's template engine for handling Minecraft packets across different versions. This approach allows for conditional code generation using '#if - #endif' blocks, simplifying development for multiple Minecraft server forks and versions. ```text [Example template for various packets to demonstrate the power of this approach](https://github.com/bergerhealer/BKCommonLib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/network/protocol_packets_other.txt) ``` -------------------------------- ### Get Swim Sound - Minecraft 1.9+ Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/entity/entity.txt Gets the swim sound for an entity in Minecraft versions 1.9 and above. The method is protected and returns a ResourceKey for SoundEffect. ```Java protected (com.bergerkiller.bukkit.common.resources.ResourceKey) SoundEffect getSwimSound(); ``` -------------------------------- ### Create Raw Recipe Item Stack (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/world/item_crafting_recipes.txt A utility method to create a raw `RecipeItemStack` object using reflection. It instantiates a new object and sets its choices using the `setChoices` method, providing a way to programmatically create recipe item stacks. ```Java public static Object createRawRecipeItemStack(List choices) { Object raw = T.newInstanceNull(); T.setChoices.invoke(raw, choices); return raw; } ``` -------------------------------- ### Get Chunk If Loaded (Minecraft 1.14+) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/server_level_playerchunk.txt Retrieves a chunk if it is currently loaded for Minecraft versions 1.14 and above. It uses specific internal methods to get the chunk. ```Java #if version >= 1.18 #require net.minecraft.server.level.PlayerChunkMap protected (Object) PlayerChunk getVisibleChunk_1_14:getVisibleChunkIfPresent(long i); #require net.minecraft.server.level.PlayerChunkMap protected (Object) PlayerChunk getUpdatingChunk_1_14:getUpdatingChunkIfPresent(long i); public (PlayerChunkHandle) PlayerChunk getVisibleChunk(int x, int z) { return (PlayerChunk) instance#getVisibleChunk_1_14(ChunkCoordIntPair.asLong(x, z)); } public (PlayerChunkHandle) PlayerChunk getUpdatingChunk(int x, int z) { return (PlayerChunk) instance#getUpdatingChunk_1_14(ChunkCoordIntPair.asLong(x, z)); } #else #require net.minecraft.server.level.PlayerChunkMap protected (Object) PlayerChunk getVisibleChunk_1_14:getVisibleChunk(long i); #require net.minecraft.server.level.PlayerChunkMap protected (Object) PlayerChunk getUpdatingChunk_1_14:getUpdatingChunk(long i); public (PlayerChunkHandle) PlayerChunk getVisibleChunk(int x, int z) { return (PlayerChunk) instance#getVisibleChunk_1_14(ChunkCoordIntPair.pair(x, z)); } public (PlayerChunkHandle) PlayerChunk getUpdatingChunk(int x, int z) { return (PlayerChunk) instance#getUpdatingChunk_1_14(ChunkCoordIntPair.pair(x, z)); } #endif ``` -------------------------------- ### Get Movement Vector - Minecraft 1.18+ Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/entity/entity.txt Retrieves the movement vector for an entity in Minecraft 1.18 and later. This method is used to get the entity's current motion. ```Java Vec3D mot = instance.getDeltaMovement(); ``` -------------------------------- ### File Configuration Management in Java Source: https://github.com/bergerhealer/bkcommonlib/blob/master/README.md Manages file-based configurations (e.g., YAML) with support for headers, node manipulation, and cloning. It allows loading, saving, and modifying configuration values asynchronously. ```java FileConfiguration config = new FileConfiguration(myPlugin, "file.yml"); config.load(); config.setHeader("This is the header at the top of the file"); config.addHeader("This adds a new line"); config.setHeader("coolName", "\nSets the cool name. Empty whitespace above."); config.addHeader("coolName", "Yup, this is on a new line too"); String coolName = config.get("coolName", "DefaultCoolName"); config.setHeader("stuff", "\nThis is some stuff"); ConfigurationNode stuff = config.getNode("stuff"); boolean stuffEnabled = stuff.get("enabled", false); int stuffCount = stuff.get("count", 0); // Clone the stuff settings, modify, show yaml ConfigurationNode stuffCopy = stuff.clone(); stuffCopy.set("count", 20); System.out.println(stuffCopy.toString()); config.save(); // Non-blocking! ``` -------------------------------- ### Initialize FileConfiguration in Java Source: https://github.com/bergerhealer/bkcommonlib/wiki/Configuration-API Initializes a FileConfiguration object to manage a YAML configuration file. This constructor requires an instance of your JavaPlugin and the name of the configuration file, including its extension. ```java FileConfiguration config = new FileConfiguration(this, "config.yml"); ``` -------------------------------- ### Get and Set Push Force for Minecart Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/entity/vehicle_minecart.txt Implements methods to get and set the push force vector for a minecart. This functionality is available from version 1.21.2 onwards and utilizes a Vec3D object. ```java public (org.bukkit.util.Vector) Vec3D getPushForce() { return instance.push; } public void setPushForce(double fx, double fy, double fz) { instance.push = new Vec3D(fx, fy, fz); } ``` -------------------------------- ### Concrete DataWatcher Key Definitions and Initialization Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/entity/entity.txt Provides the concrete Java definitions and initialization logic for DataWatcher keys. It handles version-specific instantiation for DATA_CUSTOM_NAME, ensuring compatibility with different Minecraft versions (pre and post 1.13). ```Java public static final DataWatcher.Key DATA_FLAGS = DataWatcher.Key.Type.BYTE.createKey(T.DATA_FLAGS, 0); public static final DataWatcher.Key DATA_AIR_TICKS = DataWatcher.Key.Type.INTEGER.createKey(T.DATA_AIR_TICKS, 1); public static final DataWatcher.Key DATA_CUSTOM_NAME; static { if (com.bergerkiller.bukkit.common.Common.evaluateMCVersion(">=", "1.13")) { DATA_CUSTOM_NAME = DataWatcher.Key.Type.CHAT_TEXT.createKey(T.DATA_CUSTOM_NAME, 2); } else { DATA_CUSTOM_NAME = DataWatcher.Key.Type.STRING.translate(ChatText.class).createKey(T.DATA_CUSTOM_NAME, 2); } } public static final DataWatcher.Key DATA_CUSTOM_NAME_VISIBLE = DataWatcher.Key.Type.BOOLEAN.createKey(T.DATA_CUSTOM_NAME_VISIBLE, 3); public static final DataWatcher.Key DATA_SILENT = DataWatcher.Key.Type.BOOLEAN.createKey(T.DATA_SILENT, 4); public static final DataWatcher.Key DATA_NO_GRAVITY = DataWatcher.Key.Type.BOOLEAN.createKey(T.DATA_NO_GRAVITY, -1); public static final DataWatcher.Key DATA_POSE = DataWatcher.Key.Type.ENTITY_POSE.createKey(T.DATA_POSE, -1); ``` -------------------------------- ### Get Movement Vector - Pre 1.18 Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/entity/entity.txt Gets the entity's movement vector for Minecraft versions prior to 1.18. This uses the 'getMot' method to access the entity's motion. ```Java Vec3D mot = instance.getMot(); ``` -------------------------------- ### Get Internal Name from Minecraft Paintings (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/org/bukkit/craftbukkit/art.txt Retrieves the internal string name of a Minecraft Paintings enum. It uses version-specific methods to get the MinecraftKey associated with the enum and returns its path. ```Java public static String NotchToInternalName((Object) Paintings art) { #if version >= 1.18 net.minecraft.resources.MinecraftKey key = (net.minecraft.resources.MinecraftKey) BuiltInRegistries.MOTIVE.getKey((Object) art); return (key == null) ? null : key.getPath(); #elseif version >= 1.13.1 net.minecraft.resources.MinecraftKey key = (net.minecraft.resources.MinecraftKey) BuiltInRegistries.MOTIVE.getKey((Object) art); ``` -------------------------------- ### Mountiplex Type Conversion Example Source: https://github.com/bergerhealer/bkcommonlib/blob/master/README.md Demonstrates how Mountiplex, a reflection library used by BKCommonLib, handles type conversions. It shows inline declarations for converting Bukkit Entities to net.minecraft Entities and for accessing block positions, facilitating cross-version compatibility. ```java ```java // Fields public final (IntVector3) BlockPosition position; // Instance methods public (List) List findEntities() { // Code } ``` ``` -------------------------------- ### Get Dimension Key (Java - Older Versions) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/server_level_worldserver.txt Provides a method to get the dimension key in older Minecraft versions. The specific implementation details might vary for versions prior to 1.16. ```Java public (com.bergerkiller.bukkit.common.resources.ResourceKey) ResourceKey getDimensionKey() { ``` -------------------------------- ### Handle onTick Method Based on Minecraft Version Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/entity/entity.txt This snippet shows how the 'onTick' method is implemented differently based on the Minecraft version. It uses preprocessor directives to select the appropriate method signature for versions 1.12 and above, falling back to a default for older versions. ```java #elseif version >= 1.12 public void onTick:B_(); #else if version >= 1.11 public void onTick:A_(); #elseif version >= 1.9 public void onTick:m(); #elseif version >= 1.8.3 public void onTick:t_(); #else public void onTick:s_(); #endif ``` -------------------------------- ### Get Item Map Color (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/world/item_itemstack.txt Retrieves the map color associated with an item. Versions 1.20.5 and later use the 'MAP_COLOR' DataComponent to get the RGB value. Older versions have a placeholder comment. ```Java public int getMapColor() { #if version >= 1.20.5 net.minecraft.world.item.component.MapItemColor color; color = (net.minecraft.world.item.component.MapItemColor) instance.get(DataComponents.MAP_COLOR); return (color == null) ? -1 : color.rgb(); #else ``` -------------------------------- ### Handle Entity Push Method Based on Minecraft Version Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/entity/entity.txt This snippet shows how the 'onPush' method is implemented differently based on the Minecraft version. It uses a '#select' directive to choose the correct method signature, including different parameter names and internal method calls, for versions 1.18 down to 1.11, with a default for older versions. ```java #select version >= #case 1.18: public void onPush:push(double d0, double d1, double d2); #case 1.16.2: public void onPush:i(double d0, double d1, double d2); #case 1.15: public void onPush:h(double d0, double d1, double d2); #case 1.11: public void onPush:f(double d0, double d1, double d2); #case else: public void onPush:g(double d0, double d1, double d2); #endselect ``` -------------------------------- ### Get Chunk If Loaded (Minecraft 1.8) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/server_level_playerchunk.txt Retrieves a chunk if it is currently loaded on the server for Minecraft versions 1.8. It checks the loaded status and then attempts to get the chunk from the server's chunk provider. ```Java #require net.minecraft.server.level.PlayerChunk private final net.minecraft.world.level.ChunkCoordIntPair location; #require net.minecraft.server.level.PlayerChunk private boolean loaded; #if exists net.minecraft.server.level.PlayerChunk private final PlayerChunkMap this$0; #require net.minecraft.server.level.PlayerChunk private final PlayerChunkMap playerChunkMap:this$0; #else #require net.minecraft.server.level.PlayerChunk final PlayerChunkMap playerChunkMap; #endif public (org.bukkit.Chunk) Chunk getChunkIfLoaded() { boolean loaded = instance#loaded; if (loaded) { PlayerChunkMap map = instance#playerChunkMap; ChunkCoordIntPair loc = instance#location; return map.a().chunkProviderServer.getChunkAt(loc.x, loc.z); } else { return null; } } ``` -------------------------------- ### Get Plugins Directory (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/org/bukkit/craftbukkit/server.txt Returns the File object representing the server's plugins directory. This is achieved by accessing the server's options and retrieving the value associated with 'plugins'. ```Java public java.io.File getPluginsDirectory() { return (java.io.File) instance.getServer().options.valueOf("plugins"); } ``` -------------------------------- ### Get Entity Class Instance (1.14+) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/entity/entity_types.txt This method retrieves the `Class` instance of an entity from its internal representation. It utilizes the `EntityTypingHandler` to get the class from the entity type instance. This functionality is available from version 1.14 onwards. ```java public optional (Class) Class getEntityClassInst() { return com.bergerkiller.bukkit.common.internal.logic.EntityTypingHandler.INSTANCE.getClassFromEntityTypes(instance); } ``` -------------------------------- ### Get Particle Type from ParticleParam (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/network/protocol_packets_other.txt Retrieves the `ParticleType` from a `ParticleParam` object. The method used to get the type varies across Minecraft versions, with different accessors like `getType()`, `getParticle()`, or a private method `b()` being used. ```Java public (com.bergerkiller.bukkit.common.resources.ParticleType) Particle getParticleType() { ParticleParam param = instance#particle; if (param == null) return null; #if version >= 1.18 return param.getType(); #elseif version >= 1.14.4 return param.getParticle(); #else return param.b(); #endif } ``` -------------------------------- ### Create PacketPlayOutMountHandle with IDs (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/network/protocol_packets_other.txt Creates a PacketPlayOutMountHandle and initializes it with an entity ID and an array of mounted entity IDs. ```Java public static PacketPlayOutMountHandle createNew(int entityId, int[] mountedEntityIds) { PacketPlayOutMountHandle handle = createNew(); handle.setEntityId(entityId); handle.setMountedEntityIds(mountedEntityIds); return handle; } ``` -------------------------------- ### Get Sound Names from Registry (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/sounds.txt Retrieves a collection of MinecraftKey objects representing sound event names. The implementation adapts based on the Minecraft version, utilizing different registry access methods for versions 1.13.1 and above, 1.9 and above, and older versions. For older versions, it iterates through Bukkit Sounds and converts them to MinecraftKeys. ```java public static java.util.Collection getSoundNames() { #if version >= 1.13.1 return ((RegistryMaterials) net.minecraft.core.registries.BuiltInRegistries.SOUND_EVENT).keySet(); #elseif version >= 1.9 return SoundEffect.a.keySet(); #else // The only registry that exists is CraftSound. Sadge. org.bukkit.Sound[] values = org.bukkit.Sound.values(); int len = values.length; java.util.List names = new java.util.ArrayList(len); for (int i = 0; i < len; i++) { String nameStr = org.bukkit.craftbukkit.CraftSound.getSound(values[i]); names.add(new MinecraftKey(nameStr)); } return names; #endif } ``` -------------------------------- ### Get Block State Value Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/world/level_block_iblockdata.txt Retrieves the value associated with a given IBlockState. This function checks for null states and uses version-specific methods to get the state's value, primarily for Minecraft versions 1.18 and above. ```java public Object get((IBlockStateHandle) IBlockState state) { if (state != null) { return instance.getValue(state); } else { return null; } } ``` ```java public Object get((IBlockStateHandle) IBlockState state) { if (state != null) { return instance.get(state); } else { return null; } } ``` -------------------------------- ### Work with NBT Data using Java Source: https://context7.com/bergerhealer/bkcommonlib/llms.txt Demonstrates how to create, populate, read, clone, and save NBT data using the CommonTag API in Java. It covers setting primitive values, UUIDs, locations, nested compounds, and tag lists, as well as loading data from files. This example requires the `com.bergerkiller.bukkit.common.nbt` package. ```java import com.bergerkiller.bukkit.common.nbt.CommonTag; import com.bergerkiller.bukkit.common.nbt.CommonTagCompound; import com.bergerkiller.bukkit.common.nbt.CommonTagList; import java.io.File; import java.util.UUID; public class NBTExample { public void workWithNBT() { // Create NBT compound CommonTagCompound tag = new CommonTagCompound(); // Set primitive values tag.putValue("name", "TestEntity"); tag.putValue("health", 20.0f); tag.putValue("level", 5); tag.putValue("active", true); // Store UUID (automatically splits into Most/Least) tag.putUUID("playerId", UUID.randomUUID()); // Store block location BlockLocation loc = new BlockLocation("world", 100, 64, 200); tag.putValue("spawn", loc); // Create nested compounds CommonTagCompound inventory = new CommonTagCompound(); inventory.putValue("slots", 36); tag.put("inventory", inventory); // Create tag lists CommonTagList itemList = new CommonTagList(); CommonTagCompound item1 = new CommonTagCompound(); item1.putValue("id", "minecraft:diamond"); item1.putValue("count", 64); itemList.add(item1); tag.put("items", itemList); // Read values back String name = tag.getValue("name", "Unknown"); float health = tag.getValue("health", 0.0f); UUID playerId = tag.getUUID("playerId"); // Clone and modify CommonTagCompound copy = tag.clone(); copy.putValue("health", 10.0f); // Save to file (compressed) File dataFile = new File(plugin.getDataFolder(), "entity.dat"); tag.writeToFile(dataFile); // Load from file CommonTagCompound loaded = CommonTagCompound.readFromFile(dataFile); } public void modifyItemNBT(ItemStack item) { // Get item's custom NBT data CommonTagCompound customData = ItemUtil.getCustomData(item); if (customData != CommonTagCompound.EMPTY) { // Modify existing data customData.putValue("enchantLevel", 5); } else { // Create new custom data CommonTagCompound newData = new CommonTagCompound(); newData.putValue("customItem", true); newData.putValue("creator", "MyPlugin"); ItemUtil.setCustomData(item, newData); } } } ``` -------------------------------- ### Get Spawn Packet (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/server_level_entity_tracker.txt Provides different implementations for getting the spawn packet based on Minecraft version and server fork. It includes cases for versions >= 1.9, and specific handling for Nachospigot/Azurite forks, as well as a default private implementation. ```Java private (CommonPacket) Packet getSpawnPacket:e(); ``` ```Java protected (CommonPacket) Packet getSpawnPacket:c(); ``` ```Java private (CommonPacket) Packet getSpawnPacket:c(); ``` -------------------------------- ### Get and Set Entity Type Using CommonEntityType Across Versions Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/network/protocol_packets_spawn.txt This code provides methods to get and set the entity type using the CommonEntityType enum. It includes version-specific logic for accessing the NMS entity type or entity type ID and converting between them. ```Java // Entity type property #if version >= 1.19 #require PacketPlayOutSpawnEntityLiving private final EntityTypes entityType:type; public com.bergerkiller.bukkit.common.entity.CommonEntityType getCommonEntityType() { Object nmsEntityType = instance.getType(); return com.bergerkiller.bukkit.common.entity.CommonEntityType.byNMSEntityTypeRaw(nmsEntityType); } public void setCommonEntityType(com.bergerkiller.bukkit.common.entity.CommonEntityType commonEntityType) { if (commonEntityType == null) { throw new IllegalArgumentException("Input CommonEntityType is null"); } instance#entityType = (EntityTypes) commonEntityType.nmsEntityType.getRaw(); } #else #if version >= 1.17 #require PacketPlayOutSpawnEntityLiving private int entityTypeId:type; #elseif version >= 1.9 #require PacketPlayOutSpawnEntityLiving private int entityTypeId:c; #else #require PacketPlayOutSpawnEntityLiving private int entityTypeId:b; #endif public com.bergerkiller.bukkit.common.entity.CommonEntityType getCommonEntityType() { int typeId = instance#entityTypeId; return com.bergerkiller.bukkit.common.entity.CommonEntityType.byEntityTypeId(typeId); } public void setCommonEntityType(com.bergerkiller.bukkit.common.entity.CommonEntityType commonEntityType) { if (commonEntityType == null) { throw new IllegalArgumentException("Input CommonEntityType is null"); } if (commonEntityType.entityTypeId == -1) { throw new IllegalArgumentException("Input CommonEntityType " + commonEntityType.toString() + " cannot be spawned using this packet"); } instance#entityTypeId = commonEntityType.entityTypeId; } #endif ``` -------------------------------- ### Create Tag List Value Input (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/global/global.txt Constructs a `TypedInputList` for tag values from an `NBTTagList`. It uses a `ValueInputContextHelper` which is initialized with `HolderLookup` and `DynamicOpsNBT`. Handles empty lists by returning an empty context, otherwise uses a constructor to build the list. ```java public static ValueInput.TypedInputList createTagListValueInput(net.minecraft.util.ProblemReporter problemreporter, net.minecraft.core.HolderLookup.a holderlookup_a, com.mojang.serialization.Codec codec, net.minecraft.nbt.NBTTagList nbttaglist) { net.minecraft.world.level.storage.ValueInputContextHelper context = new net.minecraft.world.level.storage.ValueInputContextHelper(holderlookup_a, net.minecraft.nbt.DynamicOpsNBT.INSTANCE); if (nbttaglist.isEmpty()) { return context.emptyTypedList(); } #require TagValueInput.TypedListWrapper static TagValueInput.TypedListWrapper tagListInputCtor:(net.minecraft.util.ProblemReporter problemreporter, String s, net.minecraft.world.level.storage.ValueInputContextHelper context, com.mojang.serialization.Codec codec, net.minecraft.nbt.NBTTagList nbttaglist); return (ValueInput$TypedInputList) #tagListInputCtor(problemreporter, "", context, codec, nbttaglist); } ``` -------------------------------- ### CraftInventoryPlayer Constructor Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/org/bukkit/craftbukkit/inventories.txt Shows the constructor for CraftInventoryPlayer, which takes an NMS PlayerInventory object. ```java class CraftInventoryPlayer { public (org.bukkit.inventory.PlayerInventory) CraftInventoryPlayer((Object) net.minecraft.world.entity.player.PlayerInventory nmsPlayerInventory); } ``` -------------------------------- ### Get PlayerInfoData Properties for ClientboundPlayerInfoUpdatePacket (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/network/protocol_packets_playerinfo.txt Provides methods to retrieve properties from PlayerInfoData within the ClientboundPlayerInfoUpdatePacket. This includes getting the GameProfile, ping latency, game mode, and display name. Implementations vary based on Minecraft version (1.19.3+, 1.18, and older). ```java #if version >= 1.19.3 public (GameProfileHandle) GameProfile getProfile:profile(); public int getPing:latency(); public (org.bukkit.GameMode) EnumGamemode getGameMode:gameMode(); public (ChatText) IChatBaseComponent getListName:displayName(); #elseif version >= 1.18 public (GameProfileHandle) GameProfile getProfile(); public int getPing:getLatency(); public (org.bukkit.GameMode) EnumGamemode getGameMode(); public (ChatText) IChatBaseComponent getListName:getDisplayName(); #else public (GameProfileHandle) GameProfile getProfile:a(); public int getPing:b(); public (org.bukkit.GameMode) EnumGamemode getGameMode:c(); public (ChatText) IChatBaseComponent getListName:d(); #endif ``` -------------------------------- ### Get Recipe Item Stack Choices (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/world/item_crafting_recipes.txt Retrieves the possible item stacks for a `RecipeItemStack`. This method has different implementations based on Minecraft version, handling exact matches and item material lookups. It ensures compatibility across various game versions. ```Java #if version >= 1.21.2 public (List) List getChoices() { if (instance.isExact()) { #if exists net.minecraft.world.item.crafting.RecipeItemStack public java.util.Set itemStacks(); java.util.Set itemStacks = instance.itemStacks(); if (itemStacks.isEmpty()) { return java.util.Collections.emptyList(); } else { return new java.util.ArrayList(itemStacks); } #else return (List) instance.itemStacks(); #endif } // Only stores the Item material to match. Create itemstacks out of them (count 1) #if version >= 1.21.4 #require RecipeItemStack private final net.minecraft.core.HolderSet values; net.minecraft.core.HolderSet items = instance#values; #else java.util.List items = instance.items(); #endif java.util.List itemStacks = new java.util.ArrayList(items.size()); for (java.util.Iterator iter = items.iterator(); iter.hasNext();) { net.minecraft.core.Holder itemHolder = (net.minecraft.core.Holder) iter.next(); ItemStack item = new ItemStack(itemHolder); itemStacks.add(item); } return itemStacks; } #elseif version >= 1.18 public (List) ItemStack[] getChoices:getItems(); #elseif version >= 1.17 public (List) ItemStack[] getChoices:a(); #else public (List) ItemStack[] getChoices() { #if version >= 1.13 instance.buildChoices(); #endif return instance.choices; } #endif ``` -------------------------------- ### Get Block Data At Coordinate - World (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/world/level_world.txt Optimized method to get BlockData using integer coordinates (x, y, z). It avoids creating BlockPosition objects for performance gains and includes a conditional check for CraftBukkit's 'captureTreeGeneration' behavior. ```Java public BlockData getBlockDataAtCoord(int x, int y, int z) { #if exists net.minecraft.world.level.World public boolean captureTreeGeneration; && !exists io.github.opencubicchunks.cubicchunks.api.world.ICube // CraftBukkit does some special stuff, sometimes, when captureTreeGeneration is set if (instance.captureTreeGeneration) { #if version >= 1.18 IBlockData blockData = instance.getBlockState(new BlockPosition(x, y, z)); #else ``` -------------------------------- ### Get Internal Name from Minecraft Holder (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/org/bukkit/craftbukkit/art.txt Retrieves the internal string name (resource location path) of a Minecraft Holder object. It uses the painting registry to get the MinecraftKey associated with the painting's value and returns its path. ```Java public static String NotchToInternalName((Object) Holder art) { IRegistry paintingRegistry = #getPaintingVariantRegistry(); net.minecraft.resources.MinecraftKey key = (net.minecraft.resources.MinecraftKey) paintingRegistry.getKey((Object) art.value()); return (key == null) ? null : key.getPath(); } ``` -------------------------------- ### Item Dropping Implementation Across Minecraft Versions Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/entity/entity.txt This snippet shows the implementation of the `dropItem` method for dropping items from entities. It highlights variations in method signatures and the use of `spawnAtLocation` across different Minecraft versions, including parameters for material, amount, and force. ```Java #if version >= 1.21.2 public (org.bukkit.entity.Item) EntityItem dropItem((org.bukkit.Material) Item material, int amount, float force) { return instance.spawnAtLocation((WorldServer) instance.level(), new ItemStack(material, amount), force); } #elseif version >= 1.18 public (org.bukkit.entity.Item) EntityItem dropItem((org.bukkit.Material) Item material, int amount, float force) { return instance.spawnAtLocation(new ItemStack(material, amount), force); } #elseif version >= 1.13 public (org.bukkit.entity.Item) EntityItem dropItem((org.bukkit.Material) Item material, int amount, float force) { ``` -------------------------------- ### Particle API (1.13+): Get particle name Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/net/minecraft/core_particles.txt Retrieves the name of the particle. For versions 1.13.1 and later, it uses BuiltInRegistries to get the MinecraftKey. For earlier versions (pre-1.18), it uses a different registry lookup and returns the key's key instead of its path. ```java public String getName() { // Particle API added in MC 1.13 MinecraftKey key; #if version >= 1.13.1 key = BuiltInRegistries.PARTICLE_TYPE.getKey((Object) instance); #else key = (MinecraftKey) Particle.REGISTRY.b((Object) instance); #endif if (key == null) return ""; #if version >= 1.18 return key.getPath(); #else return key.getKey(); #endif } ``` -------------------------------- ### Create Tag List Value Output (Java) Source: https://github.com/bergerhealer/bkcommonlib/blob/master/src/main/templates/com/bergerkiller/templates/global/global.txt Generates a `TypedOutputList` for tag values. This function takes a `ProblemReporter`, `HolderLookup`, a `Codec` for serialization, and an `NBTTagList`. It sets up the `DynamicOps` context and uses a specific constructor to create the list output. ```java public static ValueOutput.TypedOutputList createTagListValueOutput(net.minecraft.util.ProblemReporter problemreporter, net.minecraft.core.HolderLookup.a holderlookup_a, com.mojang.serialization.Codec codec, net.minecraft.nbt.NBTTagList nbttaglist) { #require TagValueOutput.TypedListWrapper static TagValueInput.TypedListWrapper tagListOutputCtor:(net.minecraft.util.ProblemReporter problemreporter, String s, com.mojang.serialization.DynamicOps dynamicops, com.mojang.serialization.Codec codec, net.minecraft.nbt.NBTTagList nbttaglist); com.mojang.serialization.DynamicOps dynamicops = holderlookup_a.createSerializationContext(net.minecraft.nbt.DynamicOpsNBT.INSTANCE); return (ValueOutput.TypedOutputList) #tagListOutputCtor(problemreporter, "", dynamicops, codec, nbttaglist); } ```