Usage Guide v1.4.0

Learn how to use ChosenLib utilities effectively in your Fabric mods with practical examples and best practices.

🚀 Quick Start

Get started with ChosenLib v1.4.0 in just a few steps:

1. Import the Utilities

// New in v1.4.0
import com.chosen.lib.util.WorldUtils;
import com.chosen.lib.util.EntityUtils;
import com.chosen.lib.util.NetworkUtils;

// Enhanced existing utilities
import com.chosen.lib.util.TextUtils;
import com.chosen.lib.util.GuiUtils; // Now server-side compatible!
import com.chosen.lib.util.ItemUtils;

2. Use Basic Functions

// World operations (NEW!)
WorldUtils.setBlockState(world, pos, newState);

// Entity operations (NEW!)
EntityUtils.heal(entity, 10.0f);

// Network operations (NEW!)
PacketByteBuf buffer = NetworkUtils.createBuffer();

// Enhanced text operations
Text interactive = TextUtils.interactiveText("Click me", "Tooltip", "https://example.com");

// Enhanced item operations
ItemUtils.insertStack(inventory, stack);

🌍 WorldUtils Examples NEW

WorldUtils provides safe world and block manipulation utilities.

Block Operations

// Safe block operations with validation
BlockState state = WorldUtils.getBlockState(world, pos);
boolean success = WorldUtils.setBlockState(world, pos, newState);

// Check if position is loaded
if (WorldUtils.isPositionLoaded(world, pos)) {
    // Safe to operate on this position
}

// Check if block can be placed
if (WorldUtils.canPlaceBlock(world, pos, state)) {
    WorldUtils.setBlockState(world, pos, state);
}

Area Operations

// Get blocks in different shapes
List<BlockPos> cubeBlocks = WorldUtils.getBlocksInCube(center, 5);
List<BlockPos> sphereBlocks = WorldUtils.getBlocksInSphere(center, 5.0);
List<BlockPos> areaBlocks = WorldUtils.getBlocksInArea(pos1, pos2);

// Find specific blocks
List<BlockPos> ores = WorldUtils.findBlocks(world, center, 10, 
    state -> state.isOf(Blocks.DIAMOND_ORE));

// Find nearest block
BlockPos nearest = WorldUtils.findNearestBlock(world, center, 20,
    state -> state.isOf(Blocks.WATER));

// Replace blocks in area
int replaced = WorldUtils.replaceBlocks(world, center, 5,
    Blocks.STONE.getDefaultState(), Blocks.COBBLESTONE.getDefaultState());

World Properties

// Get world information
RegistryEntry<Biome> biome = WorldUtils.getBiome(world, pos);
int lightLevel = WorldUtils.getLightLevel(world, pos);
boolean canSeeSky = WorldUtils.canSeeSky(world, pos);
BlockPos highest = WorldUtils.getHighestBlock(world, x, z);

// Chunk operations
Chunk chunk = WorldUtils.getChunk(world, pos);
boolean loaded = WorldUtils.isChunkLoaded(world, pos);
ChunkPos chunkPos = WorldUtils.getChunkPos(pos);

// Fluid operations
FluidState fluidState = WorldUtils.getFluidState(world, pos);
boolean hasFluid = WorldUtils.hasFluid(world, pos, Fluids.WATER);

👤 EntityUtils Examples NEW

EntityUtils provides comprehensive entity management utilities.

Health Management

// Health operations
float health = EntityUtils.getHealth(entity);
EntityUtils.setHealth(entity, 20.0f);
EntityUtils.heal(entity, 10.0f);
EntityUtils.damage(entity, damageSource, 5.0f);

// Health validation
float maxHealth = EntityUtils.getMaxHealth(entity);
boolean isAlive = EntityUtils.isAlive(entity);
boolean isFullHealth = EntityUtils.isFullHealth(entity);

Status Effects

// Status effect management
boolean hasEffect = EntityUtils.hasStatusEffect(entity, StatusEffects.SPEED);
EntityUtils.addStatusEffect(entity, new StatusEffectInstance(StatusEffects.SPEED, 200, 1));
EntityUtils.removeStatusEffect(entity, StatusEffects.POISON);
EntityUtils.clearStatusEffects(entity);

// Get effect information
StatusEffectInstance effect = EntityUtils.getStatusEffect(entity, StatusEffects.SPEED);
int duration = EntityUtils.getStatusEffectDuration(entity, StatusEffects.SPEED);

Teleportation

// Teleportation methods
EntityUtils.teleport(entity, new Vec3d(100, 64, 100));
EntityUtils.teleport(entity, new BlockPos(100, 64, 100));
EntityUtils.teleportToEntity(entity, targetEntity);

// Safe teleportation with validation
boolean success = EntityUtils.safeTeleport(entity, targetPos);

Entity Finding

// Find entities in area
List<Entity> nearbyEntities = EntityUtils.getEntitiesInRadius(world, center, 10.0, null);
List<PlayerEntity> players = EntityUtils.getPlayersInRadius(world, center, 20.0);
PlayerEntity nearest = EntityUtils.findNearestPlayer(world, center, 50.0);

// Find specific entity types
List<MobEntity> mobs = EntityUtils.getEntitiesOfType(world, center, 15.0, MobEntity.class);
List<ItemEntity> items = EntityUtils.getEntitiesOfType(world, center, 5.0, ItemEntity.class);

Physics Operations

// Velocity and movement
EntityUtils.setVelocity(entity, new Vec3d(0, 1, 0));
EntityUtils.launchTowards(entity, targetPos, 2.0);
EntityUtils.knockback(entity, sourcePos, 1.5);

// Launch entity upward
EntityUtils.launchUp(entity, 1.0);

🌐 NetworkUtils Examples NEW

NetworkUtils provides easy networking and packet utilities.

Packet Creation

// Create empty buffer
PacketByteBuf buffer = NetworkUtils.createBuffer();

// Create buffer with data
PacketByteBuf buffer = NetworkUtils.createBuffer(buf -> {
    buf.writeString("Hello World");
    buf.writeInt(42);
});

// Create simple packets
PacketByteBuf simplePacket = NetworkUtils.createSimplePacket("test message");
PacketByteBuf posPacket = NetworkUtils.createPositionPacket(blockPos);

Data Serialization

// Write different data types
NetworkUtils.writeString(buffer, "Hello World");
NetworkUtils.writeBlockPos(buffer, new BlockPos(100, 64, 100));
NetworkUtils.writeVec3d(buffer, new Vec3d(1.0, 2.0, 3.0));
NetworkUtils.writeUuid(buffer, player.getUuid());

// Write arrays
NetworkUtils.writeBooleanArray(buffer, new boolean[]{true, false, true});
NetworkUtils.writeIntArray(buffer, new int[]{1, 2, 3, 4, 5});
NetworkUtils.writeStringArray(buffer, new String[]{"hello", "world"});

// Write collections
NetworkUtils.writeStringList(buffer, Arrays.asList("item1", "item2", "item3"));

Packet Sending

// Send to specific player
NetworkUtils.sendToPlayer(player, channelId, buffer);

// Send to multiple players
List<ServerPlayerEntity> players = Arrays.asList(player1, player2);
NetworkUtils.sendToPlayers(players, channelId, buffer);

// Send to all players in world
NetworkUtils.sendToWorld(world, channelId, buffer);

// Send to players in radius
NetworkUtils.sendToPlayersInRadius(world, center, 50.0, channelId, buffer);

Safe Operations

// Safe buffer operations with error handling
boolean success = NetworkUtils.safeBufferOperation(buffer, buf -> {
    buf.writeString("data");
    buf.writeInt(123);
    return true;
});

// Check buffer state
boolean hasData = NetworkUtils.hasReadableBytes(buffer, 4);
int remaining = NetworkUtils.getRemainingBytes(buffer);

📝 Enhanced TextUtils Examples ENHANCED

TextUtils now includes interactive components and performance improvements.

Interactive Text Components

// Create interactive text
Text clickableUrl = TextUtils.clickable("Visit website", "https://example.com");
Text clickableCommand = TextUtils.clickableCommand("Run help", "/help");
Text withTooltip = TextUtils.withTooltip("Hover me", "This is a tooltip");

// Combined interactive text
Text interactive = TextUtils.interactiveText("Click me", "Tooltip text", "https://example.com");

Text Wrapping and Formatting

// Text wrapping
List<String> wrapped = TextUtils.wrapText(longText, 40);
Text multiLineBox = TextUtils.createMultiLineTextBox(lines, 50);

// Number and duration formatting
String formatted = TextUtils.formatNumber(1234567); // "1,234,567"
String decimal = TextUtils.formatDecimal(123.456, 2); // "123.46"
String duration = TextUtils.formatDuration(90000); // "1m 30s"

Enhanced Validation (with caching)

// Cached pattern matching for better performance
boolean isBlank = TextUtils.isBlank("   "); // true
boolean matches = TextUtils.matches("abc123", "[a-z0-9]+"); // Cached regex

// Progress bars with percentages
Text progressBar = TextUtils.progressBar(0.75, 20); // 75% progress

Legacy Text Operations

// Basic text operations (still available)
TextUtils.success("Operation completed!");
TextUtils.error("Something went wrong!");
String capitalized = TextUtils.capitalize("hello world");
boolean isEmail = TextUtils.isValidEmail("user@example.com");

🎒 Enhanced ItemUtils Examples ENHANCED

ItemUtils now includes inventory operations and performance optimizations.

Enhanced Item Operations

// Enhanced validation
boolean canMerge = ItemUtils.canMerge(stack1, stack2);
boolean isDamageable = ItemUtils.isDamageable(stack);
boolean isEnchanted = ItemUtils.isEnchanted(stack);

// Item lookup by ID
Item item = ItemUtils.getItemById("minecraft:diamond_sword");
Item item2 = ItemUtils.getItemById(new Identifier("minecraft", "diamond_sword"));

// Enhanced durability operations
double durabilityPercent = ItemUtils.getDurabilityPercentage(stack);
ItemUtils.damageItem(stack, 10);
ItemUtils.repairItem(stack, 50);
ItemUtils.fullyRepairItem(stack);

Inventory Management

// Insert items into inventory
ItemStack remaining = ItemUtils.insertStack(inventory, stack);

// Consume items from inventory
int consumed = ItemUtils.consumeItem(inventory, Items.DIAMOND, 5);

// Count items in inventory
int total = ItemUtils.countItem(inventory, Items.DIAMOND);

// Find items in inventory
Optional<ItemStack> found = ItemUtils.findFirst(inventory, 
    stack -> stack.isEnchanted());
List<ItemStack> enchanted = ItemUtils.findAll(inventory,
    stack -> stack.isEnchanted());

NBT and Enchantments

// NBT operations
NbtCompound nbt = ItemUtils.getNbt(stack);
ItemUtils.setNbt(stack, nbtData);
boolean hasNbt = ItemUtils.hasNbt(stack);

// Enchantment operations
int level = ItemUtils.getEnchantmentLevel(stack, enchantment);
boolean hasEnchant = ItemUtils.hasEnchantment(stack, enchantment);

// Get all enchantments
Map<RegistryEntry<Enchantment>, Integer> enchantments = ItemUtils.getEnchantments(stack);

Performance Features

// Cached operations for better performance
String itemId = ItemUtils.getItemId(stack); // Cached
int maxStack = ItemUtils.getMaxStackSize(item); // Cached

// Cache management
String stats = ItemUtils.getCacheStats();
ItemUtils.clearCache();

🎨 Enhanced GuiUtils Examples ENHANCED

GuiUtils is now server-side compatible with client-side extensions.

Server-Side Color Operations

// Color creation (works on both client and server)
int red = GuiUtils.rgb(255, 0, 0);
int transparent = GuiUtils.rgba(255, 0, 0, 128);

// Color component extraction
int redComponent = GuiUtils.getRed(color);
int greenComponent = GuiUtils.getGreen(color);
int blueComponent = GuiUtils.getBlue(color);
int alphaComponent = GuiUtils.getAlpha(color);

// Color interpolation
int interpolated = GuiUtils.interpolateColor(red, blue, 0.5f);

Mathematical Operations

// Positioning (server-side compatible)
int centerX = GuiUtils.centerX(elementWidth, containerWidth);
int centerY = GuiUtils.centerY(elementHeight, containerHeight);

// Collision detection
boolean overlaps = GuiUtils.rectanglesOverlap(x1, y1, w1, h1, x2, y2, w2, h2);
boolean pointInRect = GuiUtils.isPointInRect(x, y, rectX, rectY, rectW, rectH);

// Distance calculation
double distance = GuiUtils.distance(x1, y1, x2, y2);

Client-Side Rendering (ClientGuiUtils)

// Import client-side utilities
import com.chosen.lib.util.client.ClientGuiUtils;

// Drawing operations (client-side only)
ClientGuiUtils.drawRect(context, x, y, width, height, color);
ClientGuiUtils.drawProgressBar(context, x, y, width, height, 0.75, bgColor, fgColor);
ClientGuiUtils.drawCenteredText(context, "Hello", centerX, y, color);

// Advanced drawing
ClientGuiUtils.drawBorderedRect(context, x, y, w, h, fillColor, borderColor, borderWidth);
ClientGuiUtils.drawGradient(context, x, y, w, h, startColor, endColor, horizontal);

🎯 Real-World Examples

Here are some practical examples using v1.4.0 features:

World Modification Tool

public class WorldTool {
    public void replaceOresInArea(ServerWorld world, BlockPos center, int radius) {
        // Find all diamond ores in area
        List<BlockPos> ores = WorldUtils.findBlocks(world, center, radius,
            state -> state.isOf(Blocks.DIAMOND_ORE));
        
        // Replace with emerald ore
        for (BlockPos pos : ores) {
            if (WorldUtils.canPlaceBlock(world, pos, Blocks.EMERALD_ORE.getDefaultState())) {
                WorldUtils.setBlockState(world, pos, Blocks.EMERALD_ORE.getDefaultState());
            }
        }
        
        TextUtils.success("Replaced " + ores.size() + " diamond ores with emerald ore!");
    }
}

Entity Management System

public class EntityManager {
    public void healNearbyPlayers(ServerWorld world, Vec3d center, double radius) {
        List<PlayerEntity> players = EntityUtils.getPlayersInRadius(world, center, radius);
        
        for (PlayerEntity player : players) {
            if (!EntityUtils.isFullHealth(player)) {
                EntityUtils.heal(player, 10.0f);
                
                // Send feedback
                Text message = TextUtils.success("You have been healed!");
                player.sendMessage(message, false);
            }
        }
    }
    
    public void teleportToSafety(Entity entity) {
        BlockPos safePos = WorldUtils.getHighestBlock(entity.getWorld(), 
            (int)entity.getX(), (int)entity.getZ());
        
        if (EntityUtils.safeTeleport(entity, safePos.up())) {
            TextUtils.success("Teleported to safety!");
        } else {
            TextUtils.error("Could not find safe location!");
        }
    }
}

Network Communication System

public class NetworkManager {
    public static final Identifier CHANNEL_ID = new Identifier("mymod", "data");
    
    public void sendPlayerData(ServerPlayerEntity player, String data, int value) {
        PacketByteBuf buffer = NetworkUtils.createBuffer(buf -> {
            NetworkUtils.writeString(buf, data);
            buf.writeInt(value);
            NetworkUtils.writeBlockPos(buf, player.getBlockPos());
        });
        
        NetworkUtils.sendToPlayer(player, CHANNEL_ID, buffer);
    }
    
    public void broadcastToArea(ServerWorld world, Vec3d center, String message) {
        PacketByteBuf buffer = NetworkUtils.createSimplePacket(message);
        NetworkUtils.sendToPlayersInRadius(world, center, 100.0, CHANNEL_ID, buffer);
    }
}

Advanced Inventory System

public class InventoryManager {
    public boolean processRecipe(Inventory inventory, Item input, Item output, int count) {
        // Check if we have enough input items
        int available = ItemUtils.countItem(inventory, input);
        if (available < count) {
            TextUtils.error("Not enough " + ItemUtils.getItemId(input.getDefaultStack()));
            return false;
        }
        
        // Consume input items
        int consumed = ItemUtils.consumeItem(inventory, input, count);
        
        // Create output stack
        ItemStack outputStack = new ItemStack(output, consumed);
        
        // Try to insert output
        ItemStack remaining = ItemUtils.insertStack(inventory, outputStack);
        
        if (remaining.isEmpty()) {
            TextUtils.success("Recipe processed successfully!");
            return true;
        } else {
            TextUtils.error("Not enough space for output!");
            return false;
        }
    }
}

⚡ Performance Features

ChosenLib v1.4.0 includes comprehensive performance optimizations:

Caching Systems

// ItemUtils caching
String itemId = ItemUtils.getItemId(stack); // Cached for performance
int maxStack = ItemUtils.getMaxStackSize(item); // Cached

// TextUtils caching
boolean matches = TextUtils.matches(text, regex); // Regex patterns cached
String formatted = TextUtils.formatNumber(123456); // Formatters cached

// Cache management
String itemStats = ItemUtils.getCacheStats();
String textStats = TextUtils.getCacheStats();

// Clear caches if needed
ItemUtils.clearCache();
TextUtils.clearCache();

Thread Safety

  • All caches use ConcurrentHashMap for thread-safe operations
  • Utility methods are designed to be thread-safe
  • No shared mutable state between method calls

💡 Best Practices

Performance Tips

  • Use caching features: ItemUtils and TextUtils cache frequently used data
  • Batch operations: Use area operations instead of individual block operations
  • Validate before processing: Check if positions are loaded before world operations
  • Use appropriate radius: Don't use unnecessarily large search radii

Code Organization

  • Separate client and server: Use ClientGuiUtils for client-side rendering
  • Handle errors gracefully: Always check return values and handle failures
  • Use meaningful feedback: Provide clear messages to users
  • Validate inputs: Check for null values and valid ranges

Network Best Practices

  • Minimize packet size: Only send necessary data
  • Use appropriate targeting: Don't broadcast when you can send to specific players
  • Handle packet failures: Use safe operations when possible
  • Validate packet data: Always validate received data

📚 API Stability: The current API (v1.4.0) is stable for production use. While we plan new features for v1.5.0-1.9.0, we maintain backward compatibility. See our changelog for detailed migration information.

🔗 Next Steps

Now that you understand the v1.4.0 features, explore these resources:

📚 API Reference

Complete documentation for all v1.4.0 methods and classes.

View API

📋 Changelog

See detailed information about v1.4.0 changes and improvements.

View Changelog

🚀 Getting Started

Learn how to set up ChosenLib v1.4.0 in your project.

Get Started