### Run Client with Gradle Wrapper Source: https://github.com/ldtteam/minecolonies/blob/version/main/README.md Alternatively, use this command to start Minecraft directly with the compiled MineColonies jar. This is useful for testing. ```bash ./gradlew runClient ``` -------------------------------- ### Install Gradle on Gentoo Source: https://github.com/ldtteam/minecolonies/blob/version/main/README.md Use this command to install the binary version of Gradle on Gentoo Linux. ```bash emerge dev-java/gradle-bin ``` -------------------------------- ### Install Gradle on Ubuntu/Debian Source: https://github.com/ldtteam/minecolonies/blob/version/main/README.md Use this command to install Gradle on Ubuntu or Debian-based Linux distributions. ```bash apt-get install gradle ``` -------------------------------- ### Run Gradle Tasks for Eclipse Setup Source: https://github.com/ldtteam/minecolonies/blob/version/main/documentation/eclipse/setup.MD Execute these Gradle commands to prepare your workspace for Eclipse development. Ensure you run 'setupDecompWorkspace' before 'eclipse'. ```bash gradlew setupDecompWorkspace gradlew eclipse ``` -------------------------------- ### Manage Player Permissions with IPermissions Source: https://context7.com/ldtteam/minecolonies/llms.txt Access permissions via colony.getPermissions(). Check player permissions for actions, get player ranks, add/remove players, alter permissions for ranks, and create custom ranks. Use Action enum for specific in-world actions. ```java import com.minecolonies.api.colony.permissions.Action; import com.minecolonies.api.colony.permissions.IPermissions; import com.minecolonies.api.colony.permissions.Rank; IPermissions perms = colony.getPermissions(); // ── Check permissions ──────────────────────────────────────────────────────── boolean canBreak = perms.hasPermission(player, Action.BREAK_HUTS); boolean canAccess = perms.hasPermission(player, Action.ACCESS_HUTS); // ── Rank of a player ───────────────────────────────────────────────────────── Rank rank = perms.getRank(player); Rank owner = perms.getRankOwner(); UUID ownerUUID = perms.getOwner(); String ownerName = perms.getOwnerName(); // ── Add/promote a player ───────────────────────────────────────────────────── boolean added = perms.addPlayer(player.getGameProfile(), perms.getRankFriend()); perms.setPlayerRank(player.getUUID(), perms.getRankOfficer(), world); // ── Remove a player ─────────────────────────────────────────────────────────── perms.removePlayer(player.getUUID()); // ── Toggle an action for a rank ────────────────────────────────────────────── // Give FRIEND rank permission to place blocks Rank actorRank = perms.getRankOfficer(); // only officer+ may alter perms.alterPermission(actorRank, perms.getRankFriend(), Action.PLACE_BLOCKS, true); // Hard set without actor check (admin tool / command use): perms.setPermission(perms.getRankNeutral(), Action.OPEN_CONTAINER, false); // ── Create a custom rank ───────────────────────────────────────────────────── perms.addRank("Foreman"); Map allRanks = perms.getRanks(); // ── Membership test ─────────────────────────────────────────────────────────── boolean isMember = perms.isColonyMember(player); Set officers = perms.getPlayersByRank(perms.getRankOfficer()); ``` -------------------------------- ### Accessing and Modifying Colony Properties Source: https://context7.com/ldtteam/minecolonies/llms.txt Obtain an IColony instance and access its identity, geometry, and visual style properties. Use this to get or set colony details like name, center position, happiness, and visual configurations. ```java import com.minecolonies.api.colony.IColony; import com.minecolonies.api.colony.ColonyState; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; IColony colony = IColonyManager.getInstance().getColonyByWorld(1, world); if (colony == null) return; // ── Basic identity ─────────────────────────────────────────────────────────── int id = colony.getID(); // e.g. 1 String name = colony.getName(); // e.g. "New Hope" colony.setName("Rising Tide"); BlockPos center = colony.getCenter(); // Town Hall block position boolean isDay = colony.isDay(); double happy = colony.getOverallHappiness(); // 0.0 – 10.0 int day = colony.getDay(); // colony day counter int lastContact = colony.getLastContactInHours(); // for auto-delete checks // ── Geometry ───────────────────────────────────────────────────────────────── boolean inside = colony.isCoordInColony(world, new BlockPos(110, 64, 210)); long distSq = colony.getDistanceSquared(new BlockPos(200, 64, 300)); // ── Visual style ───────────────────────────────────────────────────────────── colony.setColonyColor(ChatFormatting.GOLD); colony.setStructurePack("medieval_oak"); // building schematic pack colony.setTextureStyle("medieval"); // citizen skin pack colony.setNameStyle("nordic"); // citizen name generator // ── Lifecycle / state ──────────────────────────────────────────────────────── ColonyState state = colony.getState(); // ACTIVE | INACTIVE | UNLOADED boolean active = colony.isActive(); boolean attacked = colony.isColonyUnderAttack(); // ── Waypoints (navigation helpers for citizens) ────────────────────────────── colony.addWayPoint(new BlockPos(105, 64, 205), Blocks.COBBLESTONE.defaultBlockState()); Map waypoints = colony.getWayPoints(); // ── Persist / load (called by Forge world save) ────────────────────────────── CompoundTag tag = colony.write(new CompoundTag()); colony.read(tag); ``` -------------------------------- ### Build MineColonies using Gradle Wrapper Source: https://github.com/ldtteam/minecolonies/blob/version/main/README.md Execute this command in the MineColonies folder to build the project. This command also sets up Forge and downloads necessary libraries. It may take a while to complete. ```bash gradlew build ``` -------------------------------- ### Edit .classpath for Minecolonies Source: https://github.com/ldtteam/minecolonies/blob/version/main/documentation/eclipse/setup.MD Remove specific classpath entries from your .classpath file to resolve potential conflicts or issues during Eclipse setup. These entries often relate to build output directories. ```xml ``` -------------------------------- ### Configure VM Arguments for Log4j2 Source: https://github.com/ldtteam/minecolonies/blob/version/main/documentation/eclipse/logging.MD Add this to your launch target VM arguments to enable Log4j2 configuration. ```bash -Dlog4j.configurationFile=log4j2.xml ``` -------------------------------- ### Register a New Factory to the SFC Source: https://github.com/ldtteam/minecolonies/wiki/Standard-Factory-Manager Register a new factory implementation with the Standard Factory Controller. This is typically done during the game's initialization phase. ```java StandardFactoryController.getInstance().registerNewFactory(factory); ``` -------------------------------- ### Commit and Push Local Changes Source: https://github.com/ldtteam/minecolonies/blob/version/main/README.md Use these commands in your command line to stage all changes, commit them with a message, and then push them to your forked repository. This is part of the process for submitting a pull request. ```bash git commit -a ``` ```bash git push ``` -------------------------------- ### Generate IntelliJ Run Configurations Source: https://github.com/ldtteam/minecolonies/blob/version/main/README.md Execute this Gradle task within IntelliJ IDEA to generate necessary run configurations for client and server. Restart IntelliJ after execution. ```bash genIntellijRuns ``` -------------------------------- ### Manage Colony Quests with IQuestManager Source: https://context7.com/ldtteam/minecolonies/llms.txt Handle quest availability, acceptance, progress, and colony reputation. Retrieve via `colony.getQuestManager()`. Use `attemptAcceptQuest` with caution as it can fail due to low reputation or existing quests. ```java import com.minecolonies.api.quests.IQuestManager; import com.minecolonies.api.quests.IQuestInstance; import net.minecraft.resources.ResourceLocation; IQuestManager qm = colony.getQuestManager(); // ── List quests ─────────────────────────────────────────────────────────────── List available = qm.getAvailableQuests(); List inProgress = qm.getInProgressQuests(); List finished = qm.getFinishedQuests(); // ── Check & accept a quest ──────────────────────────────────────────────────── ResourceLocation questId = new ResourceLocation("minecolonies", "quests/explore_cave"); boolean unlocked = qm.isUnlocked(questId); if (unlocked) { boolean accepted = qm.attemptAcceptQuest(questId, player); // returns false if colony reputation is too low or quest already active } // ── Unlock / complete / delete ──────────────────────────────────────────────── qm.unlockQuest(questId); qm.completeQuest(questId); qm.deleteQuest(questId); // ── Colony reputation ───────────────────────────────────────────────────────── double rep = qm.getReputation(); qm.alterReputation(+5.0); // positive event qm.alterReputation(-2.5); // player upset villagers // ── Fetch active instance ──────────────────────────────────────────────────── IQuestInstance inst = qm.getAvailableOrInProgressQuest(questId); // null if absent ``` -------------------------------- ### Create a New Instance with No Input Source: https://github.com/ldtteam/minecolonies/wiki/Standard-Factory-Manager Create a new instance of a type that requires no input parameters. The SFC will automatically handle the instantiation. ```java NoArgs instance = StandardFactoryController.getInstance().getNewInstance(new TypeToken {}); ``` -------------------------------- ### Log4j2 Console Appender Configuration Source: https://github.com/ldtteam/minecolonies/blob/version/main/documentation/eclipse/logging.MD Create this log4j2.xml file in the project's /run directory to direct logs to the console. ```xml ``` -------------------------------- ### IColonyManager - Global colony registry Source: https://context7.com/ldtteam/minecolonies/llms.txt The IColonyManager is the singleton gateway to all colonies in the game. It allows for colony creation, lookup by various criteria, and enumeration. ```APIDOC ## IColonyManager ### Description The singleton gateway to all colonies in the game. Retrieved via `IColonyManager.getInstance()` (delegates to `IMinecoloniesAPI`). Provides colony creation, lookup by world/dimension/position/owner, and event callbacks for world lifecycle and network view synchronisation. ### Methods #### `createColony` Creates a new colony at the specified position. - **Parameters** - `world` (Level) - The world in which to create the colony. - `townHallPos` (BlockPos) - The position of the Town Hall. - `founder` (Player) - The player founding the colony. - `colonyName` (String) - The name of the colony. - `styleName` (String) - The style of the colony. - **Returns** - `IColony` - The newly created colony, or null if the position is inside an existing colony's claim zone. #### `isFarEnoughFromColonies` Checks if a position is sufficiently far from existing colonies. - **Parameters** - `world` (Level) - The world to check. - `pos` (BlockPos) - The position to check. - **Returns** - `boolean` - True if the position is far enough, false otherwise. #### `getColonyByWorld` Retrieves a colony by its integer ID within a specific world. - **Parameters** - `id` (int) - The ID of the colony. - `world` (Level) - The world the colony is in. - **Returns** - `IColony` - The colony with the specified ID, or null if not found. #### `getColonyByPosFromWorld` Retrieves a colony by its block position within a specific world. - **Parameters** - `world` (Level) - The world to search in. - `pos` (BlockPos) - The block position. - **Returns** - `IColony` - The colony at the specified position, or null if none found. #### `getIColonyByOwner` Retrieves a colony owned by a specific player in a given world. - **Parameters** - `world` (Level) - The world to search in. - `owner` (Player) - The owner of the colony. - **Returns** - `IColony` - The colony owned by the player, or null if none found. #### `getClosestColony` Finds the closest colony to a given position in a world. - **Parameters** - `world` (Level) - The world to search in. - `pos` (BlockPos) - The position to find the closest colony to. - **Returns** - `IColony` - The closest colony, or null if no colonies are found. #### `getAllColonies` Retrieves a list of all colonies in the game. - **Returns** - `List` - A list of all colonies. #### `getColonies` Retrieves a list of all colonies in a specific world. - **Parameters** - `world` (Level) - The world to list colonies from. - **Returns** - `List` - A list of colonies in the specified world. #### `getColoniesAbandonedSince` Retrieves a list of colonies that have been abandoned for a specified duration. - **Parameters** - `hours` (int) - The minimum number of hours since last contact for a colony to be considered abandoned. - **Returns** - `List` - A list of abandoned colonies. #### `deleteColonyByWorld` Deletes a colony by its ID in a specific world. - **Parameters** - `id` (int) - The ID of the colony to delete. - `canDestroy` (boolean) - Whether to destroy the colony's structures. - `world` (Level) - The world the colony is in. #### `isCoordinateInAnyColony` Checks if a given coordinate is within any claimed colony area. - **Parameters** - `world` (Level) - The world to check. - `pos` (BlockPos) - The coordinate to check. - **Returns** - `boolean` - True if the coordinate is in any colony, false otherwise. ``` -------------------------------- ### Pull Latest Changes from Repository Source: https://github.com/ldtteam/minecolonies/blob/version/main/README.md Execute this command in your local repository's base folder to fetch and integrate the latest updates from the official repository. Ensure no uncommitted local changes exist before running. ```bash git pull version/1.16.3 ``` -------------------------------- ### Manage Build/Upgrade Orders with IWorkManager Source: https://context7.com/ldtteam/minecolonies/llms.txt Track and manage construction work orders for builders. Retrieved via `colony.getWorkManager()`. Use `addWorkOrder` for manual order creation and `removeWorkOrder` to cancel. ```java import com.minecolonies.api.colony.workorders.IWorkManager; import com.minecolonies.api.colony.workorders.IServerWorkOrder; IWorkManager wm = colony.getWorkManager(); // ── Inspect orders ──────────────────────────────────────────────────────────── Map all = wm.getWorkOrders(); IServerWorkOrder byId = wm.getWorkOrder(1); // ── Find the first unclaimed build order ───────────────────────────────────── IServerWorkOrder unclaimed = wm.getUnassignedWorkOrder(IBuildingWorkOrder.class); // ── Get ordered list by priority for a specific builder ────────────────────── BlockPos builderPos = new BlockPos(130, 64, 130); List buildOrders = wm.getOrderedList(IBuildingWorkOrder.class, builderPos); // ── Add a manual order (called by building.requestUpgrade internally) ───────── wm.addWorkOrder(new BuildingUpgradeWorkOrder( colony, building, building.getBuildingLevel() + 1, building.getPosition()), /*readingFromNbt=*/false); // ── Remove an order ─────────────────────────────────────────────────────────── if (unclaimed != null) { wm.removeWorkOrder(unclaimed); } // ── Clear orders when a citizen is removed ──────────────────────────────────── ICitizenData builder = colony.getCitizen(7); wm.clearWorkForCitizen(builder); ``` -------------------------------- ### Accessing Server Configuration Values in Java Source: https://context7.com/ldtteam/minecolonies/llms.txt Use MineColonies.getConfig().getServer() to access server-side configuration values. These values are typically retrieved using a .get() method. ```java // Access at runtime via MineColonies.getConfig().getServer() import com.minecolonies.api.configuration.Configurations; int maxCits = MineColonies.getConfig().getServer().maxCitizenPerColony.get(); boolean pvp = MineColonies.getConfig().getServer().pvp_mode.get(); boolean raids = MineColonies.getConfig().getServer().enableColonyRaids.get(); ``` -------------------------------- ### Define a Basic Java Class Source: https://github.com/ldtteam/minecolonies/wiki/Example-Class This snippet shows the structure of a simple Java class with a constant, a private field, a constructor, and a method. Ensure proper syntax for class definition and member declaration. ```java /**/ public class MyClass { public static final String MY_TEXT_CONSTANT = "Foobar"; private final int initial = 0; public MyClass( ) { } public void someMethod( ) { final int initial = this.initial; } /**/ } /**/ ``` -------------------------------- ### ICitizenManager - Citizen Lifecycle Source: https://context7.com/ldtteam/minecolonies/llms.txt Manages the spawning, tracking, and removal of citizen NPCs within a colony. ```APIDOC ## ICitizenManager - Citizen Lifecycle ### Description Sub-manager of `IColony` responsible for spawning, tracking, and removing citizen NPCs. Access via `colony.getCitizenManager()`. ### Methods - **getCurrentCitizenCount()**: Returns the number of living citizens currently in the colony. - **getMaxCitizens()**: Returns the maximum number of citizens the colony can support (based on beds). - **getPotentialMaxCitizens()**: Returns the potential maximum number of citizens, including beds from guard towers. - **calculateMaxCitizens()**: Forces a recalculation of the maximum citizen count after a building change. - **getCitizens()**: Returns a list of `ICitizenData` for all citizens in the colony. - **spawnOrCreateCitizen()**: Spawns a new citizen or creates data for one if needed. - **spawnOrCreateCitizen(Object data, World world, BlockPos pos)**: Spawns a citizen at a specific location, optionally with provided data. - **resurrectCivilianData(CompoundTag savedNBT, boolean resetId, World world, BlockPos pos)**: Resurrects a dead citizen from saved NBT data. - **checkCitizensForHappiness()**: Updates citizen happiness levels. - **updateCitizenMourn(ICitizenData citizen, boolean mourn)**: Updates the mourning status for a specific citizen. - **getCivilian(int id)**: Retrieves a specific citizen by their integer ID. - **getJoblessCitizen()**: Returns the first available jobless citizen, or null if none exist. - **getRandomCitizen()**: Returns a random citizen from the colony. ``` -------------------------------- ### Build MineColonies Jar in IntelliJ Source: https://github.com/ldtteam/minecolonies/blob/version/main/README.md Execute the 'build' task within IntelliJ IDEA to produce a runnable jar file. The output will be located in `basefolder\MineColonies\build\libs`. ```bash build ``` -------------------------------- ### Manage Colonies with IColonyManager Source: https://context7.com/ldtteam/minecolonies/llms.txt Use `IColonyManager` to create, retrieve, delete, and check for the existence of colonies. Ensure sufficient distance from existing colonies before creation. ```java import com.minecolonies.api.colony.IColonyManager; import com.minecolonies.api.colony.IColony; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; // ── Create a colony (server-side, e.g. on supply-ship placement) ───────────── IColonyManager mgr = IColonyManager.getInstance(); Level world = serverLevel; // ServerLevel reference BlockPos townHallPos = new BlockPos(100, 64, 200); Player founder = serverPlayer; IColony colony = mgr.createColony(world, townHallPos, founder, "New Hope", "medieval_oak"); // colony is null only when the position is inside an existing colony's claim zone // ── Guard against placing too close to an existing colony ─────────────────── if (!mgr.isFarEnoughFromColonies(world, townHallPos)) { founder.sendSystemMessage(Component.literal("Too close to another colony!")); return; } // ── Retrieve an existing colony ───────────────────────────────────────────── IColony byId = mgr.getColonyByWorld(1, world); // by integer id IColony atPos = mgr.getColonyByPosFromWorld(world, townHallPos); // by block position IColony owned = mgr.getIColonyByOwner(world, founder); // by owner Player IColony closest = mgr.getClosestColony(world, new BlockPos(90, 64, 190)); // ── Enumerate colonies ─────────────────────────────────────────────────────── List all = mgr.getAllColonies(); List inWorld = mgr.getColonies(world); List abandoned = mgr.getColoniesAbandonedSince(72); // last contact >72 h ago // ── Delete a colony ───────────────────────────────────────────────────────── mgr.deleteColonyByWorld(colony.getID(), /*canDestroy=*/false, world); // ── Check membership of any colony at an arbitrary position ───────────────── boolean occupied = mgr.isCoordinateInAnyColony(world, new BlockPos(500, 64, 500)); // → true if the position is claimed by any colony ``` -------------------------------- ### Convert to Wildcard Import in Java Source: https://github.com/ldtteam/minecolonies/wiki/Classes-&-Interfaces When using five or more classes from the same package, convert to a wildcard import for brevity. Ensure imports are correctly formatted. ```java import my.company.package.ClassA; import my.company.package.ClassB; import my.company.package.ClassC; import my.company.package.ClassD; import my.company.package.ClassE; ``` ```java import my.company.package.*; ``` -------------------------------- ### Managing Citizen Population and Spawning Source: https://context7.com/ldtteam/minecolonies/llms.txt Utilize the ICitizenManager to control the colony's population. This includes checking current and maximum citizen counts, iterating through existing citizens, and spawning new citizens. ```java import com.minecolonies.api.colony.ICitizenData; import com.minecolonies.api.colony.managers.interfaces.ICitizenManager; ICitizenManager cm = colony.getCitizenManager(); // ── Population census ──────────────────────────────────────────────────────── int current = cm.getCurrentCitizenCount(); // living citizens right now int max = cm.getMaxCitizens(); // beds available int potential = cm.getPotentialMaxCitizens(); // including guard-tower beds cm.calculateMaxCitizens(); // force recalculation after building change // ── Iterate citizens ────────────────────────────────────────────────────────── List citizens = cm.getCitizens(); for (ICitizenData cit : citizens) { System.out.printf(" [%d] %s job=%s saturation=%.1f%n", cit.getId(), cit.getName(), cit.getJob() != null ? cit.getJob().getJobRegistryEntry().getKey() : "none", cit.getSaturation()); } // ── Spawn a brand-new citizen (e.g. after building a new house) ────────────── cm.spawnOrCreateCitizen(); // game will create data + entity automatically // ── Spawn at a specific location ───────────────────────────────────────────── BlockPos spawnAt = new BlockPos(103, 65, 203); cm.spawnOrCreateCitizen(null, world, spawnAt); // null → generate new CitizenData // ── Resurrect a dead citizen from saved NBT (Undertaker mechanic) ──────────── CompoundTag savedNBT = ...; // previously serialised citizen tag ICitizenData resurrected = cm.resurrectCivilianData(savedNBT, /*resetId=*/false, world, new BlockPos(100, 64, 200)); // ── Happiness & mourn propagation ──────────────────────────────────────────── cm.checkCitizensForHappiness(); cm.updateCitizenMourn(resurrected, /*mourn=*/false); // ── Retrieve a single citizen ──────────────────────────────────────────────── ICitizenData cit = cm.getCivilian(3); // by integer id ICitizenData jobless = cm.getJoblessCitizen(); // first unemployed citizen or null ICitizenData random = cm.getRandomCitizen(); ``` -------------------------------- ### InventoryUtils Source: https://context7.com/ldtteam/minecolonies/llms.txt A static utility class providing various functions for interacting with IItemHandler instances, such as filtering, counting, moving, and removing items. ```APIDOC ## InventoryUtils ### Description A static utility class providing various functions for interacting with IItemHandler instances, such as filtering, counting, moving, and removing items. ### Methods - `filterItemHandler(IItemHandler handler, Item item)`: Filters an item handler to find all stacks of a specific item. - `filterItemHandler(IItemHandler handler, Predicate predicate)`: Filters an item handler based on a custom item stack predicate. - `findFirstSlotInItemHandlerWith(IItemHandler handler, Item item)`: Finds the slot index of the first stack containing a specific item. - `getItemCountInItemHandler(IItemHandler handler, Predicate predicate)`: Counts the total number of items in an item handler that match a predicate. - `hasItemInItemHandler(IItemHandler handler, Predicate predicate, int count)`: Checks if an item handler contains at least a specified count of items matching a predicate. - `transferItemStackIntoNextFreeSlotInItemHandler(IItemHandler sourceHandler, int sourceSlot, IItemHandler destinationHandler)`: Transfers an item stack from a source slot to the next free slot in a destination handler. - `removeStackFromItemHandler(IItemHandler handler, ItemStack stack)`: Removes a specific item stack from an item handler. - `shrinkItemCountInItemHandler(IItemHandler handler, Predicate predicate)`: Shrinks the count of the first item stack found that matches the predicate by one. ``` -------------------------------- ### Create a New Instance of a Type Source: https://github.com/ldtteam/minecolonies/wiki/Standard-Factory-Manager Request a new instance of a specific type from the SFC. This method can accept additional parameters for object construction. ```java Type instance = StandardFactoryController.getInstance().getNewInstance(inputType, new TypeToken {}, additionalParam1, additionalParam2); ``` -------------------------------- ### Manage Crafting Recipes with IRecipeManager Source: https://context7.com/ldtteam/minecolonies/llms.txt Use IRecipeManager to cache, add, retrieve, and track the usage of crafting recipes. Obtain the manager via IColonyManager.getInstance().getRecipeManager(). ```java import com.minecolonies.api.crafting.IRecipeManager; import com.minecolonies.api.crafting.IRecipeStorage; import com.minecolonies.api.colony.requestsystem.token.IToken; IRecipeManager recipeManager = IColonyManager.getInstance().getRecipeManager(); // ── Add / look up a recipe ──────────────────────────────────────────────────── IRecipeStorage storage = StandardFactoryController.getInstance() .getNewInstance(TypeConstants.RECIPE, ...); // built by RecipeStorage.of(...) IToken token = recipeManager.checkOrAddRecipe(storage); // idempotent // ── Retrieve by token ──────────────────────────────────────────────────────── IRecipeStorage fetched = recipeManager.getRecipe(token); ItemStack output = fetched.getPrimaryOutput(); List inputs = fetched.getInput(); // ── Full recipe catalog ─────────────────────────────────────────────────────── ImmutableMap, IRecipeStorage> all = recipeManager.getRecipes(); // ── Record a recipe as "used" (for analytics / optimization) ───────────────── recipeManager.registerUse(token); // ── Persistence (world save / load) ────────────────────────────────────────── CompoundTag nbt = new CompoundTag(); recipeManager.write(nbt); recipeManager.read(nbt); // ── World shutdown cleanup ──────────────────────────────────────────────────── recipeManager.reset(); ``` -------------------------------- ### Clone MineColonies Repository Source: https://github.com/ldtteam/minecolonies/blob/version/main/README.md Use this command to clone the MineColonies source code from GitHub into your specified base folder. ```bash git clone https://github.com/Minecolonies/minecolonies.git ``` -------------------------------- ### Brace Placement Convention in Java Source: https://github.com/ldtteam/minecolonies/wiki/Classes-&-Interfaces Opening braces for classes, methods, and blocks should be placed on a new line. This formatting ensures consistent code structure. ```java public class MyClassName { // class content } ``` -------------------------------- ### Utility for Item Handling with InventoryUtils Source: https://context7.com/ldtteam/minecolonies/llms.txt InventoryUtils provides static methods for filtering, counting, finding, transferring, and removing items across various IItemHandler implementations. Ensure you have the correct IItemHandler instance. ```java import com.minecolonies.api.util.InventoryUtils; import net.minecraftforge.items.IItemHandler; import net.minecraft.world.item.Items; import net.minecraft.world.item.ItemStack; IItemHandler handler = building.getCapability(ForgeCapabilities.ITEM_HANDLER).orElseThrow(); // ── Filter: find all oak log stacks ────────────────────────────────────────── List logs = InventoryUtils.filterItemHandler(handler, Items.OAK_LOG); // ── Filter with arbitrary predicate ────────────────────────────────────────── List food = InventoryUtils.filterItemHandler(handler, stack -> stack.getItem().isEdible()); // ── Find first slot index ───────────────────────────────────────────────────── int slot = InventoryUtils.findFirstSlotInItemHandlerWith(handler, Items.IRON_PICKAXE); if (slot == -1) System.out.println("No pickaxe found"); // ── Count total items matching a predicate ──────────────────────────────────── int logCount = InventoryUtils.getItemCountInItemHandler(handler, stack -> stack.is(Items.OAK_LOG)); // ── Check if handler has a minimum count ───────────────────────────────────── boolean hasEnough = InventoryUtils.hasItemInItemHandler(handler, stack -> stack.is(Items.OAK_LOG), 64); // ── Transfer one stack to player inventory ─────────────────────────────────── boolean transferred = InventoryUtils.transferItemStackIntoNextFreeSlotInItemHandler( handler, slot, new InvWrapper(player.getInventory())); // ── Remove a specific amount from handler ──────────────────────────────────── boolean removed = InventoryUtils.removeStackFromItemHandler(handler, new ItemStack(Items.OAK_LOG, 16)); // ── Shrink first matching stack by 1 ──────────────────────────────────────── InventoryUtils.shrinkItemCountInItemHandler(handler, stack -> stack.is(Items.COAL)); ``` -------------------------------- ### Manage Colony Buildings with IRegisteredStructureManager Source: https://context7.com/ldtteam/minecolonies/llms.txt Obtain the building manager via colony.getServerBuildingManager(). Use it to look up buildings, manage warehouses, set leisure sites, query guard proximity, check colony prestige, manage chunk loading, and validate new building placements. ```java import com.minecolonies.api.colony.buildings.IBuilding; import com.minecolonies.api.colony.buildings.workerbuildings.IWareHouse; import com.minecolonies.api.colony.managers.interfaces.IRegisteredStructureManager; IRegisteredStructureManager bm = colony.getServerBuildingManager(); // ── Lookup ──────────────────────────────────────────────────────────────────── Map all = bm.getBuildings(); IBuilding at = bm.getBuilding(new BlockPos(120, 64, 220)); // null if absent ITownHall th = bm.getTownHall(); // null before TH placed // ── Warehouses ──────────────────────────────────────────────────────────────── List warehouses = bm.getWareHouses(); IWareHouse closest = bm.getClosestWarehouseInColony(new BlockPos(150, 64, 150)); // ── Leisure sites (citizens relax here) ────────────────────────────────────── bm.addLeisureSite(new BlockPos(112, 64, 212)); List leisure = bm.getLeisureSites(); BlockPos randomLeisure = bm.getRandomLeisureSite(); bm.removeLeisureSite(new BlockPos(112, 64, 212)); // ── Guard proximity query ───────────────────────────────────────────────────── boolean guardNearby = bm.hasGuardBuildingNear(at); bm.guardBuildingChangedAt(at, 3); // notify after guard tower reached level 3 // ── Prestige (cosmetic score) ───────────────────────────────────────────────── int prestige = bm.getColonyPrestige(); // ── Chunk retention ─────────────────────────────────────────────────────────── LevelChunk chunk = world.getChunkAt(new BlockPos(120, 64, 220)); boolean keep = bm.keepChunkColonyLoaded(chunk); // ── Validate new building placement ────────────────────────────────────────── boolean canPlace = bm.canPlaceAt(ModBlocks.blockHutMiner.get(), new BlockPos(140, 64, 140), player); ``` -------------------------------- ### IQuestManager Source: https://context7.com/ldtteam/minecolonies/llms.txt Manages quest availability, acceptance, progress, and reputation for a colony, including listing, checking, accepting, and managing quests. ```APIDOC ### `IQuestManager` — Colony quest system Manages quest availability, acceptance, progress, and reputation for a colony. Retrieved via `colony.getQuestManager()`. ```java import com.minecolonies.api.quests.IQuestManager; import com.minecolonies.api.quests.IQuestInstance; import net.minecraft.resources.ResourceLocation; IQuestManager qm = colony.getQuestManager(); // ── List quests ─────────────────────────────────────────────────────────────── List available = qm.getAvailableQuests(); List inProgress = qm.getInProgressQuests(); List finished = qm.getFinishedQuests(); // ── Check & accept a quest ──────────────────────────────────────────────────── ResourceLocation questId = new ResourceLocation("minecolonies", "quests/explore_cave"); boolean unlocked = qm.isUnlocked(questId); if (unlocked) { boolean accepted = qm.attemptAcceptQuest(questId, player); // returns false if colony reputation is too low or quest already active } // ── Unlock / complete / delete ──────────────────────────────────────────────── qm.unlockQuest(questId); qm.completeQuest(questId); qm.deleteQuest(questId); // ── Colony reputation ───────────────────────────────────────────────────────── double rep = qm.getReputation(); qm.alterReputation(+5.0); // positive event qm.alterReputation(-2.5); // player upset villagers // ── Fetch active instance ──────────────────────────────────────────────────── IQuestInstance inst = qm.getAvailableOrInProgressQuest(questId); // null if absent ``` ``` -------------------------------- ### IWorkManager Source: https://context7.com/ldtteam/minecolonies/llms.txt Tracks all queued construction work orders (build, upgrade, repair, remove) that Builders will claim. Allows inspection, addition, and removal of work orders. ```APIDOC ### `IWorkManager` — Build / upgrade work orders Tracks all queued construction work orders (build, upgrade, repair, remove) that Builders will claim. Retrieved via `colony.getWorkManager()`. ```java import com.minecolonies.api.colony.workorders.IWorkManager; import com.minecolonies.api.colony.workorders.IServerWorkOrder; IWorkManager wm = colony.getWorkManager(); // ── Inspect orders ──────────────────────────────────────────────────────────── Map all = wm.getWorkOrders(); IServerWorkOrder byId = wm.getWorkOrder(1); // ── Find the first unclaimed build order ───────────────────────────────────── IServerWorkOrder unclaimed = wm.getUnassignedWorkOrder(IBuildingWorkOrder.class); // ── Get ordered list by priority for a specific builder ────────────────────── BlockPos builderPos = new BlockPos(130, 64, 130); List buildOrders = wm.getOrderedList(IBuildingWorkOrder.class, builderPos); // ── Add a manual order (called by building.requestUpgrade internally) ───────── wm.addWorkOrder(new BuildingUpgradeWorkOrder( colony, building, building.getBuildingLevel() + 1, building.getPosition()), /*readingFromNbt=*/false); // ── Remove an order ─────────────────────────────────────────────────────────── if (unclaimed != null) { wm.removeWorkOrder(unclaimed); } // ── Clear orders when a citizen is removed ──────────────────────────────────── ICitizenData builder = colony.getCitizen(7); wm.clearWorkForCitizen(builder); ``` ``` -------------------------------- ### IBuilding - Colony building Source: https://context7.com/ldtteam/minecolonies/llms.txt Represents a player-built colony structure and provides methods for managing its metadata, upgrades, citizen assignments, and inventory. ```APIDOC ## IBuilding ### Description Represents any player-built colony structure (worker hut, Town Hall, Warehouse, Barracks, etc.). Obtained from `colony.getServerBuildingManager().getBuildings()` or via `IColonyManager.getInstance().getBuilding(world, pos)`. ### Methods - `getBuildingDisplayName()`: Returns the display name of the building. - `getCustomName()`: Returns the custom name set for the building. - `getBuildingLevel()`: Returns the current level of the building. - `getMaxBuildingLevel()`: Returns the maximum possible level for the building. - `isBuilt()`: Checks if the building has been fully constructed. - `isPendingConstruction()`: Checks if the building is currently under construction. - `setCustomBuildingName(String name)`: Sets a custom name for the building. - `requestUpgrade(ServerPlayer player, BlockPos builderPos)`: Requests an upgrade for the building. - `requestRepair(BlockPos repairPos)`: Requests a repair for the building. - `requestRemoval(ServerPlayer player, BlockPos removalPos)`: Requests the removal of the building. - `canAssignCitizens()`: Checks if citizens can be assigned to this building. - `getAllAssignedCitizen()`: Returns a set of all citizens assigned to this building. - `getMaxEquipmentLevel()`: Returns the maximum equipment level the building allows for its workers. - `forceTransferStack(ItemStack stack, World world)`: Attempts to transfer an item stack into the building's inventory. - `createRequest(ICitizenData citizen, Stack stack, boolean async)`: Creates a supply request for a citizen. - `isInBuilding(BlockPos pos)`: Checks if a given position is within the building's bounding box. ### Example Usage ```java IBuilding building = colony.getServerBuildingManager().getBuilding(new BlockPos(120, 64, 220)); // Metadata String displayName = building.getBuildingDisplayName(); String customName = building.getCustomName(); int level = building.getBuildingLevel(); int maxLevel = building.getMaxBuildingLevel(); boolean built = building.isBuilt(); boolean pending = building.isPendingConstruction(); // Custom name building.setCustomBuildingName("Deep Shaft Alpha"); // Request an upgrade or repair building.requestUpgrade(player, new BlockPos(130, 64, 130)); building.requestRepair(new BlockPos(130, 64, 130)); building.requestRemoval(player, new BlockPos(130, 64, 130)); // Assign citizens boolean canAssign = building.canAssignCitizens(); Set assigned = building.getAllAssignedCitizen(); // Equipment level the building allows its worker int maxEquip = building.getMaxEquipmentLevel(); // Inventory management ItemStack leftover = building.forceTransferStack(new ItemStack(Items.OAK_LOG, 64), world); // Create a supply request for a citizen ICitizenData miner = colony.getCitizen(5); IToken token = building.createRequest(miner, new Stack(new ItemStack(Items.IRON_PICKAXE)), false); // Check if a position is inside this building's bounding box boolean inside = building.isInBuilding(new BlockPos(121, 65, 221)); ``` ``` -------------------------------- ### IRecipeManager Source: https://context7.com/ldtteam/minecolonies/llms.txt Manages a world-wide cache of crafting recipes. Recipes can be added, retrieved by token, and their usage can be registered. Persistence is supported via NBT tags. ```APIDOC ## IRecipeManager ### Description Manages a world-wide cache of crafting recipes. Recipes can be added, retrieved by token, and their usage can be registered. Persistence is supported via NBT tags. ### Methods - `checkOrAddRecipe(IRecipeStorage storage)`: Checks if a recipe exists, adds it if not, and returns a token. - `getRecipe(IToken token)`: Retrieves a recipe storage by its token. - `getRecipes()`: Returns an immutable map of all registered recipes. - `registerUse(IToken token)`: Records that a recipe has been used. - `write(CompoundTag nbt)`: Writes the recipe manager's state to an NBT tag. - `read(CompoundTag nbt)`: Reads the recipe manager's state from an NBT tag. - `reset()`: Cleans up resources on world shutdown. ``` -------------------------------- ### Whitespace in Empty Method Arguments Source: https://github.com/ldtteam/minecolonies/wiki/Methods Add whitespace to empty method arguments for readability. ```java /**/ public void doSomething( ) { // Method content } /**/ ``` -------------------------------- ### IColony - Core Colony Object Source: https://context7.com/ldtteam/minecolonies/llms.txt Represents a single living colony and provides methods for managing its identity, geometry, visual style, and lifecycle. ```APIDOC ## IColony - Core Colony Object ### Description Represents a single living colony. Obtained from `IColonyManager`. Exposes identity, geometry, sub-managers, and lifecycle hooks. Server-side code works with `IColony`; client-side code receives `IColonyView`. ### Methods - **getID()**: Returns the unique integer ID of the colony. - **getName()**: Returns the name of the colony. - **setName(String name)**: Sets the name of the colony. - **getCenter()**: Returns the `BlockPos` of the Town Hall, representing the colony's center. - **isDay()**: Returns `true` if it is currently daytime in the colony's world. - **getOverallHappiness()**: Returns the overall happiness level of the colony (0.0 - 10.0). - **getDay()**: Returns the current colony day counter. - **getLastContactInHours()**: Returns the last contact time in hours, used for auto-delete checks. - **isCoordInColony(World world, BlockPos pos)**: Checks if a given coordinate is within the colony's boundaries. - **getDistanceSquared(BlockPos pos)**: Calculates the squared distance from the colony's center to a given position. - **setColonyColor(ChatFormatting color)**: Sets the visual color tint for the colony. - **setStructurePack(String packName)**: Sets the building schematic pack to be used for the colony. - **setTextureStyle(String styleName)**: Sets the citizen skin pack for the colony. - **setNameStyle(String styleName)**: Sets the citizen name generator style for the colony. - **getState()**: Returns the current `ColonyState` of the colony (ACTIVE, INACTIVE, UNLOADED). - **isActive()**: Returns `true` if the colony is currently active. - **isColonyUnderAttack()**: Returns `true` if the colony is currently under attack. - **addWayPoint(BlockPos pos, BlockState state)**: Adds a waypoint for citizen navigation. - **getWayPoints()**: Returns a map of all waypoints in the colony. - **write(CompoundTag tag)**: Serializes the colony's data into a `CompoundTag`. - **read(CompoundTag tag)**: Deserializes the colony's data from a `CompoundTag`. ``` -------------------------------- ### IRequestManager - Item / Resource Request System Source: https://context7.com/ldtteam/minecolonies/llms.txt Manages the centralized request-and-resolve pipeline for colony resources. Citizens declare needs, and resolvers fulfill them using IToken handles. ```APIDOC ## `IRequestManager` — Item / resource request system Each colony runs a centralised request-and-resolve pipeline. Citizens (requesters) declare what they need; resolvers (Couriers, Crafters, the player) fulfill those requests. All interactions happen via `IToken` handles. ### Create and immediately assign a request ```java IRequestManager rm = colony.getRequestManager(); IRequester building = colony.getRequesterBuildingForPosition(new BlockPos(120, 64, 220)); IToken token = rm.createAndAssignRequest(building, new Stack(new ItemStack(Items.IRON_INGOT, 32))); ``` ### Inspect the request ```java IRequest req = rm.getRequestForToken(token); if (req != null) { RequestState state = req.getState(); // QUEUED | ASSIGNED | IN_PROGRESS | RESOLVED System.out.println("State: " + state); } ``` ### Resolve state transitions ```java rm.updateRequestState(token, RequestState.RESOLVED); ``` ### Overrule: manually provide the item (admin shortcut) ```java rm.overruleRequest(token, new ItemStack(Items.IRON_INGOT, 32)); ``` ### Reassign after a resolver became unavailable ```java Collection> blacklist = List.of(token); // avoid previous resolver IToken newResolverToken = rm.reassignRequest(token, blacklist); ``` ### Notify after item availability changed (e.g. warehouse restocked) ```java rm.onColonyUpdate(request -> request.getState() == RequestState.QUEUED); ``` ### Persistence (called by colony NBT serialization) ```java CompoundTag nbt = rm.serializeNBT(); rm.deserializeNBT(nbt); ``` ``` -------------------------------- ### Serialize an Object Source: https://github.com/ldtteam/minecolonies/wiki/Standard-Factory-Manager Serialize an object into an NBTTagCompound for storage or transmission. The SFC handles the serialization process. ```java NBTTagCompound nbt = StandardFactoryController.getInstance().serialize(object); ```