repo_id
stringclasses
383 values
file_path
stringlengths
7
168
content
stringlengths
0
1.75M
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\kits\User.java
package hu.tryharddevs.advancedkits.kits; import com.google.common.collect.Maps; import hu.tryharddevs.advancedkits.AdvancedKitsMain; import hu.tryharddevs.advancedkits.kits.flags.DefaultFlags; import org.bukkit.ChatColor; import org.bukkit.configuration.file.YamlConfiguration; import java.io.File; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; import static hu.tryharddevs.advancedkits.kits.KitManager.getDifferenceText; public class User { private static HashMap<UUID, User> userHashMap = new HashMap<>(); private final UUID uuid; private List<String> unlockedList = new ArrayList<>(); private Map<String, Map<String, Boolean>> firstUseList = new HashMap<>(); private Map<String, Map<String, Double>> delaysList = new HashMap<>(); private Map<String, Map<String, Integer>> usedList = new HashMap<>(); private final AdvancedKitsMain instance = AdvancedKitsMain.getPlugin(); private YamlConfiguration userConfig; private User(UUID uuid) { this.uuid = uuid; this.userConfig = YamlConfiguration.loadConfiguration(getSaveFile()); if (this.userConfig.contains("UnlockedKits")) this.unlockedList = this.userConfig.getStringList("UnlockedKits"); Map<String, Object> tempMap; Map<String, Double> tempMapDouble; Map<String, Integer> tempMapInteger; Map<String, Boolean> tempMapBoolean; if (this.userConfig.contains("LastUseTime")) { for (String kit : this.userConfig.getConfigurationSection("LastUseTime").getKeys(false)) { tempMap = this.userConfig.getConfigurationSection("LastUseTime." + kit).getValues(false); tempMapDouble = tempMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, me -> Double.valueOf(me.getValue().toString()))); this.delaysList.put(kit, tempMapDouble); } } if (this.userConfig.contains("TimesUsed")) { for (String kit : this.userConfig.getConfigurationSection("TimesUsed").getKeys(false)) { tempMap = this.userConfig.getConfigurationSection("TimesUsed." + kit).getValues(false); tempMapInteger = tempMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, me -> Integer.valueOf(me.getValue().toString()))); this.usedList.put(kit, tempMapInteger); } } if (this.userConfig.contains("FirstUse")) { for (String kit : this.userConfig.getConfigurationSection("FirstUse").getKeys(false)) { tempMap = this.userConfig.getConfigurationSection("FirstUse." + kit).getValues(false); tempMapBoolean = tempMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, me -> Boolean.valueOf(me.getValue().toString()))); this.firstUseList.put(kit, tempMapBoolean); } } } public static User getUser(UUID uuid) { if (!userHashMap.containsKey(uuid)) { User user = new User(uuid); userHashMap.put(uuid, user); return user; } return userHashMap.get(uuid); } public void addToUnlocked(Kit kit) { this.unlockedList.add(kit.getName()); } public boolean isUnlocked(Kit kit) { return isUnlocked(kit.getName()); } private boolean isUnlocked(String name) { return this.unlockedList.contains(name); } public int getTimesUsed(Kit kit, String world) { if (this.usedList.containsKey(kit.getName())) { if (!kit.hasFlag(DefaultFlags.MAXUSES, world)) world = "global"; return this.usedList.get(kit.getName()).getOrDefault(world, 0); } return 0; } public boolean isFirstTime(Kit kit, String world) { if (this.firstUseList.containsKey(kit.getName())) { if (!kit.hasFlag(DefaultFlags.FIRSTJOIN, world)) world = "global"; return this.firstUseList.get(kit.getName()).getOrDefault(world, true); } return true; } public void setFirstTime(Kit kit, String world) { if (!this.firstUseList.containsKey(kit.getName())) this.firstUseList.put(kit.getName(), Maps.newHashMap()); if (!kit.hasFlag(DefaultFlags.FIRSTJOIN, world)) world = "global"; this.firstUseList.get(kit.getName()).put(world, false); } public void addUse(Kit kit, String world) { if (!this.usedList.containsKey(kit.getName())) this.usedList.put(kit.getName(), Maps.newHashMap()); if (!kit.hasFlag(DefaultFlags.MAXUSES, world)) world = "global"; int prevVal = 1; if (this.usedList.containsKey(kit.getName()) && this.usedList.get(kit.getName()).containsKey(world)) { prevVal += this.usedList.get(kit.getName()).get(world); } this.usedList.get(kit.getName()).put(world, prevVal); } public void setDelay(Kit kit, String world, double delay) { if (!this.delaysList.containsKey(kit.getName())) this.delaysList.put(kit.getName(), Maps.newHashMap()); if (!kit.hasFlag(DefaultFlags.DELAY, world)) world = "global"; this.delaysList.get(kit.getName()).put(world, System.currentTimeMillis() + (delay * 1000)); } public String getDelay(Kit kit, String world) { if (!kit.hasFlag(DefaultFlags.DELAY, world)) world = "global"; if (checkDelay(kit, world) || !this.delaysList.containsKey(kit.getName()) || !this.delaysList.get(kit.getName()).containsKey(world)) { return "None"; } Long delay = this.delaysList.get(kit.getName()).get(world).longValue(); Date date = new Date(delay); return getDifferenceText(new Date(System.currentTimeMillis()), date); } public boolean checkDelay(Kit kit, String world) { if (!this.delaysList.containsKey(kit.getName())) { return true; } if (!kit.hasFlag(DefaultFlags.DELAY, world)) world = "global"; if (!this.delaysList.get(kit.getName()).containsKey(world)) { return true; } Long delay = this.delaysList.get(kit.getName()).get(world).longValue(); return System.currentTimeMillis() >= delay; } public void save() { try { this.userConfig.set("UnlockedKits", this.unlockedList); this.userConfig.set("LastUseTime", this.delaysList); this.userConfig.set("TimesUsed", this.usedList); this.userConfig.save(getSaveFile()); } catch (IOException e) { this.instance.log(ChatColor.RED + "Please send this to the author of this plugin:"); this.instance.log(" -- StackTrace --"); e.printStackTrace(); this.instance.log(" -- End of StackTrace --"); } } private File getSaveFile() { if (!this.instance.getDataFolder().exists()) { this.instance.getDataFolder().mkdir(); } final File folder = new File(this.instance.getDataFolder(), "userfiles"); if (!folder.isDirectory()) { folder.mkdirs(); } File file = new File(this.instance.getDataFolder() + File.separator + "userfiles", this.uuid.toString() + ".yml"); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { this.instance.getLogger().info("Couldn't create the savefile for " + this.uuid.toString()); this.instance.getLogger().info(" -- StackTrace --"); e.printStackTrace(); this.instance.getLogger().info(" -- End of StackTrace --"); } } return file; } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\listeners\PlayerListener.java
package hu.tryharddevs.advancedkits.listeners; import hu.tryharddevs.advancedkits.AdvancedKitsMain; import hu.tryharddevs.advancedkits.Config; import hu.tryharddevs.advancedkits.kits.Kit; import hu.tryharddevs.advancedkits.kits.KitManager; import hu.tryharddevs.advancedkits.kits.User; import hu.tryharddevs.advancedkits.utils.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.block.*; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Objects; import static hu.tryharddevs.advancedkits.kits.flags.DefaultFlags.FIRSTJOIN; import static hu.tryharddevs.advancedkits.utils.MessagesApi.sendMessage; import static hu.tryharddevs.advancedkits.utils.localization.I18n.getMessage; public class PlayerListener implements Listener { private final AdvancedKitsMain instance; public PlayerListener(AdvancedKitsMain instance) { this.instance = instance; } @EventHandler public void onPlayerJoin(PlayerLoginEvent event) { final Player player = event.getPlayer(); User user = User.getUser(player.getUniqueId()); this.instance.getServer().getScheduler().scheduleSyncDelayedTask(instance, () -> KitManager.getKits().stream().filter(kit -> kit.getFlag(FIRSTJOIN, player.getWorld().getName()) && user.isFirstTime(kit, player.getWorld().getName())).forEach(kit -> { Bukkit.dispatchCommand(player, "advancedkitsreloaded:kit use " + kit.getName()); user.setFirstTime(kit, player.getWorld().getName()); }), 2L); } @EventHandler public void onPlayerLeave(PlayerQuitEvent event) { User.getUser(event.getPlayer().getUniqueId()).save(); } @EventHandler(priority = EventPriority.MONITOR) public void onBlockPlace(BlockPlaceEvent event) { ItemStack itemStack = event.getItemInHand(); if (Objects.isNull(itemStack) || !itemStack.hasItemMeta() || !itemStack.getItemMeta().hasDisplayName()) return; if (event.isCancelled()) return; final Block block = event.getBlock(); if (block.getType() == Material.CHEST) { Kit kit = KitManager.getKit(itemStack.getItemMeta().getDisplayName(), event.getPlayer().getWorld().getName()); if (Objects.nonNull(kit)) { if (Config.DISABLED_WORLDS.contains(event.getPlayer().getWorld().getName())) { sendMessage(event.getPlayer(), getMessage("kitUseDisabledInWorld")); event.setCancelled(true); return; } ArrayList<ItemStack> items = new ArrayList<>(kit.getItems()); items.addAll(kit.getArmors()); if ((items.size()) > 27 && event.canBuild()) { Block northBlock = block.getRelative(BlockFace.NORTH); Block southBlock = block.getRelative(BlockFace.SOUTH); Block westBlock = block.getRelative(BlockFace.WEST); Block eastBlock = block.getRelative(BlockFace.EAST); if (Objects.isNull(northBlock) || northBlock.getType().equals(Material.AIR)) { northBlock.setType(Material.CHEST); } else if (Objects.isNull(southBlock) || northBlock.getType().equals(Material.AIR)) { southBlock.setType(Material.CHEST); } else if (Objects.isNull(westBlock) || northBlock.getType().equals(Material.AIR)) { westBlock.setType(Material.CHEST); } else if (Objects.isNull(eastBlock) || northBlock.getType().equals(Material.AIR)) { eastBlock.setType(Material.CHEST); } else { event.getPlayer().sendMessage(Config.CHAT_PREFIX + " " + getMessage("cantPlaceChest")); event.setCancelled(true); return; } } InventoryHolder chestBlock = (block.getState() instanceof DoubleChest ? (DoubleChest) block.getState() : (block.getState() instanceof Chest ? (Chest) block.getState() : null)); Inventory chestinv = chestBlock.getInventory(); if (Objects.nonNull(chestinv)) chestinv.addItem(items.toArray(new ItemStack[items.size()])); } } } @EventHandler(priority = EventPriority.MONITOR) public void onBlockBreakEvent(BlockBreakEvent event) { if (event.isCancelled()) return; if (!event.getBlock().getType().equals(Material.CHEST) || event.getBlock().getDrops().isEmpty()) return; event.setCancelled(true); event.getBlock().setType(Material.AIR); Collection<ItemStack> drops = event.getBlock().getDrops(); drops.add(new ItemStack(Material.CHEST)); drops.forEach(drop -> { if (drop.getType().equals(Material.CHEST)) { if (drop.hasItemMeta() && drop.getItemMeta().hasDisplayName()) { if (Objects.nonNull(KitManager.getKit(drop.getItemMeta().getDisplayName(), event.getPlayer().getWorld().getName()))) { drop = new ItemBuilder(drop).setName("Chest").toItemStack(); } } } event.getPlayer().getWorld().dropItemNaturally(event.getBlock().getLocation(), drop); }); } @EventHandler public void onPlayerClickSignEvent(PlayerInteractEvent event) { Action action = event.getAction(); if (action == Action.RIGHT_CLICK_BLOCK) { if (event.getClickedBlock().getState() instanceof Sign) { Player player = event.getPlayer(); Sign sign = (Sign) event.getClickedBlock().getState(); if (sign.getLine(0).equalsIgnoreCase(ChatColor.GRAY + "[" + ChatColor.DARK_BLUE + "Kits" + ChatColor.GRAY + "]")) { Kit kit = KitManager.getKit(ChatColor.stripColor(sign.getLine(1)), player.getWorld().getName()); if (kit == null) { this.instance.log(ChatColor.RED + "Error: Kit doesn't exists. Sign location: " + sign.getLocation().toString()); event.setCancelled(true); return; } Bukkit.dispatchCommand(player, "advancedkitsreloaded:kit use " + kit.getName()); event.setCancelled(true); } } } } @EventHandler public void onPlayerCreateSignEvent(SignChangeEvent event) { if (event.getLine(0) == null) { return; } Player player = event.getPlayer(); if (!player.hasPermission("advancedkits.create")) { return; } if (Arrays.asList("kit|akit|advancedkits|kits|akits", "[kit]", "[kits]", "kit|akit|advancedkits|kits|akits", "[Kit]", "[Kits]").contains(event.getLine(0))) { event.setLine(0, ChatColor.GRAY + "[" + ChatColor.DARK_BLUE + "Kits" + ChatColor.GRAY + "]"); if (event.getLine(1) == null) { this.instance.log(ChatColor.RED + "Error: Kit doesn't exists. Sign location: " + event.getBlock().getLocation().toString()); player.sendMessage(ChatColor.RED + "Error: Kit doesn't exists. Sign location: " + event.getBlock().getLocation().toString()); return; } Kit kit = KitManager.getKit(ChatColor.stripColor(event.getLine(1)), player.getWorld().getName()); if (kit == null) { this.instance.log(ChatColor.RED + "Error: Kit doesn't exists. Sign location: " + event.getBlock().getLocation().toString()); player.sendMessage(ChatColor.RED + "Error: Kit doesn't exists. Sign location: " + event.getBlock().getLocation().toString()); return; } event.setLine(1, ChatColor.GREEN + event.getLine(1)); } } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\utils\ItemBuilder.java
package hu.tryharddevs.advancedkits.utils; import org.bukkit.Color; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.inventory.meta.SkullMeta; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; /** * Easily create itemstacks, without messing your hands. * <i>Note that if you do use this in one of your projects, leave this notice.</i> * <i>Please do credit me if you do use this in one of your projects.</i> * * @author NonameSL */ public class ItemBuilder { private final ItemStack is; /** * Create a new ItemBuilder from scratch. * * @param m The material to create the ItemBuilder with. */ public ItemBuilder(Material m) { this(m, 1); } /** * Create a new ItemBuilder over an existing itemstack. * * @param is The itemstack to create the ItemBuilder over. */ public ItemBuilder(ItemStack is) { this.is = is; } /** * Create a new ItemBuilder from scratch. * * @param m The material of the item. * @param amount The amount of the item. */ private ItemBuilder(Material m, int amount) { is = new ItemStack(m, amount); } /** * Create a new ItemBuilder from scratch. * * @param m The material of the item. * @param amount The amount of the item. * @param durability The durability of the item. */ public ItemBuilder(Material m, int amount, byte durability) { is = new ItemStack(m, amount, durability); } /** * Clone the ItemBuilder into a new one. * * @return The cloned instance. */ public ItemBuilder clone() { return new ItemBuilder(is); } /** * Change the durability of the item. * * @param dur The durability to set it to. */ public ItemBuilder setDurability(short dur) { is.setDurability(dur); return this; } /** * Set the displayname of the item. * * @param name The name to change it to. */ public ItemBuilder setName(String name) { ItemMeta im = is.getItemMeta(); im.setDisplayName(name); is.setItemMeta(im); return this; } /** * Add an unsafe enchantment. * * @param ench The enchantment to add. * @param level The level to put the enchant on. */ public ItemBuilder addUnsafeEnchantment(Enchantment ench, int level) { is.addUnsafeEnchantment(ench, level); return this; } /** * Remove a certain enchant from the item. * * @param ench The enchantment to remove */ public ItemBuilder removeEnchantment(Enchantment ench) { is.removeEnchantment(ench); return this; } /** * Set the skull owner for the item. Works on skulls only. * * @param owner The name of the skull's owner. */ public ItemBuilder setSkullOwner(String owner) { try { SkullMeta im = (SkullMeta) is.getItemMeta(); im.setOwner(owner); is.setItemMeta(im); } catch (ClassCastException ignored) { } return this; } /** * Add an enchant to the item. * * @param ench The enchant to add * @param level The level */ public ItemBuilder addEnchant(Enchantment ench, int level) { ItemMeta im = is.getItemMeta(); im.addEnchant(ench, level, true); is.setItemMeta(im); return this; } /** * Add multiple enchants at once. * * @param enchantments The enchants to add. */ public ItemBuilder addEnchantments(Map<Enchantment, Integer> enchantments) { is.addEnchantments(enchantments); return this; } /** * Sets infinity durability on the item by setting the durability to Short.MAX_VALUE. */ public ItemBuilder setInfinityDurability() { is.setDurability(Short.MAX_VALUE); return this; } /** * Re-sets the lore. * * @param lore The lore to set it to. */ public ItemBuilder setLore(String... lore) { ItemMeta im = is.getItemMeta(); im.setLore(Arrays.asList(lore)); is.setItemMeta(im); return this; } /** * Re-sets the lore. * * @param lore The lore to set it to. */ public ItemBuilder setLore(List<String> lore) { ItemMeta im = is.getItemMeta(); im.setLore(lore); is.setItemMeta(im); return this; } /** * Remove a lore line. * * @param line The lore to remove. */ public ItemBuilder removeLoreLine(String line) { ItemMeta im = is.getItemMeta(); List<String> lore = new ArrayList<>(im.getLore()); if (!lore.contains(line)) return this; lore.remove(line); im.setLore(lore); is.setItemMeta(im); return this; } /** * Remove a lore line. * * @param index The index of the lore line to remove. */ public ItemBuilder removeLoreLine(int index) { ItemMeta im = is.getItemMeta(); List<String> lore = new ArrayList<>(im.getLore()); if (index < 0 || index > lore.size()) return this; lore.remove(index); im.setLore(lore); is.setItemMeta(im); return this; } /** * Add a lore line. * * @param line The lore line to add. */ public ItemBuilder addLoreLine(String line) { ItemMeta im = is.getItemMeta(); List<String> lore = new ArrayList<>(); if (im.hasLore()) lore = new ArrayList<>(im.getLore()); lore.add(line); im.setLore(lore); is.setItemMeta(im); return this; } /** * Add a lore line. * * @param line The lore line to add. * @param pos The index of where to put it. */ public ItemBuilder addLoreLine(String line, int pos) { ItemMeta im = is.getItemMeta(); List<String> lore = new ArrayList<>(im.getLore()); lore.set(pos, line); im.setLore(lore); is.setItemMeta(im); return this; } /** * Hides every attributes, and extra lores generated by Minecraft. */ public ItemBuilder hideAttributes() { ItemMeta im = is.getItemMeta(); im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_DESTROYS, ItemFlag.HIDE_PLACED_ON, ItemFlag.HIDE_UNBREAKABLE, ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_POTION_EFFECTS); is.setItemMeta(im); return this; } /** * Sets the dye color on an item. * <b>* Notice that this doesn't check for item type, sets the literal data of the dyecolor as durability.</b> * * @param color The color to put. */ @SuppressWarnings("deprecation") public ItemBuilder setDyeColor(DyeColor color) { this.is.setDurability(color.getDyeData()); return this; } /** * Sets the dye color of a wool item. Works only on wool. * * @param color The DyeColor to set the wool item to. * @see ItemBuilder@setDyeColor(DyeColor) * @deprecated As of version 1.2 changed to setDyeColor. */ @Deprecated public ItemBuilder setWoolColor(DyeColor color) { if (!is.getType().equals(Material.WOOL)) return this; this.is.setDurability(color.getDyeData()); return this; } /** * Sets the armor color of a leather armor piece. Works only on leather armor pieces. * * @param color The color to set it to. */ public ItemBuilder setLeatherArmorColor(Color color) { try { LeatherArmorMeta im = (LeatherArmorMeta) is.getItemMeta(); im.setColor(color); is.setItemMeta(im); } catch (ClassCastException ignored) { } return this; } /** * Retrieves the itemstack from the ItemBuilder. * * @return The itemstack created/modified by the ItemBuilder instance. */ public ItemStack toItemStack() { return is; } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\utils\ItemStackUtil.java
package hu.tryharddevs.advancedkits.utils; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; import hu.tryharddevs.advancedkits.AdvancedKitsMain; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.util.io.BukkitObjectInputStream; import org.bukkit.util.io.BukkitObjectOutputStream; import org.inventivetalent.reflection.minecraft.Minecraft; import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.StringReader; public class ItemStackUtil { /** * Serialize an Object to a JsonObject. * <p> * The item itself will be saved as a Base64 encoded string to * simplify the serialization and deserialization process. The result is * not human readable. * </p> * * @param object The item to serialize. * @return A JsonObject with the serialized item. */ private static JsonObject serializeItem(Object object) { JsonObject values = new JsonObject(); if (object == null) return null; if (object instanceof ItemStack) { ItemStack itemStack = (ItemStack) object; /* * Check to see if the item is a skull with a null owner. * This is because some people are getting skulls with null owners, which causes Spigot to throw an error * when it tries to serialize the item. If this ever gets fixed in Spigot, this will be removed. */ if (itemStack.getType() == Material.SKULL_ITEM) { SkullMeta meta = (SkullMeta) itemStack.getItemMeta(); if (meta.hasOwner() && (meta.getOwner() == null || meta.getOwner().isEmpty())) { itemStack.setItemMeta(Bukkit.getServer().getItemFactory().getItemMeta(Material.SKULL_ITEM)); } } } try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); BukkitObjectOutputStream bos = new BukkitObjectOutputStream(outputStream)) { bos.writeObject(object); String encoded = Base64Coder.encodeLines(outputStream.toByteArray()); values.addProperty("item", encoded.replaceAll("[\n\r]", "").trim()); } catch (IOException ex) { AdvancedKitsMain.getPlugin().log(ChatColor.RED + "Error: " + ex.getMessage()); AdvancedKitsMain.getPlugin().log(ChatColor.RED + "Unable to serialize item '" + object.toString() + "':"); return null; } return values; } /** * Get an ItemStack from a JsonObject. * * @param data The Json to read. * @return The deserialized item stack. */ private static Object deserializeItem(JsonObject data) { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data.get("item").getAsString())); BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream)) { return dataInput.readObject(); } catch (IOException | ClassNotFoundException ex) { AdvancedKitsMain.getPlugin().log(ChatColor.RED + "Error: " + ex.getMessage()); AdvancedKitsMain.getPlugin().log(ChatColor.RED + "Unable to deserialize an item"); return new ItemStack(Material.AIR); } } public static String itemToString(ItemStack itemStack) { return serializeItem(itemStack).toString(); } public static ItemStack itemFromString(String itemStackString) { return (ItemStack) deserializeItem(jsonFromString(itemStackString)); } private static JsonObject jsonFromString(String jsonObjectStr) { JsonReader reader = new JsonReader(new StringReader(jsonObjectStr)); reader.setLenient(true); JsonElement jsonElement = new JsonParser().parse(reader); return jsonElement.getAsJsonObject(); } public static boolean isBoots(ItemStack item) { return isBoots(item.getType()); } private static boolean isBoots(Material material) { return material.name().endsWith("BOOTS"); } public static boolean isLegs(ItemStack item) { return isLegs(item.getType()); } private static boolean isLegs(Material material) { return material.name().endsWith("LEGGINGS"); } public static boolean isChest(ItemStack item) { return isChest(item.getType()); } private static boolean isChest(Material material) { return material.name().endsWith("CHESTPLATE") || Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1) && material.name().endsWith("ELYTRA"); } public static boolean isHelmet(ItemStack item) { return isHelmet(item.getType()); } private static boolean isHelmet(Material material) { return material.name().endsWith("HELMET"); } public static boolean isArmor(ItemStack item) { return isArmor(item.getType()); } private static boolean isArmor(Material type) { return isBoots(type) || isLegs(type) || isChest(type) || isHelmet(type); } public static boolean isShield(ItemStack item) { return isShield(item.getType()); } private static boolean isShield(Material material) { return material.name().endsWith("SHIELD"); } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\utils\MessagesApi.java
package hu.tryharddevs.advancedkits.utils; import hu.tryharddevs.advancedkits.AdvancedKitsMain; import hu.tryharddevs.advancedkits.Config; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import org.inventivetalent.reflection.minecraft.Minecraft; import org.inventivetalent.reflection.resolver.FieldResolver; import org.inventivetalent.reflection.resolver.MethodResolver; import org.inventivetalent.reflection.resolver.ResolverQuery; import org.inventivetalent.reflection.resolver.minecraft.NMSClassResolver; import org.inventivetalent.reflection.resolver.minecraft.OBCClassResolver; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; /***************************************************** * * MessagesAPI * by ConnorLinfoot {@see https://github.com/ConnorLinfoot/MessagesAPI/} ** * ****************************************************/ @SuppressWarnings("ALL") public class MessagesApi { private static final OBCClassResolver obcClassResolver = new OBCClassResolver(); private static final NMSClassResolver nmsClassResolver = new NMSClassResolver(); private static final boolean useOldMethods = Minecraft.VERSION.olderThan(Minecraft.Version.v1_8_R1); @Deprecated public static void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String message) { sendTitle(player, fadeIn, stay, fadeOut, message, null); } @Deprecated public static void sendSubtitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String message) { sendTitle(player, fadeIn, stay, fadeOut, null, message); } @Deprecated public static void sendFullTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle) { sendTitle(player, fadeIn, stay, fadeOut, title, subtitle); } @Deprecated public static Integer getPlayerProtocol(Player player) { return 47; } private static void sendPacket(Player player, Object packet) { try { Object handle = new MethodResolver(player.getClass()).resolveSilent("getHandle").invoke(player); Object playerConnection = new FieldResolver(handle.getClass()).resolveSilent("playerConnection").get(handle); new MethodResolver(playerConnection.getClass()).resolveSilent(new ResolverQuery("sendPacket", nmsClassResolver.resolveSilent("Packet"))).invoke(playerConnection, packet); } catch (Exception e) { e.printStackTrace(); } } public static void sendTitle(Player player, String title, String subtitle) { sendTitle(player, 4, 23, 4, title, subtitle); } private static void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle) { try { Object e; Object chatTitle; Object chatSubtitle; Constructor subtitleConstructor; Object titlePacket; Object subtitlePacket; if (title != null) { title = ChatColor.translateAlternateColorCodes('&', title); title = title.replaceAll("%player%", player.getDisplayName()); // Times packets e = nmsClassResolver.resolveSilent("PacketPlayOutTitle").getDeclaredClasses()[0].getField("TIMES").get(null); chatTitle = nmsClassResolver.resolveSilent("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", String.class).invoke(null, "{\"text\":\"" + title + "\"}"); subtitleConstructor = nmsClassResolver.resolveSilent("PacketPlayOutTitle").getConstructor(nmsClassResolver.resolveSilent("PacketPlayOutTitle").getDeclaredClasses()[0], nmsClassResolver.resolveSilent("IChatBaseComponent"), Integer.TYPE, Integer.TYPE, Integer.TYPE); titlePacket = subtitleConstructor.newInstance(e, chatTitle, fadeIn, stay, fadeOut); sendPacket(player, titlePacket); e = nmsClassResolver.resolveSilent("PacketPlayOutTitle").getDeclaredClasses()[0].getField("TITLE").get(null); chatTitle = nmsClassResolver.resolveSilent("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", String.class).invoke(null, "{\"text\":\"" + title + "\"}"); subtitleConstructor = nmsClassResolver.resolveSilent("PacketPlayOutTitle").getConstructor(nmsClassResolver.resolveSilent("PacketPlayOutTitle").getDeclaredClasses()[0], nmsClassResolver.resolveSilent("IChatBaseComponent")); titlePacket = subtitleConstructor.newInstance(e, chatTitle); sendPacket(player, titlePacket); } if (subtitle != null) { subtitle = ChatColor.translateAlternateColorCodes('&', subtitle); subtitle = subtitle.replaceAll("%player%", player.getDisplayName()); // Times packets e = nmsClassResolver.resolveSilent("PacketPlayOutTitle").getDeclaredClasses()[0].getField("TIMES").get(null); chatSubtitle = nmsClassResolver.resolveSilent("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", String.class).invoke(null, "{\"text\":\"" + title + "\"}"); subtitleConstructor = nmsClassResolver.resolveSilent("PacketPlayOutTitle").getConstructor(nmsClassResolver.resolveSilent("PacketPlayOutTitle").getDeclaredClasses()[0], nmsClassResolver.resolveSilent("IChatBaseComponent"), Integer.TYPE, Integer.TYPE, Integer.TYPE); subtitlePacket = subtitleConstructor.newInstance(e, chatSubtitle, fadeIn, stay, fadeOut); sendPacket(player, subtitlePacket); e = nmsClassResolver.resolveSilent("PacketPlayOutTitle").getDeclaredClasses()[0].getField("SUBTITLE").get(null); chatSubtitle = nmsClassResolver.resolveSilent("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", String.class).invoke(null, "{\"text\":\"" + subtitle + "\"}"); subtitleConstructor = nmsClassResolver.resolveSilent("PacketPlayOutTitle").getConstructor(nmsClassResolver.resolveSilent("PacketPlayOutTitle").getDeclaredClasses()[0], nmsClassResolver.resolveSilent("IChatBaseComponent"), Integer.TYPE, Integer.TYPE, Integer.TYPE); subtitlePacket = subtitleConstructor.newInstance(e, chatSubtitle, fadeIn, stay, fadeOut); sendPacket(player, subtitlePacket); } } catch (Exception var11) { var11.printStackTrace(); } } public static void clearTitle(Player player) { sendTitle(player, 0, 0, 0, "", ""); } public static void sendTabTitle(Player player, String header, String footer) { if (header == null) header = ""; header = ChatColor.translateAlternateColorCodes('&', header); if (footer == null) footer = ""; footer = ChatColor.translateAlternateColorCodes('&', footer); header = header.replaceAll("%player%", player.getDisplayName()); footer = footer.replaceAll("%player%", player.getDisplayName()); try { Object tabHeader = nmsClassResolver.resolveSilent("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", String.class).invoke(null, "{\"text\":\"" + header + "\"}"); Object tabFooter = nmsClassResolver.resolveSilent("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", String.class).invoke(null, "{\"text\":\"" + footer + "\"}"); Constructor<?> titleConstructor = nmsClassResolver.resolveSilent("PacketPlayOutPlayerListHeaderFooter").getConstructor(nmsClassResolver.resolveSilent("IChatBaseComponent")); Object packet = titleConstructor.newInstance(tabHeader); Field field = packet.getClass().getDeclaredField("b"); field.setAccessible(true); field.set(packet, tabFooter); sendPacket(player, packet); } catch (Exception ex) { ex.printStackTrace(); } } public static void sendActionBar(Player player, String message) { try { Class<?> c1 = obcClassResolver.resolveSilent("entity.CraftPlayer"); Object p = c1.cast(player); Object ppoc; Class<?> c4 = nmsClassResolver.resolveSilent("PacketPlayOutChat"); Class<?> c5 = nmsClassResolver.resolveSilent("Packet"); if (useOldMethods) { Class<?> c2 = nmsClassResolver.resolveSilent("ChatSerializer"); Class<?> c3 = nmsClassResolver.resolveSilent("IChatBaseComponent"); Method m3 = c2.getDeclaredMethod("a", String.class); Object cbc = c3.cast(m3.invoke(c2, "{\"text\": \"" + message + "\"}")); ppoc = c4.getConstructor(new Class<?>[]{c3, byte.class}).newInstance(cbc, (byte) 2); } else { Class<?> c2 = nmsClassResolver.resolveSilent("ChatComponentText"); Class<?> c3 = nmsClassResolver.resolveSilent("IChatBaseComponent"); Object o = c2.getConstructor(new Class<?>[]{String.class}).newInstance(message); ppoc = c4.getConstructor(new Class<?>[]{c3, byte.class}).newInstance(o, (byte) 2); } Method m1 = c1.getDeclaredMethod("getHandle"); Object h = m1.invoke(p); Field f1 = h.getClass().getDeclaredField("playerConnection"); Object pc = f1.get(h); Method m5 = pc.getClass().getDeclaredMethod("sendPacket", c5); m5.invoke(pc, ppoc); } catch (Exception ex) { ex.printStackTrace(); } } private static void sendActionBar(final Player player, final String message, int duration) { sendActionBar(player, message); if (duration >= 0) { // Sends empty message at the end of the duration. Allows messages shorter than 3 seconds, ensures precision. new BukkitRunnable() { @Override public void run() { sendActionBar(player, ""); } }.runTaskLater(AdvancedKitsMain.getPlugin(), duration + 1); } // Re-sends the messages every 3 seconds so it doesn't go away from the player's screen. while (duration > 60) { duration -= 60; int sched = duration % 60; new BukkitRunnable() { @Override public void run() { sendActionBar(player, message); } }.runTaskLater(AdvancedKitsMain.getPlugin(), (long) sched); } } public static void sendActionBarToAllPlayers(String message) { sendActionBarToAllPlayers(message, -1); } private static void sendActionBarToAllPlayers(String message, int duration) { for (Player p : Bukkit.getOnlinePlayers()) { sendActionBar(p, message, duration); } } public static void sendMessage(CommandSender sender, String... messages) { Arrays.stream(messages).forEach(message -> sender.sendMessage(Config.CHAT_PREFIX + " " + message)); } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\cinventory\inventories\CPageInventory.java
package hu.tryharddevs.advancedkits.cinventory.inventories; import hu.tryharddevs.advancedkits.cinventory.CInventory; import hu.tryharddevs.advancedkits.utils.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import static hu.tryharddevs.advancedkits.utils.localization.I18n.getMessage; public class CPageInventory extends CInventory { private ItemStack backAPage, forwardsAPage, exitInventory; private int currentPage; private int inventorySize; private boolean dynamicInventorySize = true; private final HashMap<Integer, ItemStack[]> pagesHashMap = new HashMap<>(); public CPageInventory(Player player) { this(null, player); } public CPageInventory(Player player, boolean dymanicInventory) { this(null, player, dymanicInventory); } public CPageInventory(Player player, int inventorySize) { this(null, player, inventorySize); } public CPageInventory(String inventoryName, Player player) { super(inventoryName, player); } private CPageInventory(String inventoryName, Player player, boolean dymanicInventory) { super(inventoryName, player); this.dynamicInventorySize = dymanicInventory; } private CPageInventory(String inventoryName, Player player, int inventorySize) { super(inventoryName, player); this.inventorySize = Math.min(54, (int) (Math.ceil((double) inventorySize / 9)) * 9); this.dynamicInventorySize = false; this.pagesHashMap.put(0, new ItemStack[0]); } public void setPages(ArrayList<ItemStack> allItems) { setPages(allItems.toArray(new ItemStack[allItems.size()])); } private void setPages(ItemStack... allItems) { if (this.inventorySize == 0) this.inventorySize = Math.min(54, (int) (Math.ceil((double) allItems.length / 9)) * 9); this.pagesHashMap.clear(); int invPage = 0; boolean usePages = getExitInventory() != null || allItems.length > this.inventorySize; ItemStack[] items = null; int currentSlot = 0; int baseSize = this.inventorySize; for (int currentItem = 0; currentItem < allItems.length; currentItem++) { if (items == null) { int newSize = allItems.length - currentItem; if (usePages && newSize + 9 > baseSize) { newSize = baseSize - 9; } else if (newSize > baseSize) { newSize = baseSize; } items = new ItemStack[newSize]; } ItemStack item = allItems[currentItem]; items[currentSlot++] = item; if (currentSlot == items.length) { this.pagesHashMap.put(invPage, items); invPage++; currentSlot = 0; items = null; } } if (this.pagesHashMap.keySet().size() < getCurrentPage()) this.currentPage = this.pagesHashMap.keySet().size() - 1; if (allItems.length == 0) { int size = this.inventorySize; if (this.dynamicInventorySize) { size = 9; } items = generateEmptyPage(size); if (getExitInventory() != null) { items[0] = getExitInventory(); } this.pagesHashMap.put(0, items); } setPage(getCurrentPage()); } @Override protected void onInventoryClick(InventoryClickEvent event) { ItemStack item = event.getCurrentItem(); if (item != null) { int newPage = 0; if (item.equals(getBackPage())) { newPage = -1; } else if (item.equals(getForwardsPage())) { newPage = 1; } if (newPage != 0) { setPage(getCurrentPage() + newPage); event.setCancelled(true); } } } @Override public ItemStack getItem(int slot) { return this.currentInventory.getItem(slot); } /** * Opens the inventory for use */ public void openInventory() { if (isInventoryInUse()) return; ItemStack[] pageItems = getItemsForPage(); if (this.currentInventory == null) { this.currentInventory = Bukkit.createInventory(null, pageItems.length, getInventoryName()); } setItems(pageItems); openInv(); } private ItemStack[] getItemsForPage() { ItemStack[] pageItems = this.pagesHashMap.get(Math.max(getCurrentPage(), 0)); int pageSize = pageItems.length; if (this.pagesHashMap.size() > 1 || this.getExitInventory() != null) { pageSize += 9; } if (!this.dynamicInventorySize) { pageSize = this.inventorySize; } else { pageSize = ((pageSize + 8) / 9) * 9; } pageItems = Arrays.copyOf(pageItems, pageSize); if (getCurrentPage() > 0 || getExitInventory() != null) { pageItems[pageItems.length - 9] = getCurrentPage() == 0 ? getExitInventory() : getBackPage(); } if (this.pagesHashMap.size() - 1 > getCurrentPage()) { pageItems[pageItems.length - 1] = getForwardsPage(); } return pageItems; } private void setPage(int newPage) { if (this.pagesHashMap.containsKey(newPage)) { this.currentPage = newPage; if (isInventoryInUse()) { ItemStack[] pageItems = getItemsForPage(); setItems(pageItems); } } } private static ItemStack[] generateEmptyPage(int itemsSize) { itemsSize = (int) (Math.ceil((double) itemsSize / 9)) * 9; return new ItemStack[Math.min(54, itemsSize)]; } private ItemStack getExitInventory() { return this.exitInventory; } public void setExitInventory(ItemStack item) { this.exitInventory = item; } public ItemStack getBackPage() { if (this.backAPage == null) { this.backAPage = new ItemBuilder(new ItemStack(Material.SIGN)).setName(getMessage("guiBackpage")).setLore(getMessage("guiBackpageLore")).toItemStack(); } return this.backAPage; } public void setBackPage(ItemStack newBack) { this.backAPage = newBack; } private int getCurrentPage() { return this.currentPage; } public ItemStack getForwardsPage() { if (this.forwardsAPage == null) { this.forwardsAPage = new ItemBuilder(new ItemStack(Material.SIGN)).setName(getMessage("guiNextpage")).setLore(getMessage("guiNextpageLore")).toItemStack(); } return this.forwardsAPage; } public void setForwardsPage(ItemStack newForwards) { this.forwardsAPage = newForwards; } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\cinventory\inventories\CSimpleInventory.java
package hu.tryharddevs.advancedkits.cinventory.inventories; import hu.tryharddevs.advancedkits.cinventory.CInventory; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Objects; public class CSimpleInventory extends CInventory { private int inventorySize; private final HashMap<Integer, ItemStack> itemStackHashMap = new HashMap<>(); private final ArrayList<ItemStack> itemStackArrayList = new ArrayList<>(); public CSimpleInventory(String inventoryName, Player player) { super(inventoryName, player); } public CSimpleInventory(Player player, int inventorySize) { this(null, player, inventorySize); } public CSimpleInventory(String inventoryName, Player player, int inventorySize) { super(inventoryName, player); this.inventorySize = getDynamicSize(inventorySize); } public void addItems(ArrayList<ItemStack> itemStacks) { addItems(itemStacks.toArray(new ItemStack[itemStacks.size()])); } private void addItems(ItemStack... itemStacks) { Arrays.stream(itemStacks).forEach(itemStack -> { if (Objects.isNull(itemStack)) this.itemStackArrayList.add(new ItemStack(Material.AIR)); else this.itemStackArrayList.add(itemStack); }); } public void setItem(int slot, ItemStack itemStack) { this.itemStackHashMap.put(slot, itemStack); } public void openInventory() { if (isInventoryInUse()) return; if (Objects.isNull(this.currentInventory)) { this.currentInventory = Bukkit.createInventory(null, inventorySize == 0 ? getDynamicSize(itemStackHashMap.size() + itemStackArrayList.size()) : inventorySize, getInventoryName()); } this.itemStackHashMap.forEach(this.currentInventory::setItem); this.itemStackArrayList.forEach(this.currentInventory::addItem); openInv(); } @Override protected void onInventoryClick(InventoryClickEvent event) { } @Override public ItemStack getItem(int slot) { return this.currentInventory.getItem(slot); } private int getDynamicSize(int items) { return Math.min(54, (int) (Math.ceil((double) items / 9)) * 9); } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\cinventory\listeners\InventoryClickListener.java
package hu.tryharddevs.advancedkits.cinventory.listeners; import org.bukkit.event.inventory.InventoryClickEvent; public interface InventoryClickListener { /** * Called when a player clicks the inventory * * @param event {@link InventoryClickEvent} */ void interact(InventoryClickEvent event); }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\cinventory\listeners\InventoryCloseListener.java
package hu.tryharddevs.advancedkits.cinventory.listeners; import org.bukkit.event.inventory.InventoryCloseEvent; public interface InventoryCloseListener { /** * Called when a player closes the inventory * * @param event {@link InventoryCloseEvent} */ void interact(InventoryCloseEvent event); }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\cinventory\listeners\InventoryDragListener.java
package hu.tryharddevs.advancedkits.cinventory.listeners; import org.bukkit.event.inventory.InventoryDragEvent; public interface InventoryDragListener { /** * Called when a player closes the inventory * * @param event {@link InventoryDragEvent} */ void interact(InventoryDragEvent event); }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\kits\flags\BooleanFlag.java
package hu.tryharddevs.advancedkits.kits.flags; import hu.tryharddevs.advancedkits.Config; import org.bukkit.ChatColor; import org.jetbrains.annotations.Nullable; public class BooleanFlag extends Flag<Boolean> { private final boolean defaultValue; public BooleanFlag(String name, boolean defaultValue) { super(name); this.defaultValue = defaultValue; } public BooleanFlag(String name) { super(name); defaultValue = false; } @Nullable @Override public Boolean getDefault() { return defaultValue; } @Override public Boolean parseInput(String input) throws InvalidFlagValueException { if (input.equalsIgnoreCase("true") || input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("on") || input.equalsIgnoreCase("1")) { return true; } else if (input.equalsIgnoreCase("false") || input.equalsIgnoreCase("no") || input.equalsIgnoreCase("off") || input.equalsIgnoreCase("0")) { return false; } else { throw new InvalidFlagValueException(Config.CHAT_PREFIX + " " + ChatColor.RED + "Not a yes/no value: " + input); } } @Override public Boolean unmarshal(Object o) { if (o instanceof Boolean) { return (Boolean) o; } else { return null; } } @Override public Object marshal(Boolean o) { return o; } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\kits\flags\DefaultFlags.java
package hu.tryharddevs.advancedkits.kits.flags; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.inventivetalent.particle.ParticleEffect; import java.util.Arrays; import java.util.List; public class DefaultFlags { public static final BooleanFlag VISIBLE = new BooleanFlag("visible", true); public static final BooleanFlag FIRSTJOIN = new BooleanFlag("firstjoin", false); public static final BooleanFlag AUTOEQUIPARMOR = new BooleanFlag("autoequiparmor", false); public static final BooleanFlag FREE = new BooleanFlag("free", false); public static final BooleanFlag USEONBUY = new BooleanFlag("useonbuy", false); public static final BooleanFlag CLEARINVENTORY = new BooleanFlag("clearinventory", false); public static final BooleanFlag SPEWITEMS = new BooleanFlag("spewitems", false); public static final BooleanFlag ITEMSINCONTAINER = new BooleanFlag("itemsincontainer", false); public static final StringFlag DISPLAYNAME = new StringFlag("displayname"); public static final IntegerFlag PERUSECOST = new IntegerFlag("perusecost", 0); public static final IntegerFlag COST = new IntegerFlag("cost", 0); public static final IntegerFlag MAXUSES = new IntegerFlag("maxuses", 0); public static final DoubleFlag DELAY = new DoubleFlag("delay", 0.0); public static final ItemStackFlag ICON = new ItemStackFlag("icon", new ItemStack(Material.EMERALD_BLOCK)); public static final ItemStackFlag FIREWORK = new ItemStackFlag("firework", new ItemStack(Material.FIREWORK)); public static final ListFlag<String> CUSTOMDESCRIPTION = new ListFlag<>("customdescription", new StringFlag(null)); public static final ListFlag<String> COMMANDS = new ListFlag<>("commands", new StringFlag(null)); public static final ListFlag<String> MESSAGES = new ListFlag<>("messages", new StringFlag(null)); public static final ListFlag<String> DISABLEDWORLDS = new ListFlag<>("disabledworlds", new StringFlag(null)); public static final ListFlag<PotionEffect> POTIONEFFECTS = new ListFlag<>("potioneffects", new PotionEffectFlag(null)); public static final ListFlag<ParticleEffect> PARTICLEEFFECTS = new ListFlag<>("particleeffects", new ParticleEffectFlag(null)); public static final ListFlag<Sound> SOUNDEFFECTS = new ListFlag<>("soundeffects", new SoundEffectFlag(null)); private static final Flag<?>[] flagsList = new Flag<?>[]{VISIBLE, FIRSTJOIN, AUTOEQUIPARMOR, FREE, USEONBUY, CLEARINVENTORY, SPEWITEMS, ITEMSINCONTAINER, DISPLAYNAME, PERUSECOST, COST, MAXUSES, DELAY, FIREWORK, ICON, CUSTOMDESCRIPTION, COMMANDS, MESSAGES, DISABLEDWORLDS, POTIONEFFECTS, PARTICLEEFFECTS, SOUNDEFFECTS}; public static Flag<?>[] getFlags() { return flagsList; } public static List<Flag<?>> getDefaultFlags() { return Arrays.asList(flagsList); } public static Flag<?> fuzzyMatchFlag(String id) { for (Flag<?> flag : getDefaultFlags()) { if (flag.getName().replace("-", "").equalsIgnoreCase(id.replace("-", ""))) { return flag; } } return null; } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\kits\flags\DoubleFlag.java
package hu.tryharddevs.advancedkits.kits.flags; import hu.tryharddevs.advancedkits.Config; import org.bukkit.ChatColor; import org.jetbrains.annotations.Nullable; public class DoubleFlag extends Flag<Double> { private final double defaultValue; public DoubleFlag(String name, double defaultValue) { super(name); this.defaultValue = defaultValue; } public DoubleFlag(String name) { super(name); this.defaultValue = 0; } @Nullable @Override public Double getDefault() { return defaultValue; } @Override public Double parseInput(String input) throws InvalidFlagValueException { return getInputAsDouble(input); } private Double getInputAsDouble(String input) throws InvalidFlagValueException { try { return Double.parseDouble(input); } catch (NumberFormatException e) { throw new InvalidFlagValueException(Config.CHAT_PREFIX + " " + ChatColor.RED + "Not a number: " + input); } } @Override public Double unmarshal(Object o) { if (o instanceof Double) { return (Double) o; } else if (o instanceof Number) { return ((Number) o).doubleValue(); } else { return null; } } @Override public Object marshal(Double o) { return o; } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\kits\flags\Flag.java
package hu.tryharddevs.advancedkits.kits.flags; import co.aikar.commands.InvalidCommandArgument; import co.aikar.commands.contexts.ContextResolver; import com.google.common.collect.Iterators; import hu.tryharddevs.advancedkits.Config; import org.bukkit.entity.Player; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Collection; import java.util.Objects; import java.util.regex.Pattern; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkNotNull; import static hu.tryharddevs.advancedkits.utils.localization.I18n.getMessage; public abstract class Flag<T> { private static final Pattern VALID_NAME = Pattern.compile("^[:A-Za-z0-9\\-]{1,40}$"); private final String name; protected Flag(String name) { if (name != null && !isValidName(name)) { throw new IllegalArgumentException("Invalid flag name used"); } this.name = name; } private static boolean isValidName(String name) { checkNotNull(name, "name"); return VALID_NAME.matcher(name).matches(); } public static ContextResolver<Flag> getContextResolver() { return (c) -> { String flagName = c.popFirstArg(); Flag flag = DefaultFlags.fuzzyMatchFlag(flagName); if (Objects.isNull(flag)) { throw new InvalidCommandArgument(getMessage("flagNotFound") + "\n" + Config.CHAT_PREFIX + " " + getMessage("availableFlags", Arrays.stream(DefaultFlags.getFlags()).map(Flag::getName).sorted(String::compareToIgnoreCase).collect(Collectors.joining(",")))); } return flag; }; } public final String getName() { return name; } @Nullable public T getDefault() { return null; } @Nullable public T chooseValue(Collection<T> values) { return Iterators.getNext(values.iterator(), null); } public abstract T parseInput(String input) throws InvalidFlagValueException; @Nullable public T parseItem(Player player) throws InvalidFlagValueException { return null; } @Override public String toString() { return getClass().getSimpleName() + "{" + "name='" + name + '\'' + '}'; } public abstract T unmarshal(@Nullable Object o); public abstract Object marshal(T o); }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\kits\flags\IntegerFlag.java
package hu.tryharddevs.advancedkits.kits.flags; import hu.tryharddevs.advancedkits.Config; import org.bukkit.ChatColor; import org.jetbrains.annotations.Nullable; public class IntegerFlag extends Flag<Integer> { private final int defaultValue; public IntegerFlag(String name, int defaultValue) { super(name); this.defaultValue = defaultValue; } public IntegerFlag(String name) { super(name); this.defaultValue = 0; } @Nullable @Override public Integer getDefault() { return defaultValue; } @Override public Integer parseInput(String input) throws InvalidFlagValueException { return getInputAsInt(input); } private Integer getInputAsInt(String input) throws InvalidFlagValueException { try { return Integer.parseInt(input); } catch (NumberFormatException e) { throw new InvalidFlagValueException(Config.CHAT_PREFIX + " " + ChatColor.RED + "Not a number: " + input); } } @Override public Integer unmarshal(Object o) { if (o instanceof Integer) { return (Integer) o; } else if (o instanceof Number) { return ((Number) o).intValue(); } else { return null; } } @Override public Object marshal(Integer o) { return o; } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\kits\flags\InvalidFlagValueException.java
package hu.tryharddevs.advancedkits.kits.flags; public class InvalidFlagValueException extends Exception { private static final long serialVersionUID = 1997753363232807009L; private String[] messages; public InvalidFlagValueException() {} public InvalidFlagValueException(String message) { super(message); this.messages = new String[1]; this.messages[0] = message; } public InvalidFlagValueException(String... messages) { this.messages = messages; } public InvalidFlagValueException(Throwable cause) { super(cause); } public InvalidFlagValueException(String message, Throwable cause) { super(message, cause); } public InvalidFlagValueException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public String[] getMessages() { return this.messages; } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\kits\flags\ItemStackFlag.java
package hu.tryharddevs.advancedkits.kits.flags; import hu.tryharddevs.advancedkits.utils.ItemStackUtil; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.Nullable; public class ItemStackFlag extends Flag<ItemStack> { private final ItemStack defaultValue; public ItemStackFlag(String name, ItemStack defaultValue) { super(name); this.defaultValue = defaultValue; } public ItemStackFlag(String name, Material defaultValue) { super(name); this.defaultValue = new ItemStack(defaultValue); } public ItemStackFlag(String name) { super(name); this.defaultValue = new ItemStack(Material.EMERALD_BLOCK); } @Nullable @Override public ItemStack getDefault() { return defaultValue; } @Override public ItemStack parseInput(String input) throws InvalidFlagValueException { return null; } @Nullable @Override public ItemStack parseItem(Player player) { return player.getInventory().getItemInMainHand(); } @Override public ItemStack unmarshal(@Nullable Object o) { try { String material = String.valueOf(o); return new ItemStack(Material.matchMaterial(material)); } catch (ClassCastException | NullPointerException e) { return ItemStackUtil.itemFromString(String.valueOf(o)); } } @Override public Object marshal(ItemStack o) { return ItemStackUtil.itemToString(o); } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\kits\flags\ListFlag.java
package hu.tryharddevs.advancedkits.kits.flags; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class ListFlag<T> extends Flag<ArrayList<T>> { private final Flag<T> subFlag; public ListFlag(String name, Flag<T> subFlag) { super(name); this.subFlag = subFlag; } public Flag<T> getType() { return subFlag; } @Override public ArrayList<T> getDefault() { return new ArrayList<>(); } @Override public ArrayList<T> parseInput(String input) throws InvalidFlagValueException { if (input.isEmpty()) { return new ArrayList<>(); } else { ArrayList<T> items = new ArrayList<>(); for (String str : input.split(",")) { items.add(subFlag.parseInput(str)); } return items; } } @Override public ArrayList<T> unmarshal(Object o) { if (o instanceof Collection<?>) { Collection<?> collection = (Collection<?>) o; ArrayList<T> items = new ArrayList<>(); for (Object sub : collection) { T item = subFlag.unmarshal(sub); if (item != null) { items.add(item); } } return items; } else { return null; } } @Override public Object marshal(ArrayList<T> o) { List<Object> list = new ArrayList<>(); for (T item : o) { list.add(subFlag.marshal(item)); } return list; } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\kits\flags\ParticleEffectFlag.java
package hu.tryharddevs.advancedkits.kits.flags; import hu.tryharddevs.advancedkits.Config; import org.bukkit.ChatColor; import org.inventivetalent.particle.ParticleEffect; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Objects; import java.util.stream.Collectors; public class ParticleEffectFlag extends Flag<ParticleEffect> { public ParticleEffectFlag(String name) { super(name); } private static ParticleEffect getParticleEffectByName(String input) { ParticleEffect lowMatch = null; for (ParticleEffect particleEffect : ParticleEffect.values()) { if (particleEffect.name().equalsIgnoreCase(input.trim())) { return particleEffect; } if (particleEffect.name().toLowerCase().startsWith(input.toLowerCase().trim())) { lowMatch = particleEffect; } } return lowMatch; } @Override public ParticleEffect parseInput(String input) throws InvalidFlagValueException { return getParticleEffectFromString(input); } @Override public ParticleEffect unmarshal(@Nullable Object o) { return getParticleEffectByName(String.valueOf(o)); } @Override public Object marshal(ParticleEffect o) { return o.name(); } private ParticleEffect getParticleEffectFromString(String input) throws InvalidFlagValueException { if (Objects.isNull(getParticleEffectByName(input))) { throw new InvalidFlagValueException(Config.CHAT_PREFIX + " " + ChatColor.RED + "Invalid particle name.", Config.CHAT_PREFIX + " " + ChatColor.RED + "Here are the available effects: ", ChatColor.GRAY + Arrays.stream(ParticleEffect.values()).map(ParticleEffect::name).collect(Collectors.joining(","))); } return getParticleEffectByName(input); } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\kits\flags\PotionEffectFlag.java
package hu.tryharddevs.advancedkits.kits.flags; import hu.tryharddevs.advancedkits.Config; import org.bukkit.ChatColor; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Objects; import java.util.stream.Collectors; public class PotionEffectFlag extends Flag<PotionEffect> { public PotionEffectFlag(String name) { super(name); } @Override public PotionEffect parseInput(String input) throws InvalidFlagValueException { if (Objects.isNull(getPotionEffectFromString(input))) { throw new InvalidFlagValueException(Config.CHAT_PREFIX + " " + ChatColor.RED + "Invalid format or effect.", Config.CHAT_PREFIX + " " + ChatColor.RED + "Correct format: effect;duration;amplifier.", Config.CHAT_PREFIX + " " + ChatColor.RED + "Here are the available potioneffects: ", ChatColor.GRAY + Arrays.stream(PotionEffectType.values()).filter(Objects::nonNull).map(PotionEffectType::getName).collect(Collectors.joining(","))); } return getPotionEffectFromString(input); } @Override public PotionEffect unmarshal(@Nullable Object o) { return getPotionEffectFromString(String.valueOf(o)); } @Override public Object marshal(PotionEffect o) { return getPotionEffectAsString(o); } private PotionEffect getPotionEffectFromString(String value) { if (value.split(";").length != 3) { return null; } PotionEffect potionEffect; String[] split = value.split(";"); if (Objects.isNull(PotionEffectType.getByName(split[0]))) { return null; } try { potionEffect = new PotionEffect(PotionEffectType.getByName(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])); } catch (Exception e) { return null; } return potionEffect; } // effect,duration,amplifier private String getPotionEffectAsString(PotionEffect potionEffect) { return potionEffect.getType().getName() + ";" + potionEffect.getDuration() + ";" + potionEffect.getAmplifier(); } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\kits\flags\SoundEffectFlag.java
package hu.tryharddevs.advancedkits.kits.flags; import hu.tryharddevs.advancedkits.Config; import org.bukkit.ChatColor; import org.bukkit.Sound; import org.jetbrains.annotations.Nullable; import java.util.Objects; public class SoundEffectFlag extends Flag<Sound> { public SoundEffectFlag(String name) { super(name); } @Override public Sound parseInput(String input) throws InvalidFlagValueException { return getSoundEffectFromString(input); } @Override public Sound unmarshal(@Nullable Object o) { return getSoundEffectByName(String.valueOf(o)); } @Override public Object marshal(Sound o) { return o.name(); } private Sound getSoundEffectFromString(String input) throws InvalidFlagValueException { if (Objects.isNull(getSoundEffectByName(input))) { throw new InvalidFlagValueException(Config.CHAT_PREFIX + " " + ChatColor.RED + "Invalid soundeffect name.", Config.CHAT_PREFIX + " " + ChatColor.RED + "Here are the available effects: ", ChatColor.GRAY + "https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Sound.html"); } return getSoundEffectByName(input); } private Sound getSoundEffectByName(String input) { Sound lowMatch = null; for (Sound sound : Sound.values()) { if (sound.name().equalsIgnoreCase(input.trim())) { return sound; } if (sound.name().toLowerCase().startsWith(input.toLowerCase().trim())) { lowMatch = sound; } } return lowMatch; } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\kits\flags\StringFlag.java
package hu.tryharddevs.advancedkits.kits.flags; import org.jetbrains.annotations.Nullable; public class StringFlag extends Flag<String> { private final String defaultValue; public StringFlag(String name) { super(name); this.defaultValue = null; } public StringFlag(String name, String defaultValue) { super(name); this.defaultValue = defaultValue; } @Nullable @Override public String getDefault() { return defaultValue; } @Override public String parseInput(String input) throws InvalidFlagValueException { return input.replaceAll("(?!\\\\)\\\\n", "\n").replaceAll("\\\\\\\\n", "\\n"); } @Override public String unmarshal(Object o) { if (o instanceof String) { return (String) o; } else { return null; } } @Override public Object marshal(String o) { return o; } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\utils\localization\I18n.java
package hu.tryharddevs.advancedkits.utils.localization; import hu.tryharddevs.advancedkits.AdvancedKitsMain; import org.bukkit.ChatColor; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.text.MessageFormat; import java.util.*; import java.util.regex.Pattern; public class I18n { private static final String MESSAGES = "messages"; private static final Pattern NODOUBLEMARK = Pattern.compile("''"); private static final ResourceBundle NULL_BUNDLE = new ResourceBundle() { public Enumeration<String> getKeys() { return null; } protected Object handleGetObject(String key) { return null; } }; private static I18n instance; private final transient Locale defaultMessageLocale = Locale.getDefault(); private final transient ResourceBundle defaultBundle; private final transient AdvancedKitsMain plugin; private transient Locale currentMessageLocale = defaultMessageLocale; private transient ResourceBundle customBundle; private transient ResourceBundle localeBundle; private transient Map<String, MessageFormat> messageFormatCache = new HashMap<>(); public I18n(final AdvancedKitsMain plugin) { this.plugin = plugin; defaultBundle = ResourceBundle.getBundle(MESSAGES, Locale.ENGLISH, new UTF8Control()); localeBundle = defaultBundle; customBundle = NULL_BUNDLE; } public static String getMessage(final String string) { return getMessage(string, new Object[0]); } public static String getMessage(final String string, final Object... objects) { if (instance == null) { return ""; } if (objects.length == 0) { return ChatColor.translateAlternateColorCodes('&', NODOUBLEMARK.matcher(instance.translate(string)).replaceAll("'")); } else { return ChatColor.translateAlternateColorCodes('&', instance.format(string, objects)); } } public static String capitalCase(final String input) { return input == null || input.length() == 0 ? input : input.toUpperCase(Locale.ENGLISH).charAt(0) + input.toLowerCase(Locale.ENGLISH).substring(1); } public void onEnable() { instance = this; } public void onDisable() { instance = null; } public Locale getCurrentLocale() { return currentMessageLocale; } private String translate(final String string) { try { try { return customBundle.getString(string); } catch (MissingResourceException ex) { return localeBundle.getString(string); } } catch (MissingResourceException ex) { plugin.log(ChatColor.RED + ex.getMessage()); plugin.log(ChatColor.RED + String.format("Missing translation key \"%s\" in translation file %s", ex.getKey(), localeBundle.getLocale().toString())); return defaultBundle.getString(string); } } private String format(final String string, final Object... objects) { String format = translate(string); MessageFormat messageFormat = messageFormatCache.get(format); if (messageFormat == null) { try { messageFormat = new MessageFormat(format); } catch (IllegalArgumentException e) { plugin.log(ChatColor.RED + e.getMessage()); plugin.log(ChatColor.RED + "Invalid Translation key for '" + string + "': " + e.getMessage()); format = format.replaceAll("\\{(\\D*?)\\}", "\\[$1\\]"); messageFormat = new MessageFormat(format); } messageFormatCache.put(format, messageFormat); } return messageFormat.format(objects); } public void updateLocale(final String loc) { if (loc != null && !loc.isEmpty()) { final String[] parts = loc.split("[_\\.]"); if (parts.length == 1) { currentMessageLocale = new Locale(parts[0]); } if (parts.length == 2) { currentMessageLocale = new Locale(parts[0], parts[1]); } if (parts.length == 3) { currentMessageLocale = new Locale(parts[0], parts[1], parts[2]); } } ResourceBundle.clearCache(); messageFormatCache = new HashMap<>(); plugin.log(ChatColor.GREEN + "Locale: \"" + currentMessageLocale.toString() + "\" | Locale file: " + "messages_" + currentMessageLocale.toString() + ".properties"); try { localeBundle = ResourceBundle.getBundle(MESSAGES, currentMessageLocale, new UTF8Control()); } catch (MissingResourceException ex) { localeBundle = NULL_BUNDLE; } try { customBundle = ResourceBundle.getBundle(MESSAGES, currentMessageLocale, new FileResClassLoader(I18n.class.getClassLoader(), plugin), new UTF8Control()); } catch (MissingResourceException ex) { customBundle = NULL_BUNDLE; } } private static class FileResClassLoader extends ClassLoader { private final transient File dataFolder; FileResClassLoader(final ClassLoader classLoader, final JavaPlugin plugin) { super(classLoader); this.dataFolder = plugin.getDataFolder(); } @Override public URL getResource(final String string) { final File file = new File(dataFolder, string); if (file.exists()) { try { return file.toURI().toURL(); } catch (MalformedURLException ignored) { } } return null; } @Override public InputStream getResourceAsStream(final String string) { final File file = new File(dataFolder, string); if (file.exists()) { try { return new FileInputStream(file); } catch (FileNotFoundException ignored) { } } return null; } } }
AdvancedKitsReloaded
src\main\java\hu\tryharddevs\advancedkits\utils\localization\UTF8Control.java
package hu.tryharddevs.advancedkits.utils.localization; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Locale; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; /***************************************************** * Created by TryHardDood on 2016. 12. 22.. ****************************************************/ class UTF8Control extends ResourceBundle.Control { public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { String bundleName = toBundleName(baseName, locale); String resourceName = toResourceName(bundleName, "properties"); ResourceBundle bundle = null; InputStream stream = null; if (reload) { URL url = loader.getResource(resourceName); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { connection.setUseCaches(false); stream = connection.getInputStream(); } } } else { stream = loader.getResourceAsStream(resourceName); } if (stream != null) { try { bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8")); } finally { stream.close(); } } return bundle; } }
AdvancedRocketryTweaker
build.gradle
buildscript { repositories { jcenter() maven { url = "https://files.minecraftforge.net/maven" } } dependencies { classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT' } } apply plugin: 'net.minecraftforge.gradle.forge' //Only edit below this line, the above code adds and enables the necessary things for Forge to be setup. version = "${project.mcVersion}-${project.modVersion}" group = "p455w0rd.art.${project.modId}" // http://maven.apache.org/guides/mini/guide-naming-conventions.html archivesBaseName = project.modName.replaceAll("\\s","") sourceCompatibility = targetCompatibility = '1.8' // Need this here so eclipse task generates correctly. compileJava { sourceCompatibility = targetCompatibility = '1.8' } repositories { maven { name "DVS1 Maven FS'" url 'http://dvs1.progwml6.com/files/maven' } maven { name = "CurseForge" url = "https://minecraft.curseforge.com/api/maven/" } maven { name = "Blamejared" url = "https://maven.blamejared.com/" } } minecraft { version = "${project.mcVersion}-${project.forgeVersion}" runDir = "eclipse" replace "@MODID@", project.modId replace "@MODNAME@", project.modName replace "@VERSION@", project.version replace "@MCVERSION@", project.mcVersion replace "@FORGEVERSION@", project.forgeVersion replace "@ARVERSION@", project.arVersion replace "@ARBUILD@", project.arBuild replace "@JEIVERSION@", project.jeiVersion replaceIn "ARTweaker.java" replaceIn "ModGlobals.java" // the mappings can be changed at any time, and must be in the following format. // snapshot_YYYYMMDD snapshot are built nightly. // stable_# stables are built at the discretion of the MCP team. // Use non-default mappings at your own risk. they may not always work. // simply re-run your setup task after changing the mappings to update your workspace. mappings = project.mappingsVersion // makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable. } dependencies { // you may put jars on which you depend on in ./libs // or you may define them like so.. //compile "some.group:artifact:version:classifier" //compile "some.group:artifact:version" // real examples //compile 'com.mod-buildcraft:buildcraft:6.0.8:dev' // adds buildcraft to the dev env //compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env // the 'provided' configuration is for optional dependencies that exist at compile-time but might not at runtime. //provided 'com.mod-buildcraft:buildcraft:6.0.8:dev' // the deobf configurations: 'deobfCompile' and 'deobfProvided' are the same as the normal compile and provided, // except that these dependencies get remapped to your current MCP mappings //deobfCompile "mezz.jei:jei_${mcVersion}:${jeiVersion}" deobfCompile "CraftTweaker2:CraftTweaker2-MC1120-Main:${ctVersion}" deobfCompile "com.blamejared:MTLib:3.0.5.15" deobfCompile "libvulpes:LibVulpes-${mcVersion}-${lvVersion}:deobf" deobfCompile "advanced-rocketry:AdvancedRocketry-${mcVersion}-${arVersion}:${arBuild}:deobf" // for more info... // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html // http://www.gradle.org/docs/current/userguide/dependency_management.html } processResources { includeEmptyDirs = false // this will ensure that this task is redone when the versions change. inputs.property "modId", project.modId inputs.property "modName", project.modName inputs.property "modVersion", project.modVersion inputs.property "mcVersion", project.minecraft.version inputs.property "forgeVersion", project.forgeVersion from(sourceSets.main.resources.srcDirs) { include 'mcmod.info' include "assets/${project.modId}/recipes/**.json" include "assets/${project.modId}/models/item/**.json" include "assets/${project.modId}/lang/**.lang" expand 'modId':project.modId, 'modName':project.modName, 'modVersion':project.modVersion, 'mcVersion':project.minecraft.version, 'forgeVersion':project.forgeVersion } // copy everything else from(sourceSets.main.resources.srcDirs) { exclude 'mcmod.info' exclude "assets/${project.modId}/recipes/**.json" exclude "assets/${project.modId}/models/item/**.json" exclude "assets/${project.modId}/lang/**.lang" } }
AdvancedRocketryTweaker
src\main\java\p455w0rd\art\ARTweaker.java
package p455w0rd.art; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import p455w0rd.art.init.ModGlobals; import p455w0rd.art.integration.CraftTweaker; @Mod(modid = ModGlobals.MODID, name = ModGlobals.NAME, version = ModGlobals.VERSION, dependencies = ModGlobals.DEP_LIST, acceptedMinecraftVersions="[" + ModGlobals.MCVERSION + "]") public class ARTweaker { @Instance(ModGlobals.MODID) public static ARTweaker INSTANCE; @EventHandler public void postInit(FMLPostInitializationEvent event) { if (Loader.isModLoaded(ModGlobals.CT_MODID)) CraftTweaker.performCraftTweakerActions(); } }
AdvancedRocketryTweaker
src\main\java\p455w0rd\art\init\ModGlobals.java
package p455w0rd.art.init; public class ModGlobals { public static final String MODID = "@MODID@"; public static final String VERSION = "@VERSION@"; public static final String NAME = "@MODNAME@"; public static final String MCVERSION = "@MCVERSION@"; public static final String AR_MODID = "advancedrocketry"; public static final String CT_MODID = "crafttweaker"; public static final String DEP_LIST = "required-after:" + AR_MODID + "@[@ARVERSION@,);required-after:jei@[@JEIVERSION@,);required-after:" + CT_MODID + ";required-after:mtlib;"; public static class ZENCLASSES { private static final String AR_ZENCLASS_BASE = "mods." + AR_MODID + "."; public static final String CHEMICALREACTOR_HANDLER = AR_ZENCLASS_BASE + "ChemicalReactor"; public static final String PRECISIONASSEMBLER_HANDLER = AR_ZENCLASS_BASE + "PrecisionAssembler"; public static final String CUTTINGMACHINE_HANDLER = AR_ZENCLASS_BASE + "CuttingMachine"; public static final String LATHE_HANDLER = AR_ZENCLASS_BASE + "Lathe"; public static final String ROLLINGMACHINE_HANDLER = AR_ZENCLASS_BASE + "RollingMachine"; public static final String ELECTROLYSER_HANDLER = AR_ZENCLASS_BASE + "Electrolyser"; public static final String ARCFURNACE_HANDLER = AR_ZENCLASS_BASE + "ArcFurnace"; public static final String CRYSTALLIZER_HANDLER = AR_ZENCLASS_BASE + "Crystallizer"; public static final String PLATEPRESSER_HANDLER = AR_ZENCLASS_BASE + "PlatePresser"; } }
AdvancedRocketryTweaker
src\main\java\p455w0rd\art\integration\CraftTweaker.java
package p455w0rd.art.integration; import com.blamejared.mtlib.helpers.InputHelper; import crafttweaker.CraftTweakerAPI; import crafttweaker.IAction; import crafttweaker.api.item.IIngredient; import crafttweaker.api.item.IItemStack; import crafttweaker.api.liquid.ILiquidStack; import crafttweaker.api.oredict.IOreDictEntry; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import zmaster587.libVulpes.interfaces.IRecipe; import zmaster587.libVulpes.recipe.NumberedOreDictStack; import zmaster587.libVulpes.recipe.RecipesMachine; public class CraftTweaker { protected static final LinkedList<IAction> LATE_ACTIONS = new LinkedList<>(); private static CraftTweaker INSTANCE; public Class getRecipeClass() { return null; } public static CraftTweaker getInstance() { if (INSTANCE == null) { INSTANCE = new CraftTweaker(); } return INSTANCE; } protected static List getRecipesForMachine(Class machineClass) { try { Class.forName(machineClass.getName()); List recipeList = RecipesMachine.getInstance().getRecipes(machineClass); if (recipeList == null) { throw new ClassNotFoundException("Machine Recipe Class " + machineClass.toString() + " not found in AR Recipe Registry"); } else { return recipeList; } } catch (ClassNotFoundException var2) { var2.printStackTrace(); return new ArrayList(); } } public static void performCraftTweakerActions() { try { LATE_ACTIONS.forEach(CraftTweakerAPI::apply); } catch (Exception var1) { var1.printStackTrace(); CraftTweakerAPI.logError("Error while applying actions", var1); } } protected static void addAction(IAction action) { if (!LATE_ACTIONS.contains(action)) { LATE_ACTIONS.add(action); } } public String formatObjectArray(Object[] objArray) { StringBuilder ret = new StringBuilder(); boolean first = true; for (Object obj : objArray) { if (!first) { ret.append("; "); } ret.append(this.formatObject(obj)); if (first) { first = false; } } return ret.toString(); } private String formatObject(Object obj) { if (obj instanceof FluidStack) { return "Fluid: " + ((FluidStack)obj).getFluid().getName() + "|Count: " + ((FluidStack)obj).amount; } else if (obj instanceof ILiquidStack) { return "Fluid: " + ((ILiquidStack)obj).getDisplayName() + "|Count: " + ((ILiquidStack)obj).getAmount(); } else if (obj instanceof ItemStack) { return "Item: " + ((ItemStack)obj).getDisplayName() + "|Count: " + ((ItemStack)obj).getCount(); } else if (obj instanceof IItemStack) { return "Item: " + ((IItemStack)obj).getDisplayName() + "|Count: " + ((IItemStack)obj).getAmount(); } else if (obj instanceof IOreDictEntry) { return "OreDict: " + ((IOreDictEntry)obj).getName() + "|Count: " + ((IOreDictEntry)obj).getAmount(); } else { return obj instanceof NumberedOreDictStack ? " OreDict: " + ((NumberedOreDictStack)obj).getOre() + "|Count: " + ((NumberedOreDictStack)obj).getNumber() : "Null: null"; } } protected static Object[] convertFromCT(Object[] input) { if (input != null && input.length > 0) { ArrayList<FluidStack> vanillaFluids = new ArrayList<>(); ArrayList<ItemStack> vanillaItems = new ArrayList<>(); ArrayList<NumberedOreDictStack> oreDicts = new ArrayList<>(); Object[] returnObj = input; int objIndex = input.length; int i; for(i = 0; i < objIndex; ++i) { Object element = returnObj[i]; if (element != null) { if (isLiquid(element)) { FluidStack liquidStack = getLiquid(element); if (liquidStack != null) { vanillaFluids.add(liquidStack); } } else if (isItem(element)) { ItemStack itemStack = getItem(element); if (itemStack != null) { vanillaItems.add(itemStack); } } else if (isOreDict(element)) { NumberedOreDictStack oreStack = getOreDict(element); if (oreStack != null) { oreDicts.add(oreStack); } } } } returnObj = new Object[vanillaFluids.size() + vanillaItems.size() + oreDicts.size()]; objIndex = 0; for(i = 0; i < vanillaFluids.size(); ++i) { returnObj[objIndex] = vanillaFluids.get(i); ++objIndex; } for(i = 0; i < vanillaItems.size(); ++i) { returnObj[objIndex] = vanillaItems.get(i); ++objIndex; } for(i = 0; i < oreDicts.size(); ++i) { returnObj[objIndex] = oreDicts.get(i); ++objIndex; } return returnObj; } else { return new Object[0]; } } private static boolean isItem(Object ctObj) { if (!(ctObj instanceof IItemStack) && !(ctObj instanceof ItemStack)) { if (!(ctObj instanceof IIngredient)) { return false; } else { return ((IIngredient)ctObj).getInternal() instanceof IItemStack || ((IIngredient)ctObj).getInternal() instanceof ItemStack; } } else { return true; } } protected static boolean isLiquid(Object ctObj) { if (!(ctObj instanceof ILiquidStack) && !(ctObj instanceof FluidStack)) { if (!(ctObj instanceof IIngredient)) { return false; } else { return ((IIngredient)ctObj).getInternal() instanceof ILiquidStack || ((IIngredient)ctObj).getInternal() instanceof FluidStack; } } else { return true; } } private static boolean isOreDict(Object ctObj) { return ctObj instanceof IIngredient ? ((IIngredient)ctObj).getInternal() instanceof IOreDictEntry : ctObj instanceof IOreDictEntry; } private static ItemStack getItem(Object obj) { if (isItem(obj)) { if (obj instanceof ItemStack) { return (ItemStack)obj; } else if (obj instanceof IIngredient) { return ((IIngredient)obj).getInternal() instanceof ItemStack ? (ItemStack)((IIngredient)obj).getInternal() : toVanilla((IItemStack)((IIngredient)obj).getInternal()); } else { return toVanilla((IItemStack)obj); } } else { return ItemStack.EMPTY; } } private static FluidStack getLiquid(Object obj) { if (isLiquid(obj)) { if (obj instanceof FluidStack) { return (FluidStack)obj; } else if (obj instanceof IIngredient) { return ((IIngredient)obj).getInternal() instanceof FluidStack ? (FluidStack)((IIngredient)obj).getInternal() : toVanilla((ILiquidStack)((IIngredient)obj).getInternal()); } else { return toVanilla((ILiquidStack)obj); } } else { return null; } } private static NumberedOreDictStack getOreDict(Object obj) { if (obj instanceof IIngredient && isOreDict(obj)) { IIngredient ingredient = (IIngredient)obj; Object type = ingredient.getInternal(); if (type instanceof IOreDictEntry) { return toVanilla((IOreDictEntry)type, ingredient.getAmount()); } } return obj instanceof IOreDictEntry ? toVanilla((IOreDictEntry)obj, ((IOreDictEntry)obj).getAmount()) : null; } private static NumberedOreDictStack toVanilla(IOreDictEntry oreDict, int amount) { return new NumberedOreDictStack(oreDict.getName(), amount); } private static ItemStack toVanilla(IItemStack item) { return InputHelper.toStack(item); } private static FluidStack toVanilla(ILiquidStack liquid) { return InputHelper.toFluid(liquid); } protected class Clear implements IAction { public Clear() { } public void apply() { if (CraftTweaker.this.getRecipeClass() != null) { CraftTweaker.getRecipesForMachine(CraftTweaker.this.getRecipeClass()).clear(); } } public String describe() { return CraftTweaker.this.getRecipeClass() != null ? "Cleared " + CraftTweaker.this.getRecipeClass().getSimpleName() + " Recipes" : ""; } } protected class Remove implements IAction { final FluidStack[] fluidOutput; final ItemStack[][] itemOutput; public Remove(FluidStack[] output) { this(output, null); } public Remove(ItemStack[][] output) { this(null, output); } public Remove(FluidStack[] fluidOutput, ItemStack[][] itemOutput) { this.fluidOutput = fluidOutput; this.itemOutput = itemOutput; } private ItemStack[] getAllStacks(ItemStack[][] stacks) { ArrayList<ItemStack> stackList = new ArrayList<>(); for (ItemStack[] stack : stacks) { for (ItemStack element : stack) { if (element != null) { stackList.add(element); } } } return stackList.toArray(new ItemStack[0]); } private ItemStack[] getAllStacks(List list) { return (ItemStack[])list.toArray(new ItemStack[0]); } public boolean matches(IRecipe recipe) { if (recipe == null) { return false; } else { int numFluidsToMatch = 0; int numItemsToMatch = 0; int i; if (this.itemOutput != null) { ItemStack[] matchArray = this.getAllStacks(this.itemOutput); numItemsToMatch = matchArray.length; ItemStack[] recipeArray = this.getAllStacks(recipe.getOutput()); if (numItemsToMatch != recipeArray.length) { return false; } for(i = 0; i < matchArray.length; ++i) { for (ItemStack element : recipeArray) { ItemStack stack1 = matchArray[i].copy(); stack1.setCount(1); ItemStack stack2 = element.copy(); stack2.setCount(1); if (ItemStack.areItemStacksEqual(stack1, stack2)) { --numItemsToMatch; if (numItemsToMatch == 0) { break; } } } } } if (this.fluidOutput != null) { if (this.fluidOutput.length != recipe.getFluidOutputs().size()) { return false; } numFluidsToMatch = this.fluidOutput.length; for(i = 0; i < this.fluidOutput.length; ++i) { for(int j = 0; j < recipe.getFluidOutputs().size(); ++j) { if (this.fluidOutput[i] != null && this.fluidOutput[i].getFluid() == recipe.getFluidOutputs().get(j).getFluid()) { --numFluidsToMatch; } } } } return numFluidsToMatch == 0 && numItemsToMatch == 0; } } public void apply() { if (CraftTweaker.this.getRecipeClass() != null) { List recipeList = CraftTweaker.getRecipesForMachine(CraftTweaker.this.getRecipeClass()); ListIterator recipeIterator = recipeList.listIterator(); while(recipeIterator.hasNext()) { IRecipe currentRecipe = (IRecipe)recipeIterator.next(); if (this.matches(currentRecipe)) { recipeIterator.remove(); break; } } } } public String describe() { if (CraftTweaker.this.getRecipeClass() != null) { boolean itemSupplied = this.itemOutput != null; boolean fluidSupplied = this.fluidOutput != null; String outputStr = "Removed Recipe for " + CraftTweaker.this.getRecipeClass().getSimpleName() + " with output \""; if (itemSupplied) { outputStr = outputStr + "-" + CraftTweaker.this.formatObjectArray(this.getAllStacks(this.itemOutput)).split("\\|")[0]; } if (fluidSupplied) { outputStr = outputStr + "-" + CraftTweaker.this.formatObjectArray(this.fluidOutput).split("\\|")[0] + "\""; } return outputStr + "\""; } else { return ""; } } } protected class Add implements IAction { final Object[] out; final int time; final int power; final Object[] inputs; public Add(Object[] out, int time, int power, Object[] inputs) { this.out = out; this.time = time; this.power = power; this.inputs = inputs; } public void apply() { if (CraftTweaker.this.getRecipeClass() != null) { RecipesMachine.getInstance().addRecipe(CraftTweaker.this.getRecipeClass(), this.out, this.time, this.power, this.inputs); } } public String describe() { return "Added Recipe" + (CraftTweaker.this.getRecipeClass() != null ? " for " + CraftTweaker.this.getRecipeClass().getSimpleName() : "") + ": INPUT:[" + CraftTweaker.this.formatObjectArray(this.inputs) + "] -> OUTPUT:[" + CraftTweaker.this.formatObjectArray(this.out) + "]; Time: " + this.time + "; Power: " + this.power; } } }
AdvancedRocketryTweaker
src\main\java\p455w0rd\art\integration\crafttweaker\HandlerArcFurnace.java
package p455w0rd.art.integration.crafttweaker; import com.blamejared.mtlib.helpers.InputHelper; import crafttweaker.annotations.ModOnly; import crafttweaker.annotations.ZenRegister; import crafttweaker.api.item.IItemStack; import net.minecraft.item.ItemStack; import p455w0rd.art.init.ModGlobals; import p455w0rd.art.integration.CraftTweaker; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import zmaster587.advancedRocketry.tile.multiblock.machine.TileElectricArcFurnace; @ZenClass(ModGlobals.ZENCLASSES.ARCFURNACE_HANDLER) @ModOnly(ModGlobals.AR_MODID) @ZenRegister public class HandlerArcFurnace extends CraftTweaker { private static HandlerArcFurnace INSTANCE; public static HandlerArcFurnace getInstance() { if (INSTANCE == null) { INSTANCE = new HandlerArcFurnace(); } return INSTANCE; } public Class getRecipeClass() { return TileElectricArcFurnace.class; } @ZenMethod public static void addRecipe(IItemStack output, int time, int power, IItemStack... inputs) { addRecipe(new ItemStack[]{InputHelper.toStack(output)}, time, power, (Object[]) InputHelper.toStacks(inputs)); } protected static void addRecipe(Object[] output, int time, int power, Object... inputs) { addAction(getInstance().new Add(output, time, power, inputs)); } @ZenMethod public static void removeRecipe(IItemStack output) { ItemStack[][] convertedOutput = new ItemStack[1][1]; convertedOutput[0][0] = InputHelper.toStack(output); removeRecipe(convertedOutput); } private static void removeRecipe(ItemStack[][] output) { if (output != null) { addAction(getInstance().new Remove(output)); } } @ZenMethod public static void clear() { addAction(getInstance().new Clear()); } }
AdvancedRocketryTweaker
src\main\java\p455w0rd\art\integration\crafttweaker\HandlerBlockPress.java
package p455w0rd.art.integration.crafttweaker; import com.blamejared.mtlib.helpers.InputHelper; import crafttweaker.annotations.ModOnly; import crafttweaker.annotations.ZenRegister; import crafttweaker.api.item.IIngredient; import crafttweaker.api.item.IItemStack; import net.minecraft.item.ItemStack; import p455w0rd.art.init.ModGlobals; import p455w0rd.art.integration.CraftTweaker; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import zmaster587.advancedRocketry.block.BlockSmallPlatePress; @ZenClass(ModGlobals.ZENCLASSES.PLATEPRESSER_HANDLER) @ModOnly(ModGlobals.AR_MODID) @ZenRegister public class HandlerBlockPress extends CraftTweaker { private static HandlerBlockPress INSTANCE; public static HandlerBlockPress getInstance() { if (INSTANCE == null) { INSTANCE = new HandlerBlockPress(); } return INSTANCE; } public Class getRecipeClass() { return BlockSmallPlatePress.class; } @ZenMethod public static void addRecipe(IIngredient output, IIngredient... inputs) { addRecipe(convertFromCT(new IIngredient[]{output}), 0, 0, convertFromCT(inputs)); } @ZenMethod public static void addRecipe(IItemStack output, IItemStack... inputs) { addRecipe(new ItemStack[]{InputHelper.toStack(output)}, 0, 0, (Object[]) InputHelper.toStacks(inputs)); } protected static void addRecipe(Object[] output, int time, int power, Object... inputs) { addAction(getInstance().new Add(output, time, power, inputs)); } @ZenMethod public static void removeRecipe(IItemStack output) { ItemStack[][] convertedOutput = new ItemStack[1][1]; convertedOutput[0][0] = InputHelper.toStack(output); addAction(getInstance().new Remove(convertedOutput)); } @ZenMethod public static void clear() { addAction(getInstance().new Clear()); } }
AdvancedRocketryTweaker
src\main\java\p455w0rd\art\integration\crafttweaker\HandlerChemicalReactor.java
package p455w0rd.art.integration.crafttweaker; import com.blamejared.mtlib.helpers.InputHelper; import crafttweaker.annotations.ModOnly; import crafttweaker.annotations.ZenRegister; import crafttweaker.api.item.IItemStack; import crafttweaker.api.liquid.ILiquidStack; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import p455w0rd.art.init.ModGlobals; import p455w0rd.art.integration.CraftTweaker; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import zmaster587.advancedRocketry.tile.multiblock.machine.TileChemicalReactor; @ZenClass(ModGlobals.ZENCLASSES.CHEMICALREACTOR_HANDLER) @ModOnly(ModGlobals.AR_MODID) @ZenRegister public class HandlerChemicalReactor extends CraftTweaker { private static HandlerChemicalReactor INSTANCE; public Class getRecipeClass() { return TileChemicalReactor.class; } public static HandlerChemicalReactor getInstance() { if (INSTANCE == null) { INSTANCE = new HandlerChemicalReactor(); } return INSTANCE; } @ZenMethod public static void addRecipe(IItemStack output, int time, int power, Object... inputs) { ItemStack outputConverted = InputHelper.toStack(output); addRecipe(new Object[]{outputConverted}, time, power, convertFromCT(inputs)); } @ZenMethod public static void addRecipe(ILiquidStack output, int time, int power, Object... inputs) { FluidStack outputConverted = InputHelper.toFluid(output); addRecipe(new FluidStack[]{outputConverted}, time, power, convertFromCT(inputs)); } @ZenMethod public static void removeRecipe(ILiquidStack output) { removeRecipe(InputHelper.toFluid(output)); } protected static void addRecipe(Object[] output, int time, int power, Object... inputs) { addAction(getInstance().new Add(output, time, power, inputs)); } private static void removeRecipe(FluidStack output) { if (output != null) { removeRecipe(new FluidStack[]{output}); } } @ZenMethod public static void removeRecipe(IItemStack output) { ItemStack[][] convertedOutput = new ItemStack[1][1]; convertedOutput[0][0] = InputHelper.toStack(output); removeRecipe(convertedOutput); } private static void removeRecipe(ItemStack[][] output) { if (output != null) { addAction(getInstance().new Remove(output)); } } private static void removeRecipe(FluidStack[] output) { addAction(getInstance().new Remove(output)); } @ZenMethod public static void removeRecipe(ILiquidStack[] output) { removeRecipe(InputHelper.toFluids(output)); } @ZenMethod public static void clear() { addAction(getInstance().new Clear()); } }
AdvancedRocketryTweaker
src\main\java\p455w0rd\art\integration\crafttweaker\HandlerCrystallizer.java
package p455w0rd.art.integration.crafttweaker; import com.blamejared.mtlib.helpers.InputHelper; import crafttweaker.annotations.ModOnly; import crafttweaker.annotations.ZenRegister; import crafttweaker.api.item.IItemStack; import net.minecraft.item.ItemStack; import p455w0rd.art.init.ModGlobals; import p455w0rd.art.integration.CraftTweaker; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import zmaster587.advancedRocketry.tile.multiblock.machine.TileCrystallizer; @ZenClass(ModGlobals.ZENCLASSES.CRYSTALLIZER_HANDLER) @ModOnly(ModGlobals.AR_MODID) @ZenRegister public class HandlerCrystallizer extends CraftTweaker { private static HandlerCrystallizer INSTANCE; public static HandlerCrystallizer getInstance() { if (INSTANCE == null) { INSTANCE = new HandlerCrystallizer(); } return INSTANCE; } public Class getRecipeClass() { return TileCrystallizer.class; } @ZenMethod public static void addRecipe(IItemStack output, int time, int power, IItemStack... inputs) { addRecipe(new ItemStack[]{InputHelper.toStack(output)}, time, power, (Object[]) InputHelper.toStacks(inputs)); } protected static void addRecipe(Object[] output, int time, int power, Object... inputs) { addAction(getInstance().new Add(output, time, power, inputs)); } @ZenMethod public static void removeRecipe(IItemStack output) { ItemStack[][] convertedOutput = new ItemStack[1][1]; convertedOutput[0][0] = InputHelper.toStack(output); removeRecipe(convertedOutput); } private static void removeRecipe(ItemStack[][] output) { if (output != null) { addAction(getInstance().new Remove(output)); } } @ZenMethod public static void clear() { addAction(getInstance().new Clear()); } }
AdvancedRocketryTweaker
src\main\java\p455w0rd\art\integration\crafttweaker\HandlerCuttingMachine.java
package p455w0rd.art.integration.crafttweaker; import com.blamejared.mtlib.helpers.InputHelper; import crafttweaker.annotations.ModOnly; import crafttweaker.annotations.ZenRegister; import crafttweaker.api.item.IItemStack; import net.minecraft.item.ItemStack; import p455w0rd.art.init.ModGlobals; import p455w0rd.art.integration.CraftTweaker; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import zmaster587.advancedRocketry.tile.multiblock.machine.TileCuttingMachine; @ZenClass(ModGlobals.ZENCLASSES.CUTTINGMACHINE_HANDLER) @ModOnly(ModGlobals.AR_MODID) @ZenRegister public class HandlerCuttingMachine extends CraftTweaker { private static HandlerCuttingMachine INSTANCE; public static HandlerCuttingMachine getInstance() { if (INSTANCE == null) { INSTANCE = new HandlerCuttingMachine(); } return INSTANCE; } public Class getRecipeClass() { return TileCuttingMachine.class; } @ZenMethod public static void addRecipe(IItemStack output, int time, int power, Object... inputs) { addRecipe(new IItemStack[]{output}, time, power, inputs); } @ZenMethod public static void removeRecipe(IItemStack output) { ItemStack[][] convertedOutput = new ItemStack[1][1]; convertedOutput[0][0] = InputHelper.toStack(output); removeRecipe(convertedOutput); } private static void removeRecipe(ItemStack[][] output) { if (output != null) { addAction(getInstance().new Remove(output)); } } @ZenMethod public static void clear() { addAction(getInstance().new Clear()); } private static void addRecipe(IItemStack[] output, int time, int power, Object... inputs) { addRecipe(InputHelper.toStacks(output), time, power, convertFromCT(inputs)); } protected static void addRecipe(Object[] output, int time, int power, Object... inputs) { addAction(getInstance().new Add(output, time, power, inputs)); } }
AdvancedRocketryTweaker
src\main\java\p455w0rd\art\integration\crafttweaker\HandlerElectrolyser.java
package p455w0rd.art.integration.crafttweaker; import com.blamejared.mtlib.helpers.InputHelper; import crafttweaker.annotations.ModOnly; import crafttweaker.annotations.ZenRegister; import crafttweaker.api.liquid.ILiquidStack; import p455w0rd.art.init.ModGlobals; import p455w0rd.art.integration.CraftTweaker; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import zmaster587.advancedRocketry.tile.multiblock.machine.TileElectrolyser; @ZenClass(ModGlobals.ZENCLASSES.ELECTROLYSER_HANDLER) @ModOnly(ModGlobals.AR_MODID) @ZenRegister public class HandlerElectrolyser extends CraftTweaker { private static HandlerElectrolyser INSTANCE; public static HandlerElectrolyser getInstance() { if (INSTANCE == null) { INSTANCE = new HandlerElectrolyser(); } return INSTANCE; } public Class getRecipeClass() { return TileElectrolyser.class; } @ZenMethod public static void addRecipe(ILiquidStack output1, ILiquidStack output2, int time, int power, ILiquidStack input) { ILiquidStack[] output = output2 == null ? new ILiquidStack[]{output1} : new ILiquidStack[]{output1, output2}; addRecipe(InputHelper.toFluids(output), time, power, InputHelper.toFluid(input)); } protected static void addRecipe(Object[] output, int time, int power, Object... inputs) { if ((output.length == 1 || output.length == 2) && inputs.length == 1) { addAction(getInstance().new Add(output, time, power, inputs)); } } @ZenMethod public static void removeRecipe(ILiquidStack output1, ILiquidStack output2) { addAction(getInstance().new Remove(InputHelper.toFluids(new ILiquidStack[]{output1, output2}))); } @ZenMethod public static void clear() { addAction(getInstance().new Clear()); } }
AdvancedRocketryTweaker
src\main\java\p455w0rd\art\integration\crafttweaker\HandlerLathe.java
package p455w0rd.art.integration.crafttweaker; import com.blamejared.mtlib.helpers.InputHelper; import crafttweaker.annotations.ModOnly; import crafttweaker.annotations.ZenRegister; import crafttweaker.api.item.IItemStack; import net.minecraft.item.ItemStack; import p455w0rd.art.init.ModGlobals; import p455w0rd.art.integration.CraftTweaker; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import zmaster587.advancedRocketry.tile.multiblock.machine.TileLathe; @ZenClass(ModGlobals.ZENCLASSES.LATHE_HANDLER) @ModOnly(ModGlobals.AR_MODID) @ZenRegister public class HandlerLathe extends CraftTweaker { private static HandlerLathe INSTANCE; public static HandlerLathe getInstance() { if (INSTANCE == null) { INSTANCE = new HandlerLathe(); } return INSTANCE; } public Class getRecipeClass() { return TileLathe.class; } @ZenMethod public static void addRecipe(IItemStack output, int time, int power, Object... inputs) { addRecipe(new IItemStack[]{output}, time, power, inputs); } @ZenMethod public static void removeRecipe(IItemStack output) { ItemStack[][] convertedOutput = new ItemStack[1][1]; convertedOutput[0][0] = InputHelper.toStack(output); removeRecipe(convertedOutput); } private static void removeRecipe(ItemStack[][] output) { if (output != null) { addAction(getInstance().new Remove(output)); } } @ZenMethod public static void clear() { addAction(getInstance().new Clear()); } public static void addRecipe(IItemStack[] output, int time, int power, Object... inputs) { addRecipe(InputHelper.toStacks(output), time, power, convertFromCT(inputs)); } protected static void addRecipe(Object[] output, int time, int power, Object... inputs) { if (output.length == 1 && inputs.length == 1) { addAction(getInstance().new Add(output, time, power, inputs)); } } }
AdvancedRocketryTweaker
src\main\java\p455w0rd\art\integration\crafttweaker\HandlerPrecisionAssembler.java
package p455w0rd.art.integration.crafttweaker; import com.blamejared.mtlib.helpers.InputHelper; import crafttweaker.annotations.ModOnly; import crafttweaker.annotations.ZenRegister; import crafttweaker.api.item.IItemStack; import net.minecraft.item.ItemStack; import p455w0rd.art.init.ModGlobals; import p455w0rd.art.integration.CraftTweaker; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import zmaster587.advancedRocketry.tile.multiblock.machine.TilePrecisionAssembler; @ZenClass(ModGlobals.ZENCLASSES.PRECISIONASSEMBLER_HANDLER) @ModOnly(ModGlobals.AR_MODID) @ZenRegister public class HandlerPrecisionAssembler extends CraftTweaker { private static HandlerPrecisionAssembler INSTANCE; public static HandlerPrecisionAssembler getInstance() { if (INSTANCE == null) { INSTANCE = new HandlerPrecisionAssembler(); } return INSTANCE; } public Class getRecipeClass() { return TilePrecisionAssembler.class; } @ZenMethod public static void addRecipe(IItemStack output, int time, int power, Object... inputs) { addRecipe(new IItemStack[]{output}, time, power, inputs); } @ZenMethod public static void removeRecipe(IItemStack output) { ItemStack[][] convertedOutput = new ItemStack[1][1]; convertedOutput[0][0] = InputHelper.toStack(output); removeRecipe(convertedOutput); } private static void removeRecipe(ItemStack[][] output) { addAction(getInstance().new Remove(output)); } @ZenMethod public static void clear() { addAction(getInstance().new Clear()); } private static void addRecipe(IItemStack[] output, int time, int power, Object... inputs) { addRecipe(InputHelper.toStacks(output), time, power, convertFromCT(inputs)); } protected static void addRecipe(Object[] output, int time, int power, Object... inputs) { addAction(getInstance().new Add(output, time, power, inputs)); } }
AdvancedRocketryTweaker
src\main\java\p455w0rd\art\integration\crafttweaker\HandlerRollingMachine.java
package p455w0rd.art.integration.crafttweaker; import com.blamejared.mtlib.helpers.InputHelper; import com.google.common.collect.Lists; import crafttweaker.annotations.ModOnly; import crafttweaker.annotations.ZenRegister; import crafttweaker.api.item.IItemStack; import java.util.ArrayList; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import p455w0rd.art.init.ModGlobals; import p455w0rd.art.integration.CraftTweaker; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import zmaster587.advancedRocketry.tile.multiblock.machine.TileRollingMachine; @ZenClass(ModGlobals.ZENCLASSES.ROLLINGMACHINE_HANDLER) @ModOnly(ModGlobals.AR_MODID) @ZenRegister public class HandlerRollingMachine extends CraftTweaker { private static HandlerRollingMachine INSTANCE; public static HandlerRollingMachine getInstance() { if (INSTANCE == null) { INSTANCE = new HandlerRollingMachine(); } return INSTANCE; } public Class getRecipeClass() { return TileRollingMachine.class; } @ZenMethod public static void addRecipe(IItemStack output, int time, int power, int waterAmount, Object... inputs) { addRecipe(new IItemStack[]{output}, time, power, waterAmount, inputs); } @ZenMethod public static void removeRecipe(IItemStack output) { ItemStack[][] convertedOutput = new ItemStack[1][1]; convertedOutput[0][0] = InputHelper.toStack(output); removeRecipe(convertedOutput); } private static void removeRecipe(ItemStack[][] output) { if (output != null) { addAction(getInstance().new Remove(output)); } } @ZenMethod public static void clear() { addAction(getInstance().new Clear()); } private static void addRecipe(IItemStack[] output, int time, int power, int waterAmount, Object... inputs) { ArrayList<Object> inputList = Lists.newArrayList(inputs); inputList.add(1, new FluidStack(FluidRegistry.WATER, waterAmount)); ItemStack[] outputConverted = InputHelper.toStacks(output); addRecipe(outputConverted, time, power, convertFromCT(inputList.toArray(new Object[0]))); } protected static void addRecipe(Object[] output, int time, int power, Object... inputs) { addAction(getInstance().new Add(output, time, power, inputs)); } }
advancements-debug
build.gradle
plugins { id 'fabric-loom' version '0.5-SNAPSHOT' id 'maven-publish' } sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 archivesBaseName = project.archives_base_name version = project.mod_version group = project.maven_group dependencies { // To change the versions see the gradle.properties file minecraft "com.mojang:minecraft:${project.minecraft_version}" mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" // Fabric API. This is technically optional, but you probably want it anyway. //modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" // PSA: Some older mods, compiled on Loom 0.2.1, might have outdated Maven POMs. // You may need to force-disable transitiveness on them. } processResources { inputs.property "version", project.version filesMatching("fabric.mod.json") { expand "version": project.version } } tasks.withType(JavaCompile).configureEach { // ensure that the encoding is set to UTF-8, no matter what the system default is // this fixes some edge cases with special characters not displaying correctly // see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html // If Javadoc is generated, this must be specified in that task too. it.options.encoding = "UTF-8" // The Minecraft launcher currently installs Java 8 for users, so your mod probably wants to target Java 8 too // JDK 9 introduced a new way of specifying this that will make sure no newer classes or methods are used. // We'll use that if it's available, but otherwise we'll use the older option. def targetVersion = 8 if (JavaVersion.current().isJava9Compatible()) { it.options.release = targetVersion } } java { // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task // if it is present. // If you remove this line, sources will not be generated. withSourcesJar() } jar { from("LICENSE") { rename { "${it}_${project.archivesBaseName}"} } } // configure the maven publication publishing { publications { mavenJava(MavenPublication) { // add all the jars that should be included when publishing to maven artifact(remapJar) { builtBy remapJar } artifact(sourcesJar) { builtBy remapSourcesJar } } } // Select the repositories you want to publish to // To publish to maven local, no extra repositories are necessary. Just use the task `publishToMavenLocal`. repositories { // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. } }
advancements-debug
settings.gradle
pluginManagement { repositories { jcenter() maven { name = 'Fabric' url = 'https://maven.fabricmc.net/' } gradlePluginPortal() } }
advancements-debug
src\main\resources\advdebug.mixins.json
{ "required": true, "minVersion": "0.8", "package": "technici4n.advdebug.mixin", "compatibilityLevel": "JAVA_8", "mixins": [ "PlayerAdvancementTrackerMixin" ], "injectors": { "defaultRequire": 1 } }
advancements-debug
src\main\resources\fabric.mod.json
{ "schemaVersion": 1, "id": "advdebug", "version": "${version}", "name": "Advancements Debug", "description": "This little mod rewrites one function of the advancements logic to make advancements checking faster, and use less recursion. It should prevent StackOverflowErrors with advancements.", "authors": [ "Technici4n" ], "contact": { "homepage": "https://www.curseforge.com/minecraft/mc-mods/advancements-debug", "sources": "https://github.com/Technici4n/advancements-debug", "issues": "https://github.com/Technici4n/advancements-debug/issues" }, "license": "CC0-1.0", "icon": "assets/advdebug/icon.png", "environment": "*", "mixins": [ "advdebug.mixins.json" ], "depends": { "fabricloader": ">=0.10.8" } }
advancements-debug
src\main\java\technici4n\advdebug\mixin\PlayerAdvancementTrackerMixin.java
package technici4n.advdebug.mixin; import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet; import net.minecraft.advancement.Advancement; import net.minecraft.advancement.AdvancementProgress; import net.minecraft.advancement.PlayerAdvancementTracker; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import java.util.*; @Mixin(PlayerAdvancementTracker.class) public abstract class PlayerAdvancementTrackerMixin { @Shadow @Final private Set<Advancement> visibleAdvancements; @Shadow @Final private Set<Advancement> visibilityUpdates; @Shadow @Final private Set<Advancement> progressUpdates; @Shadow @Final private Map<Advancement, AdvancementProgress> advancementToProgress; @Shadow protected abstract boolean canSee(Advancement advancement); private void updateDisplayDfs(Advancement advancement, Set<Advancement> visited) { if(visited.add(advancement)) { boolean bl = this.canSee(advancement); boolean bl2 = this.visibleAdvancements.contains(advancement); if (bl && !bl2) { this.visibleAdvancements.add(advancement); this.visibilityUpdates.add(advancement); if (this.advancementToProgress.containsKey(advancement)) { this.progressUpdates.add(advancement); } } else if (!bl && bl2) { this.visibleAdvancements.remove(advancement); this.visibilityUpdates.add(advancement); } for(Advancement child : advancement.getChildren()) { updateDisplayDfs(child, visited); } Advancement parent = advancement.getParent(); if (bl != bl2 && parent != null) { updateDisplayDfs(parent, visited); } } } @Overwrite protected void updateDisplay(Advancement advancement) { updateDisplayDfs(advancement, new ReferenceOpenHashSet<>()); } }
AI-Improvements
build.gradle
buildscript { repositories { maven { url = 'https://files.minecraftforge.net/maven' } maven { url = 'https://maven.parchmentmc.org' } mavenCentral() } dependencies { classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '5.1.+', changing: true classpath 'org.parchmentmc:librarian:1.+' } } //Plugins apply plugin: 'net.minecraftforge.gradle' apply plugin: 'org.parchmentmc.librarian.forgegradle' apply plugin: 'eclipse' //Set source level java.toolchain.languageVersion = JavaLanguageVersion.of(17) println('Java: ' + System.getProperty('java.version') + ' JVM: ' + System.getProperty('java.vm.version') + '(' + System.getProperty('java.vendor') + ') Arch: ' + System.getProperty('os.arch')) archivesBaseName=project.properties['file_name'] group='com.builtbroken.aiimprovements' //Minecraft build settings minecraft { mappings channel: project.properties['mappings_channel'], version: project.properties['mappings'] accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') runs { client { workingDirectory project.file('run/client') properties 'forge.logging.console.level': 'debug' mods { aiimprovements { source sourceSets.main } } } server { workingDirectory project.file('run/server') properties 'forge.logging.console.level': 'debug' mods { aiimprovements { source sourceSets.main } } } } } dependencies { minecraft project.properties['forge_version'] } jar { manifest { attributes(["Specification-Title": "AI-Improvements", "Specification-Vendor": "Built Broken Modding", "Specification-Version": project.properties['version'], "Implementation-Title": "AI-Improvements", "Implementation-Version": project.properties['version'], "Implementation-Vendor" :"Built Broken Modding", "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")]) } }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\AIImprovements.java
package com.builtbroken.ai.improvements; import com.builtbroken.ai.improvements.modifier.ModifierSystem; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; /** * Created by Dark on 7/20/2015. */ @Mod.EventBusSubscriber(modid = AIImprovements.DOMAIN, bus = Mod.EventBusSubscriber.Bus.MOD) @Mod(AIImprovements.DOMAIN) public class AIImprovements { public static final String DOMAIN = "aiimprovements"; public AIImprovements() { ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, ConfigMain.CONFIG_SPEC); } @SubscribeEvent public static void onFMLCommonSetup(FMLCommonSetupEvent event) { FastTrig.init(); ModifierSystem.init(); } }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\ConfigMain.java
package com.builtbroken.ai.improvements; import java.util.List; import org.apache.commons.lang3.tuple.Pair; import net.minecraftforge.common.ForgeConfigSpec; import net.minecraftforge.common.ForgeConfigSpec.BooleanValue; import net.minecraftforge.common.ForgeConfigSpec.ConfigValue; /** * Created by Dark(DarkGuardsman, Robert) on 2019-08-01. */ public class ConfigMain { public record AnimalConfigSection(BooleanValue removeFloat, BooleanValue removePanic, BooleanValue removeBreed, BooleanValue removeTempt, BooleanValue removeFollowParent, BooleanValue removeStroll) {} public record FilteredConfigValue(BooleanValue configValue, BooleanValue isAllowlist, ConfigValue<List<? extends String>> filterList) { public boolean isFiltered(String string) { return isAllowlist.get() != filterList.get().contains(string); } } public static final ForgeConfigSpec CONFIG_SPEC; public static final ConfigMain CONFIG; //Global public final BooleanValue allowRemoveCalls; public final BooleanValue enableCallBubbling; //Generic mob public final FilteredConfigValue removeLookGoal; public final FilteredConfigValue removeLookRandom; public final FilteredConfigValue replaceLookController; //Fish public final BooleanValue removeFishSwim; public final BooleanValue removeFishAvoidPlayer; public final BooleanValue removeFishPanic; public final BooleanValue removeFishFollowLeader; public final BooleanValue removeFishPuff; //Squid public final BooleanValue removeSquidFlee; public final BooleanValue removeRandomMove; //Animals public final AnimalConfigSection cow; public final AnimalConfigSection chicken; public final AnimalConfigSection pig; public final AnimalConfigSection sheep; public final BooleanValue removeSheepEatBlock; static { Pair<ConfigMain, ForgeConfigSpec> specPair = new ForgeConfigSpec.Builder().configure(ConfigMain::new); CONFIG_SPEC = specPair.getRight(); CONFIG = specPair.getLeft(); } ConfigMain(ForgeConfigSpec.Builder builder) { builder.comment("Entity Settings").push("entity"); //General Settings builder.comment("General").push("general"); allowRemoveCalls = builder .comment("Allow AI tasks to be removed from entities at runtime. If this is disable no per mob or per mob type removes will run.") .define("allow_remove_calls", true); enableCallBubbling = builder .comment("Allows repeat remove calls to bubble to the top of the list to improve performance of repeat mob spawning.") .define("enable_call_bubbling", true); builder.pop(); //Anything extending EntityMob (Animals, NPCS, Monsters, etc... basically everything) builder.comment("Entity Mob").push("mob"); removeLookGoal = createFilteredConfigValue(builder, "Remove Look Goal", "Remove the look at goal (player or attack target) AI task. This will cause AIs to not face targets or walking directions.", "remove_look_goal", false); removeLookRandom = createFilteredConfigValue(builder, "Remove Look Random", "Remove the look at random position AI task. This will cause AIs to feel a little lifeless as they do not animate head movement while idle.", "remove_look_random", false); replaceLookController = createFilteredConfigValue(builder, "Replace Look Controller", "Replaces the default look controller with a version featuring cached tan math improving performance. Only works on vanilla style mobs, if a mod overrides the look controller it will skip.", "replace_look_controller", true); builder.pop(); //Anything extending AbstractFish builder.comment("Entity Fish").push("fish"); removeFishSwim = builder .comment("Remove the fish's random swimming pathfinder. This will cause fish to stay in position more often.") .define("remove_swim", false); removeFishPanic = builder .comment("Remove the fish's panic pathfinder. This will cause fish to not run away.") .define("remove_panic", false); removeFishAvoidPlayer = builder .comment("Remove the fish's AI task to avoid players.") .define("remove_avoid_player", false); removeFishFollowLeader = builder .comment("Remove the fish's AI task to follow a leader fish to act as a group of fish.") .define("remove_follow_leader", false); removeFishPuff = builder .comment("Remove the fish's AI task to puff up when entities are nearby") .define("remove_puff", false); builder.pop(); //Anything extending AbstractFish builder.comment("Squid Fish").push("squid"); removeSquidFlee = builder .comment("Remove the squid's flee pathfinder. This will cause squid to not run away.") .define("remove_flee", false); removeRandomMove = builder .comment("Remove the squid's random movement pathfinder. This will cause squid to swim around randomly.") .define("remove_random_move", false); builder.pop(); //pushing done within the method, popping dependent on the boolean parameter cow = createAnimalConfigSection(builder, "Cow", "cow", "cows", true); chicken = createAnimalConfigSection(builder, "Chicken", "chicken", "chickens", true); pig = createAnimalConfigSection(builder, "Pig", "pig", "pigs", true); sheep = createAnimalConfigSection(builder, "Sheep", "sheep", "sheep", false); removeSheepEatBlock = builder .comment("Remove the sheep's eat block AI task. This causes sheep to no longer eat grass, and thus be unable to regenerate their wool.") .define("remove_eat_block", false); builder.pop(); //pop the sheep section builder.pop(); } private AnimalConfigSection createAnimalConfigSection(ForgeConfigSpec.Builder builder, String categoryComment, String singular, String plural, boolean shouldPop) { builder.comment(categoryComment).push(singular); AnimalConfigSection animalConfig = new AnimalConfigSection( builder.comment(String.format("Remove the %s's float AI task. This causes %s to no longer swim in water.", singular, plural)) .define("remove_float", false), builder.comment(String.format("Remove the %s's panic AI task. This causes %s to no longer run around after being hit, or search water to extinguish themselves.", singular, plural)) .define("remove_panic", false), builder.comment(String.format("Remove the %s's breed AI task. This causes %s to be unable to breed to create offspring.", singular, plural)) .define("remove_breed", false), builder.comment(String.format("Remove the %s's tempt AI task. This causes %s to no longer follow the player if they're holding an item they like.", singular, plural)) .define("remove_tempt", false), builder.comment(String.format("Remove the %s's follow parent AI task. This causes baby %s to no longer follow their parents.", singular, plural)) .define("remove_follow_parent", false), builder.comment(String.format("Remove the %s's random stroll AI task. This causes %s to no longer walk around randomly.", singular, plural)) .define("remove_stroll", false)); if(shouldPop) builder.pop(); return animalConfig; } private FilteredConfigValue createFilteredConfigValue(ForgeConfigSpec.Builder builder, String section, String comment, String path, boolean defaultValue) { FilteredConfigValue filteredConfigValue; builder.comment(section).push(path); filteredConfigValue = new FilteredConfigValue( builder.comment(comment) .define(path, defaultValue), builder.comment("Set this to true to apply this setting to all mobs on the filter list. Set this to false to NOT apply this to mobs on the filter list.") .define("is_allowlist", false), builder.comment("The list of mobs that is affected by this setting according to is_allowlist") .defineList("filter_list", List.of(), e -> e instanceof String)); builder.pop(); return filteredConfigValue; } }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\FastTrig.java
package com.builtbroken.ai.improvements; //http://www.java-gaming.org/index.php?topic=14647.0 public class FastTrig { //TODO recode to be object based to allow for several versions to exist //TODO move to core when recoded //TODO recode vector math to use this helper private static final int ATAN2_BITS = 8; private static final int ATAN2_BITS2 = ATAN2_BITS << 1; private static final int ATAN2_MASK = ~(-1 << ATAN2_BITS2); private static final int ATAN2_COUNT = ATAN2_MASK + 1; private static final int ATAN2_DIM = (int) Math.sqrt(ATAN2_COUNT); private static final float INV_ATAN2_DIM_MINUS_1 = 1.0f / (ATAN2_DIM - 1); private static final float[] atan2 = new float[ATAN2_COUNT]; public static void init() { for (int i = 0; i < ATAN2_DIM; i++) { for (int j = 0; j < ATAN2_DIM; j++) { float x0 = (float) i / ATAN2_DIM; float y0 = (float) j / ATAN2_DIM; atan2[j * ATAN2_DIM + i] = (float) Math.atan2(y0, x0); } } } public static final float atan2(double y, double x) { float add, mul; if (x < 0.0f) { if (y < 0.0f) { x = -x; y = -y; mul = 1.0f; } else { x = -x; mul = -1.0f; } add = -3.141592653f; } else { if (y < 0.0f) { y = -y; mul = -1.0f; } else { mul = 1.0f; } add = 0.0f; } double invDiv = 1.0f / (((x < y) ? y : x) * INV_ATAN2_DIM_MINUS_1); int xi = (int) (x * invDiv); int yi = (int) (y * invDiv); return (atan2[yi * ATAN2_DIM + xi] + add) * mul; } }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\FixedLookControl.java
package com.builtbroken.ai.improvements; import java.util.Optional; import net.minecraft.util.Mth; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.control.LookControl; /** * Created by Dark on 7/20/2015. */ public class FixedLookControl extends LookControl { public FixedLookControl(Mob entity) { super(entity); } @Override protected Optional<Float> getXRotD() { double lvt_1_1_ = this.wantedX - this.mob.getX(); double lvt_3_1_ = this.wantedY - (this.mob.getY() + this.mob.getEyeHeight()); double lvt_5_1_ = this.wantedZ - this.mob.getZ(); double lvt_7_1_ = Mth.sqrt((float)(lvt_1_1_ * lvt_1_1_ + lvt_5_1_ * lvt_5_1_)); return Optional.of((float) (-(tan(lvt_3_1_, lvt_7_1_) * 57.2957763671875D))); } @Override protected Optional<Float> getYRotD() { double lvt_1_1_ = this.wantedX - this.mob.getX(); double lvt_3_1_ = this.wantedZ - this.mob.getZ(); return Optional.of((float) (tan(lvt_3_1_, lvt_1_1_) * 57.2957763671875D) - 90.0F); } public static float tan(double a, double b) { return FastTrig.atan2(a, b); } public void copyDataIntoSelf(LookControl oldHelper) { wantedX = oldHelper.getWantedX(); wantedY = oldHelper.getWantedY(); wantedZ = oldHelper.getWantedZ(); lookAtCooldown = oldHelper.lookAtCooldown; xMaxRotAngle = oldHelper.xMaxRotAngle; yMaxRotSpeed = oldHelper.yMaxRotSpeed; } }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\modifier\ModifierLevel.java
package com.builtbroken.ai.improvements.modifier; import java.util.function.Function; import com.builtbroken.ai.improvements.modifier.editor.ModifierLayer; import com.builtbroken.ai.improvements.modifier.filters.FilterLayer; import com.builtbroken.ai.improvements.modifier.filters.FilterNode; import com.builtbroken.ai.improvements.modifier.filters.FilterResult; import com.builtbroken.ai.improvements.modifier.filters.IFilterNode; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Mob; /** * Created by Dark(DarkGuardsman, Robert) on 8/3/2019. */ public class ModifierLevel extends FilterNode { public final ModifierLayer goalEditor = new ModifierLayer(false); public final ModifierLayer combatGoalEditor = new ModifierLayer(true); public final FilterLayer filters = new FilterLayer(null); public static ModifierLevel newFilter(Function<Entity, Boolean> filter) { return new ModifierLevel(((entity) -> filter.apply(entity) ? FilterResult.FILTERED : FilterResult.DID_NOTHING)); } private ModifierLevel(IFilterNode filter) { super(filter); } @Override public FilterResult handle(Entity entity) { FilterResult filterResult = action.handle(entity); if (filterResult != FilterResult.DID_NOTHING) { if (entity instanceof Mob mob) { goalEditor.handle(mob); combatGoalEditor.handle(mob); } return filters.handle(entity); } return filterResult; } }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\modifier\ModifierSystem.java
package com.builtbroken.ai.improvements.modifier; import com.builtbroken.ai.improvements.AIImprovements; import com.builtbroken.ai.improvements.ConfigMain; import com.builtbroken.ai.improvements.ConfigMain.AnimalConfigSection; import com.builtbroken.ai.improvements.ConfigMain.FilteredConfigValue; import com.builtbroken.ai.improvements.FixedLookControl; import com.builtbroken.ai.improvements.modifier.editor.FilteredRemove; import com.builtbroken.ai.improvements.modifier.editor.GenericRemove; import com.builtbroken.ai.improvements.modifier.filters.FilterLayer; import com.builtbroken.ai.improvements.modifier.filters.FilterResult; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.control.LookControl; import net.minecraft.world.entity.ai.goal.AvoidEntityGoal; import net.minecraft.world.entity.ai.goal.BreedGoal; import net.minecraft.world.entity.ai.goal.EatBlockGoal; import net.minecraft.world.entity.ai.goal.FloatGoal; import net.minecraft.world.entity.ai.goal.FollowFlockLeaderGoal; import net.minecraft.world.entity.ai.goal.FollowParentGoal; import net.minecraft.world.entity.ai.goal.LookAtPlayerGoal; import net.minecraft.world.entity.ai.goal.PanicGoal; import net.minecraft.world.entity.ai.goal.RandomLookAroundGoal; import net.minecraft.world.entity.ai.goal.RandomSwimmingGoal; import net.minecraft.world.entity.ai.goal.TemptGoal; import net.minecraft.world.entity.ai.goal.WaterAvoidingRandomStrollGoal; import net.minecraft.world.entity.animal.AbstractFish; import net.minecraft.world.entity.animal.Chicken; import net.minecraft.world.entity.animal.Cow; import net.minecraft.world.entity.animal.Pig; import net.minecraft.world.entity.animal.Pufferfish; import net.minecraft.world.entity.animal.Sheep; import net.minecraft.world.entity.animal.Squid; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; /** * Created by Dark(DarkGuardsman, Robert) on 8/3/2019. */ @Mod.EventBusSubscriber(modid = AIImprovements.DOMAIN) public class ModifierSystem { public static final FilterLayer editor = new FilterLayer(null); public static final ModifierLevel mobEntityEditor = ModifierLevel.newFilter(entity -> entity instanceof Mob); public static final ModifierLevel fishEditor = ModifierLevel.newFilter(entity -> entity instanceof AbstractFish); public static final ModifierLevel squidEditor = ModifierLevel.newFilter(entity -> entity instanceof Squid); public static final ModifierLevel cowEditor = ModifierLevel.newFilter(entity -> entity instanceof Cow); public static final ModifierLevel chickenEditor = ModifierLevel.newFilter(entity -> entity instanceof Chicken); public static final ModifierLevel pigEditor = ModifierLevel.newFilter(entity -> entity instanceof Pig); public static final ModifierLevel sheepEditor = ModifierLevel.newFilter(entity -> entity instanceof Sheep); @SubscribeEvent public static void onEntityJoinWorld(EntityJoinWorldEvent event) { editor.handle(event.getEntity()); } public static void init() { editor.add(mobEntityEditor); //Generic remove calls mobEntityEditor.goalEditor.add(new FilteredRemove(goal -> goal instanceof LookAtPlayerGoal, ConfigMain.CONFIG.removeLookGoal)); mobEntityEditor.goalEditor.add(new FilteredRemove(goal -> goal instanceof RandomLookAroundGoal, ConfigMain.CONFIG.removeLookRandom)); mobEntityEditor.filters.add(entity -> replaceLookHelper((Mob) entity)); //Fish remove calls mobEntityEditor.filters.add(fishEditor); fishEditor.goalEditor.add(new GenericRemove(goal -> goal instanceof RandomSwimmingGoal, ConfigMain.CONFIG.removeFishSwim)); fishEditor.goalEditor.add(new GenericRemove(goal -> goal instanceof AvoidEntityGoal, ConfigMain.CONFIG.removeFishAvoidPlayer)); fishEditor.goalEditor.add(new GenericRemove(goal -> goal instanceof PanicGoal, ConfigMain.CONFIG.removeFishPanic)); fishEditor.goalEditor.add(new GenericRemove(goal -> goal instanceof FollowFlockLeaderGoal, ConfigMain.CONFIG.removeFishFollowLeader)); fishEditor.goalEditor.add(new GenericRemove(goal -> goal instanceof Pufferfish.PufferfishPuffGoal, ConfigMain.CONFIG.removeFishFollowLeader)); //Squid mobEntityEditor.filters.add(squidEditor); squidEditor.goalEditor.add(new GenericRemove(goal -> goal instanceof Squid.SquidRandomMovementGoal, ConfigMain.CONFIG.removeRandomMove)); squidEditor.goalEditor.add(new GenericRemove(goal -> goal instanceof Squid.SquidFleeGoal, ConfigMain.CONFIG.removeRandomMove)); //Cow mobEntityEditor.filters.add(cowEditor); populateAnimalEditor(cowEditor, ConfigMain.CONFIG.cow); //Chicken mobEntityEditor.filters.add(chickenEditor); populateAnimalEditor(chickenEditor, ConfigMain.CONFIG.chicken); //Pig mobEntityEditor.filters.add(pigEditor); populateAnimalEditor(pigEditor, ConfigMain.CONFIG.pig); //Sheep mobEntityEditor.filters.add(sheepEditor); populateAnimalEditor(sheepEditor, ConfigMain.CONFIG.sheep); sheepEditor.goalEditor.add(new GenericRemove(goal -> goal instanceof EatBlockGoal, ConfigMain.CONFIG.removeSheepEatBlock)); } private static FilterResult replaceLookHelper(Mob living) { FilteredConfigValue replaceLookController = ConfigMain.CONFIG.replaceLookController; //Only replace vanilla look helper to avoid overlapping mods if (replaceLookController.configValue().get() && (living.getLookControl() == null || living.getLookControl().getClass() == LookControl.class)) { //if it's an allowlist, mobs on the filter list have their look helper replaced //if it's not an allowlist (denylist), the mobs NOT on the filter list have their look helper replaced if (replaceLookController.isFiltered(living.getType().getRegistryName().toString())) return FilterResult.DID_NOTHING; //Get old so we can copy data final LookControl oldHelper = living.getLookControl(); //Set new living.lookControl = new FixedLookControl(living); //Instance of check may look unneeded but some mods do stupid things if (living.getLookControl() instanceof FixedLookControl flc) { flc.copyDataIntoSelf(oldHelper); return FilterResult.MODIFIED; } else { //TODO error/warning in console, then mark this entity as unusable for future checks } } return FilterResult.DID_NOTHING; } private static void populateAnimalEditor(ModifierLevel animalEditor, AnimalConfigSection configs) { animalEditor.goalEditor.add(new GenericRemove(goal -> goal instanceof FloatGoal, configs.removeFloat())); animalEditor.goalEditor.add(new GenericRemove(goal -> goal instanceof PanicGoal, configs.removePanic())); animalEditor.goalEditor.add(new GenericRemove(goal -> goal instanceof BreedGoal, configs.removeBreed())); animalEditor.goalEditor.add(new GenericRemove(goal -> goal instanceof TemptGoal, configs.removeTempt())); animalEditor.goalEditor.add(new GenericRemove(goal -> goal instanceof FollowParentGoal, configs.removeFollowParent())); animalEditor.goalEditor.add(new GenericRemove(goal -> goal instanceof WaterAvoidingRandomStrollGoal, configs.removeStroll())); } }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\modifier\editor\ConfigDrivenEdit.java
package com.builtbroken.ai.improvements.modifier.editor; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraftforge.common.ForgeConfigSpec.BooleanValue; /** * Created by Dark(DarkGuardsman, Robert) on 8/3/2019. */ public class ConfigDrivenEdit implements IEntityAiModifier { private final BooleanValue configCheck; private final IEntityAiModifier modifier; public ConfigDrivenEdit(BooleanValue configCheck, IEntityAiModifier modifier) { this.configCheck = configCheck; this.modifier = modifier; } @Override public Goal handle(Mob entity, Goal aiTask) { return configCheck.get() ? modifier.handle(entity, aiTask) : aiTask; } }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\modifier\editor\FilteredRemove.java
package com.builtbroken.ai.improvements.modifier.editor; import com.builtbroken.ai.improvements.ConfigMain; import com.builtbroken.ai.improvements.ConfigMain.FilteredConfigValue; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.goal.Goal; public class FilteredRemove implements IEntityAiModifier { private final InstanceCheck instanceCheck; private final FilteredConfigValue filteredConfigValue; public FilteredRemove(InstanceCheck instanceCheck, FilteredConfigValue filteredConfigValue) { this.instanceCheck = instanceCheck; this.filteredConfigValue = filteredConfigValue; } @Override public Goal handle(Mob entity, Goal aiTask) { if (ConfigMain.CONFIG.allowRemoveCalls.get() && instanceCheck.isGoal(aiTask)) { //if it's an allowlist, mobs on the filter list should be handled //if it's not an allowlist (denylist), the mobs NOT on the filter should be handled if (!filteredConfigValue.isFiltered(entity.getType().getRegistryName().toString()) && filteredConfigValue.configValue().get()) { return null; } } return aiTask; } }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\modifier\editor\GenericRemove.java
package com.builtbroken.ai.improvements.modifier.editor; import com.builtbroken.ai.improvements.ConfigMain; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraftforge.common.ForgeConfigSpec.BooleanValue; /** * Created by Dark(DarkGuardsman, Robert) on 8/3/2019. */ public class GenericRemove implements IEntityAiModifier { private final InstanceCheck instanceCheck; private final BooleanValue configCheck; public GenericRemove(InstanceCheck instanceCheck, BooleanValue configCheck) { this.instanceCheck = instanceCheck; this.configCheck = configCheck; } @Override public Goal handle(Mob entity, Goal aiTask) { return ConfigMain.CONFIG.allowRemoveCalls.get() && instanceCheck.isGoal(aiTask) && configCheck.get() ? null : aiTask; } }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\modifier\editor\IEntityAiModifier.java
package com.builtbroken.ai.improvements.modifier.editor; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.goal.Goal; /** * Created by Dark(DarkGuardsman, Robert) on 8/2/2019. */ @FunctionalInterface public interface IEntityAiModifier { /** * Called to modify an entity's AI task * * @param entity - entity being modified * @return null to remove, same to skip, new to replace */ Goal handle(Mob entity, Goal aiTask); }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\modifier\editor\InstanceCheck.java
package com.builtbroken.ai.improvements.modifier.editor; import net.minecraft.world.entity.ai.goal.Goal; /** * Created by Dark(DarkGuardsman, Robert) on 8/3/2019. */ @FunctionalInterface public interface InstanceCheck { boolean isGoal(Goal goal); }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\modifier\editor\ModifierLayer.java
package com.builtbroken.ai.improvements.modifier.editor; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.Set; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.ai.goal.GoalSelector; import net.minecraft.world.entity.ai.goal.WrappedGoal; /** * Created by Dark(DarkGuardsman, Robert) on 8/2/2019. */ public class ModifierLayer { private ModifierNode[] nodes = new ModifierNode[5]; private int size = 0; private boolean resortNormalize = false; public final boolean combatAI; public ModifierLayer(boolean combatAI) { this.combatAI = combatAI; } public void add(IEntityAiModifier modifier) { if (modifier != null) { if (size == nodes.length) { nodes = Arrays.copyOf(nodes, nodes.length + 5); } nodes[size++] = new ModifierNode(modifier); } } public void handle(Mob entity) { final GoalSelector goalSelector = combatAI ? entity.targetSelector : entity.goalSelector; final Set<Goal> goalsToRemove = new HashSet<>(); for (WrappedGoal prioritizedGoal : goalSelector.availableGoals) { final Goal reGoal = process(entity, prioritizedGoal.getGoal()); //Queue removal if (reGoal == null) { goalsToRemove.add(prioritizedGoal.getGoal()); } //TODO handle modified goals } //Do remove for (Goal goal : goalsToRemove) { goalSelector.removeGoal(goal); } //Sorta data and normal if (resortNormalize) { resortNormalize = false; resort(true); } } protected Goal process(Mob entity, Goal goal) { for (int i = 0; i < nodes.length; i++) { final ModifierNode modifier = nodes[i]; if (modifier != null) { final Goal reGoal = modifier.handle(entity, goal); //Trigger sorting if (reGoal != goal && i != 0 && modifier.callCount > nodes[i - 1].callCount) { bubble(modifier, i); } //Return if we changed the goal if (reGoal != goal) { return reGoal; } } } return goal; } protected void resort(boolean normalize) { Arrays.sort(nodes, Comparator.comparingInt(m -> m.callCount)); if (normalize) { final int sum = Arrays.stream(nodes).mapToInt(m -> m.callCount).sum(); Arrays.stream(nodes).forEach(m -> m.callCount = (int) Math.floor(m.callCount / (double) sum)); } } protected void bubble(ModifierNode modifier, int i) { //increase call count modifier.callCount += 1; //Resort and clear if (modifier.callCount >= (Integer.MAX_VALUE / 2)) { resortNormalize = true; } else { final ModifierNode m = nodes[i]; //Move down nodes[i] = nodes[i - 1]; //Move up nodes[i - 1] = m; } } }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\modifier\editor\ModifierNode.java
package com.builtbroken.ai.improvements.modifier.editor; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.goal.Goal; /** * Created by Dark(DarkGuardsman, Robert) on 8/3/2019. */ public class ModifierNode implements IEntityAiModifier { protected int callCount = 0; private final IEntityAiModifier action; public ModifierNode(IEntityAiModifier action) { this.action = action; } @Override public Goal handle(Mob entity, Goal aiTask) { return action.handle(entity, aiTask); } }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\modifier\filters\FilterLayer.java
package com.builtbroken.ai.improvements.modifier.filters; import java.util.Arrays; import java.util.Comparator; import net.minecraft.world.entity.Entity; /** * Created by Dark(DarkGuardsman, Robert) on 8/2/2019. */ public class FilterLayer extends FilterNode { private FilterNode[] nodes = new FilterNode[5]; private int size = 0; public FilterLayer(IFilterNode filter) { super(filter); } public void add(IFilterNode modifier) { if (modifier == null) { modifier = NoopNode.INSTANCE; } if (size == nodes.length) { nodes = Arrays.copyOf(nodes, nodes.length + 5); } nodes[size++] = new FilterNode(modifier); } @Override public FilterResult handle(Entity entity) { FilterResult filterResult = action != null ? action.handle(entity) : FilterResult.FILTERED; if (filterResult != FilterResult.DID_NOTHING && nodes != null) { //just to be safe for (int i = 0; i < nodes.length; i++) { if(nodes[i] == null) nodes[i] = NoopNode.INSTANCE; } for (int i = 0; i < nodes.length; i++) { final FilterNode modifier = nodes[i]; filterResult = modifier.handle(entity); if (filterResult == FilterResult.FILTERED) { //increase call count modifier.callCount += 1; //Resort and clear if (modifier.callCount >= (Integer.MAX_VALUE / 2)) { Arrays.sort(nodes, Comparator.comparingInt(m -> m.callCount)); final int sum = Arrays.stream(nodes).mapToInt(m -> m.callCount).sum(); Arrays.stream(nodes).forEach(m -> m.callCount = (int) Math.floor(m.callCount / (double) sum)); } else if (i != 0 && modifier.callCount > nodes[i - 1].callCount) { final FilterNode m = nodes[i]; //Move down nodes[i] = nodes[i - 1]; //Move up nodes[i - 1] = m; } return filterResult; } } } return filterResult; } }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\modifier\filters\FilterNode.java
package com.builtbroken.ai.improvements.modifier.filters; import net.minecraft.world.entity.Entity; /** * Created by Dark(DarkGuardsman, Robert) on 8/2/2019. */ public class FilterNode implements IFilterNode { protected int callCount = 0; protected final IFilterNode action; protected FilterNode(IFilterNode action) { this.action = action; } @Override public FilterResult handle(Entity entity) { return action.handle(entity); } }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\modifier\filters\FilterResult.java
package com.builtbroken.ai.improvements.modifier.filters; /** * Created by Dark(DarkGuardsman, Robert) on 8/3/2019. */ public enum FilterResult { /** Nothing happened, continue to next call */ DID_NOTHING, /** Passed the entity down a layer, should not continue to next call */ FILTERED, /** Changed the Entity but should still continue to pass through */ MODIFIED }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\modifier\filters\IFilterNode.java
package com.builtbroken.ai.improvements.modifier.filters; import net.minecraft.world.entity.Entity; /** * Created by Dark(DarkGuardsman, Robert) on 8/2/2019. */ @FunctionalInterface public interface IFilterNode { /** * Called to consume an entity * * @param entity - entity being modified * @return true to consume, false to move on */ FilterResult handle(Entity entity); }
AI-Improvements
src\main\java\com\builtbroken\ai\improvements\modifier\filters\NoopNode.java
package com.builtbroken.ai.improvements.modifier.filters; import net.minecraft.world.entity.Entity; public final class NoopNode extends FilterNode { public static final NoopNode INSTANCE = new NoopNode(null); private NoopNode(IFilterNode action) { super(action); } @Override public FilterResult handle(Entity entity) { return FilterResult.DID_NOTHING; } }
AI-Improvements
src\tools\java\com\builtbroken\tools\MainPerformanceTest.java
package com.builtbroken.tools; import com.builtbroken.ai.improvements.FastTrig; import com.builtbroken.ai.improvements.FixedEntityLookHelper; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.ai.EntityLookHelper; import net.minecraft.entity.monster.EntityZombie; import java.util.Random; /** * @see <a href="https://github.com/BuiltBrokenModding/VoltzEngine/blob/development/license.md">License</a> for what you can and can't do with the code. * Created by Dark(DarkGuardsman, Robert) on 7/12/2017. */ public class MainPerformanceTest { public static void main(String... args) { EntityLiving living = new EntityZombie(null); EntityLookHelper mcHelper = new EntityLookHelper(living); EntityLookHelper helper = new FixedEntityLookHelper(living); Random random = new Random(); FastTrig.init(); //load the cache for (int i = 0; i < 100000; i++) { mcHelper.isLooking = true; helper.isLooking = true; int x = random.nextInt(10) - random.nextInt(10); int y = random.nextInt(2) - random.nextInt(2); int z = random.nextInt(10) - random.nextInt(10); mcHelper.posX = x; mcHelper.posY = y; mcHelper.posZ = z; helper.posX = x; helper.posY = y; helper.posZ = z; System.out.println("[" + i + "]--------------------------------------"); long start = System.nanoTime(); mcHelper.onUpdateLook(); start = System.nanoTime() - start; System.out.println("MC: " + start); start = System.nanoTime(); helper.onUpdateLook(); start = System.nanoTime() - start; System.out.println("BBM: " + start); } } }
Alfheim
src\main\resources\mixins.alfheim.json
{ "required": true, "minVersion": "0.8", "package": "dev.redstudio.${id}.mixin", "compatibilityLevel": "JAVA_8", "refmap": "mixins.${id}.refmap.json", "injectors": { "defaultRequire": 1 }, "client": [ "client.BlockModelRendererMixin", "client.MinecraftMixin", "client.RenderGlobalMixin" ], "mixins": [ "AnvilChunkLoaderMixin", "BlockMixin", "BlockSlabMixin", "BlockStairsMixin", "BlockStateContainerMixin", "BlockStateContainerMixin$StateImplementationMixin", "ChunkCacheMixin", "ChunkMixin", "ChunkProviderServerMixin", "ExtendedBlockStorageMixin", "SPacketChunkDataMixin", "WorldMixin" ] }
Alfheim
src\main\java\dev\redstudio\alfheim\Alfheim.java
package dev.redstudio.alfheim; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import static dev.redstudio.alfheim.ProjectConstants.ID; import static dev.redstudio.alfheim.ProjectConstants.VERSION; // /$$$$$$ /$$ /$$$$$$ /$$ /$$ // /$$__ $$| $$ /$$__ $$| $$ |__/ // | $$ \ $$| $$| $$ \__/| $$$$$$$ /$$$$$$ /$$ /$$$$$$/$$$$ // | $$$$$$$$| $$| $$$$ | $$__ $$ /$$__ $$| $$| $$_ $$_ $$ // | $$__ $$| $$| $$_/ | $$ \ $$| $$$$$$$$| $$| $$ \ $$ \ $$ // | $$ | $$| $$| $$ | $$ | $$| $$_____/| $$| $$ | $$ | $$ // | $$ | $$| $$| $$ | $$ | $$| $$$$$$$| $$| $$ | $$ | $$ // |__/ |__/|__/|__/ |__/ |__/ \_______/|__/|__/ |__/ |__/ /// The main class of Alfheim. /// /// This class mainly contains constants and metadata. /// /// @author Luna Mira Lage (Desoroxxx) /// @since 1.0 @Mod(modid = ID, version = VERSION, updateJSON = "https://forge.curseupdate.com/910715/" + ID, useMetadata = true, dependencies = "required-after:mixinbooter@[10.6,);required-after:redcore@[0.6,);") public final class Alfheim { // TODO: Separate bugfixes and lighting engine /// `2 light types * 4 directions * 2 halves * (inwards + outwards)` public static final byte FLAG_COUNT = 32; public static final boolean IS_DYNAMIC_LIGHTS_LOADED = Loader.isModLoaded("dynamiclights"); public static final boolean IS_NOTHIRIUM_LOADED = Loader.isModLoaded("nothirium"); public static final boolean IS_VINTAGIUM_LOADED = Loader.isModLoaded("vintagium"); public static final boolean IS_CELERITAS_LOADED = Loader.isModLoaded("celeritas"); }
Alfheim
src\main\java\dev\redstudio\alfheim\api\IChunkLightingData.java
package dev.redstudio.alfheim.api; import net.minecraft.util.math.BlockPos; import net.minecraft.world.EnumSkyBlock; /// @author Luna Mira Lage (Desoroxxx) /// @author Angeline (@jellysquid) /// @since 1.0 public interface IChunkLightingData { short[] alfheim$getNeighborLightChecks(); void alfheim$setNeighborLightChecks(final short[] data); boolean alfheim$isLightInitialized(); void alfheim$setLightInitialized(final boolean lightInitialized); void alfheim$setSkylightUpdatedPublic(); void alfheim$initNeighborLightChecks(); byte alfheim$getCachedLightFor(final EnumSkyBlock enumSkyBlock, final BlockPos pos); }
Alfheim
src\main\java\dev\redstudio\alfheim\api\ILightInfoProvider.java
package dev.redstudio.alfheim.api; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.IBlockAccess; /// @author Luna Mira Lage (Desoroxxx) /// @since 1.0 public interface ILightInfoProvider { int alfheim$getLightFor(final IBlockAccess iBlockAccess, final EnumSkyBlock lightType, final BlockPos blockPos); boolean alfheim$useNeighborBrightness(final EnumFacing facing, final IBlockAccess blockAccess, final BlockPos blockPos); int alfheim$getLightOpacity(final EnumFacing facing, final IBlockAccess blockAccess, final BlockPos blockPos); }
Alfheim
src\main\java\dev\redstudio\alfheim\api\ILightingEngineProvider.java
package dev.redstudio.alfheim.api; import dev.redstudio.alfheim.lighting.LightingEngine; /// @author Luna Mira Lage (Desoroxxx) /// @author Angeline (@jellysquid) /// @since 1.0 public interface ILightingEngineProvider { LightingEngine getAlfheim$lightingEngine(); }
Alfheim
src\main\java\dev\redstudio\alfheim\api\ILightLevelProvider.java
package dev.redstudio.alfheim.api; import net.minecraft.util.math.BlockPos; import net.minecraft.world.EnumSkyBlock; /// @author Luna Mira Lage (Desoroxxx) /// @since 1.0 public interface ILightLevelProvider { int alfheim$getLight(final EnumSkyBlock lightType, final BlockPos blockPos); }
Alfheim
src\main\java\dev\redstudio\alfheim\api\ILightUpdatesProcessor.java
package dev.redstudio.alfheim.api; /// @author Luna Mira Lage (Desoroxxx) /// @since 1.0 public interface ILightUpdatesProcessor { void alfheim$processLightUpdates(); }
Alfheim
src\main\java\dev\redstudio\alfheim\api\ILitBlock.java
package dev.redstudio.alfheim.api; import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.IBlockAccess; /// @author Luna Mira Lage (Desoroxxx) /// @since 1.0 public interface ILitBlock { int alfheim$getLightFor(final IBlockState blockState, final IBlockAccess blockAccess, final EnumSkyBlock lightType, final BlockPos blockPos); boolean alfheim$useNeighborBrightness(final IBlockState blockState, final EnumFacing facing, final IBlockAccess blockAccess, final BlockPos blockPos); int alfheim$getLightOpacity(final IBlockState blockState, final EnumFacing facing, final IBlockAccess blockAccess, final BlockPos blockPos); }
Alfheim
src\main\java\dev\redstudio\alfheim\asm\AlfheimPlugin.java
package dev.redstudio.alfheim.asm; import com.google.common.collect.ImmutableList; import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin; import zone.rong.mixinbooter.Context; import zone.rong.mixinbooter.IEarlyMixinLoader; import zone.rong.mixinbooter.IMixinConfigHijacker; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import static dev.redstudio.alfheim.ProjectConstants.*; /// @author Luna Mira Lage (Desoroxxx) /// @since 1.0 @IFMLLoadingPlugin.MCVersion("1.12.2") @IFMLLoadingPlugin.TransformerExclusions("dev.redstudio." + ID + ".asm") public final class AlfheimPlugin implements IFMLLoadingPlugin, IEarlyMixinLoader, IMixinConfigHijacker { @Override public String[] getASMTransformerClass() { return null; } @Override public String getModContainerClass() { return null; } @Override public String getSetupClass() { return null; } @Override public void injectData(final Map<String, Object> data) { } @Override public String getAccessTransformerClass() { return null; } @Override public List<String> getMixinConfigs() { return ImmutableList.of("mixins." + ID + ".json"); } @Override public boolean shouldMixinConfigQueue(final String mixinConfig) { switch (mixinConfig) { case "mixins." + ID + ".json": return !isCubicChunksInstalled(); default: return true; } } /// Checks if Cubic Chunks is installed. /// /// @return True if Cubic Chunks is installed, false otherwise. public static boolean isCubicChunksInstalled() { try { Class.forName("io.github.opencubicchunks.cubicchunks.core.asm.CubicChunksCoreContainer"); } catch (final ClassNotFoundException ignored) { return false; } LOGGER.warn("Cubic Chunks was detected, it uses it's own lighting engine, {} will not load", NAME); return true; } @Override public Set<String> getHijackedMixinConfigs() { return Collections.singleton("mixins.phosphor.json"); } @Override public Set<String> getHijackedMixinConfigs(final Context context) { if (!context.isModPresent("phosphor-lighting")) { return Collections.emptySet(); } LOGGER.warn("Phosphor/Hesperus was detected, {} replaces them entirely, will now attempt hijacking, you should remove Phosphor/Hesperus", NAME); return getHijackedMixinConfigs(); } }
Alfheim
src\main\java\dev\redstudio\alfheim\lighting\LightingEngine.java
package dev.redstudio.alfheim.lighting; import dev.redstudio.alfheim.api.IChunkLightingData; import dev.redstudio.alfheim.utils.DeduplicatedLongQueue; import dev.redstudio.redcore.math.ClampUtil; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.profiler.Profiler; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos.MutableBlockPos; import net.minecraft.util.math.Vec3i; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.concurrent.locks.ReentrantLock; import static dev.redstudio.alfheim.ProjectConstants.LOGGER; import static dev.redstudio.alfheim.ProjectConstants.NAME; /// @author Luna Mira Lage (Desoroxxx) /// @author kappa-maintainer /// @author embeddedt /// @author Angeline (@jellysquid) /// @since 1.0 public final class LightingEngine { private static final byte MAX_LIGHT_LEVEL = 15; private final Thread ownerThread = Thread.currentThread(); private final World world; private final Profiler profiler; // Layout of longs: [padding(4)] [y(8)] [x(26)] [z(26)] private final DeduplicatedLongQueue[] lightUpdateQueues = new DeduplicatedLongQueue[EnumSkyBlock.values().length]; // Layout of longs: see above private final DeduplicatedLongQueue[] darkeningQueues = new DeduplicatedLongQueue[MAX_LIGHT_LEVEL + 1]; private final DeduplicatedLongQueue[] brighteningQueues = new DeduplicatedLongQueue[MAX_LIGHT_LEVEL + 1]; // Layout of longs: [newLight(4)] [pos(60)] private final DeduplicatedLongQueue initialBrightenings; // Layout of longs: [padding(4)] [pos(60)] private final DeduplicatedLongQueue initialDarkenings; private boolean updating = false; // Layout parameters // Length of bit segments private static final int L_X = 26, L_Y = 8, L_Z = 26, L_L = 4; // Bit segment shifts/positions private static final int S_Z = 0, S_X = S_Z + L_Z, S_Y = S_X + L_X, S_L = S_Y + L_Y; // Bit segment masks private static final long M_X = (1L << L_X) - 1, M_Y = (1L << L_Y) - 1, M_Z = (1L << L_Z) - 1, M_L = (1L << L_L) - 1, M_POS = (M_Y << S_Y) | (M_X << S_X) | (M_Z << S_Z); // Bit to check whether y had overflow private static final long Y_CHECK = 1L << (S_Y + L_Y); private static final long[] neighborShifts = new long[6]; static { for (byte i = 0; i < 6; ++i) { final Vec3i offset = EnumFacing.VALUES[i].getDirectionVec(); neighborShifts[i] = ((long) offset.getY() << S_Y) | ((long) offset.getX() << S_X) | ((long) offset.getZ() << S_Z); } } // Mask to extract chunk identifier private static final long M_CHUNK = ((M_X >> 4) << (4 + S_X)) | ((M_Z >> 4) << (4 + S_Z)); // Iteration state data // Cache position to avoid allocation of new object each time private final MutableBlockPos currentPos = new MutableBlockPos(); private Chunk currentChunk; private long currentChunkIdentifier; private long currentData; // Cached data about neighboring blocks (of tempPos) private boolean isNeighborDataValid = false; private final NeighborInfo[] neighborInfos = new NeighborInfo[6]; private DeduplicatedLongQueue currentQueue; private final ReentrantLock lock = new ReentrantLock(); public LightingEngine(final World world) { this.world = world; profiler = world.profiler; initialBrightenings = new DeduplicatedLongQueue(16384); initialDarkenings = new DeduplicatedLongQueue(16384); for (int i = 0; i < EnumSkyBlock.values().length; ++i) lightUpdateQueues[i] = new DeduplicatedLongQueue(16384); for (int i = 0; i < darkeningQueues.length; ++i) darkeningQueues[i] = new DeduplicatedLongQueue(16384); for (int i = 0; i < brighteningQueues.length; ++i) brighteningQueues[i] = new DeduplicatedLongQueue(16384); for (int i = 0; i < neighborInfos.length; ++i) neighborInfos[i] = new NeighborInfo(); } /// Schedules a light update for the specified light type and position to be processed later by [#processLightUpdatesForType(EnumSkyBlock)] public void scheduleLightUpdate(final EnumSkyBlock lightType, final BlockPos pos) { lock(); try { scheduleLightUpdate(lightType, encodeWorldCoord(pos)); } finally { lock.unlock(); } } /// Schedules a light update for the specified light type and position to be processed later by [#processLightUpdates()] private void scheduleLightUpdate(final EnumSkyBlock lightType, final long blockPos) { lightUpdateQueues[lightType.ordinal()].enqueue(blockPos); } /// Calls [#processLightUpdatesForType(EnumSkyBlock)] for both light types public void processLightUpdates() { profiler.startSection("processSky"); processLightUpdatesForType(EnumSkyBlock.SKY); profiler.endStartSection("processBlock"); processLightUpdatesForType(EnumSkyBlock.BLOCK); profiler.endSection(); } /// Processes light updates of the given light type public void processLightUpdatesForType(final EnumSkyBlock lightType) { // We only want to perform updates if we're being called from a tick event on the client. // There are many locations in the client code that will end up making calls to this method, usually from other threads. if (world.isRemote && !isCallingFromMainThread()) return; final DeduplicatedLongQueue queue = lightUpdateQueues[lightType.ordinal()]; // Quickly check if the queue is empty before we acquire a more expensive lock. if (queue.isEmpty()) return; profiler.startSection("process"); lock(); try { processLightUpdatesForTypeInner(lightType, queue); } finally { lock.unlock(); } profiler.endSection(); } @SideOnly(Side.CLIENT) private boolean isCallingFromMainThread() { return Minecraft.getMinecraft().isCallingFromMinecraftThread(); } private void lock() { if (lock.tryLock()) return; // If we cannot lock, something has gone wrong... Only one thread should ever acquire the lock. // Validate that we're on the right thread immediately, so we can gather information. // It is NEVER valid to call World methods from a thread other than the owning thread of the world instance. final Thread current = Thread.currentThread(); if (current != ownerThread) { final IllegalAccessException illegalAccessException = new IllegalAccessException(String.format("World is owned by '%s' (ID: %s)," + " but was accessed from thread '%s' (ID: %s)", ownerThread.getName(), ownerThread.getId(), current.getName(), current.getId())); LOGGER.warn( "Something (likely another mod) has attempted to modify the world's state from the wrong thread!\n" + "This is *bad practice* and can cause severe issues in your game.\n" + NAME + " has done as best as it can to mitigate this violation, but it may negatively impact performance or introduce stalls.\n" + "In a future release, this violation may result in a hard crash instead of the current soft warning.\n" , illegalAccessException); } // Wait for the lock to be released. This will likely introduce unwanted stalls, but will mitigate the issue. lock.lock(); } private void processLightUpdatesForTypeInner(final EnumSkyBlock lightType, final DeduplicatedLongQueue queue) { // Avoid nested calls if (updating) throw new IllegalStateException("Already processing updates!"); updating = true; currentChunkIdentifier = -1; // Reset chunk cache currentQueue = queue; if (currentQueue != null) currentQueue.newDeduplicationSet(); profiler.startSection("prepare"); // Process the queued updates and enqueue them for further processing while (nextItem()) { if (currentChunk == null) continue; final byte oldLight = getCursorCachedLight(lightType); final byte newLight = calculateNewLightFromCursor(lightType); if (oldLight < newLight) { initialBrightenings.enqueue(((long) newLight << S_L) | currentData); // Don't enqueue directly for brightening to avoid duplicate scheduling } else if (oldLight > newLight) { initialDarkenings.enqueue(currentData); // Don't enqueue directly for darkening to avoid duplicate scheduling } } profiler.endStartSection("enqueueBrightening"); currentQueue = initialBrightenings; if (currentQueue != null) currentQueue.newDeduplicationSet(); while (nextItem()) { final byte newLight = (byte) (currentData >> S_L & M_L); if (newLight > getCursorCachedLight(lightType)) enqueueBrightening(currentPos, currentData & M_POS, newLight, currentChunk, lightType); // Sets the light to newLight to only schedule once. Clear leading bits of curData for later } profiler.endStartSection("enqueueDarkening"); currentQueue = initialDarkenings; if (currentQueue != null) currentQueue.newDeduplicationSet(); while (nextItem()) { final byte oldLight = getCursorCachedLight(lightType); if (oldLight != 0) enqueueDarkening(currentPos, currentData, oldLight, currentChunk, lightType); // Sets the light to zero to only schedule once } profiler.endStartSection("process"); // Iterate through enqueued updates (brightening and darkening in parallel) from brightest to darkest so that we only need to iterate once for (byte currentLight = MAX_LIGHT_LEVEL; currentLight >= 0; --currentLight) { currentQueue = darkeningQueues[currentLight]; if (currentQueue != null) currentQueue.newDeduplicationSet(); while (nextItem()) { // Don't darken if we got brighter due to some other change if (getCursorCachedLight(lightType) >= currentLight) continue; final IBlockState blockState = currentChunk.getBlockState(currentPos); final byte luminosity = getCursorLuminosity(blockState, lightType); final byte opacity; // If luminosity is high enough, opacity is irrelevant if (luminosity >= MAX_LIGHT_LEVEL - 1) { opacity = 1; } else { opacity = getPosOpacity(currentPos, blockState); } // Only darken neighbors if we indeed became darker if (calculateNewLightFromCursor(luminosity, opacity, lightType) < currentLight) { // Need to calculate new light value from neighbors IGNORING neighbors which are scheduled for darkening byte newLight = luminosity; fetchNeighborDataFromCursor(lightType); for (final NeighborInfo neighborInfo : neighborInfos) { final Chunk neighborChunk = neighborInfo.chunk; if (neighborChunk == null) continue; final byte neighborLight = neighborInfo.light; if (neighborLight == 0) continue; final MutableBlockPos neighborPos = neighborInfo.mutableBlockPos; if (currentLight - getPosOpacity(neighborPos, neighborChunk.getBlockState(neighborPos)) >= neighborLight) /*Schedule neighbor for darkening if we possibly light it*/ { enqueueDarkening(neighborPos, neighborInfo.key, neighborLight, neighborChunk, lightType); } else /*Only use for new light calculation if not*/ { // If we can't darken the neighbor, no one else can (because of processing order) -> safe to let us be illuminated by it newLight = (byte) Math.max(newLight, neighborLight - opacity); } } // Schedule brightening since light level was set to 0 enqueueBrighteningFromCursor(newLight, lightType); } else /*We didn't become darker, so we need to re-set our initial light value (was set to zero) and notify neighbors*/ { enqueueBrighteningFromCursor(currentLight, lightType); // Do not spread to neighbors immediately to avoid scheduling multiple times } } currentQueue = brighteningQueues[currentLight]; if (currentQueue != null) currentQueue.newDeduplicationSet(); while (nextItem()) { final byte oldLight = getCursorCachedLight(lightType); // Only process this if nothing else has happened at this position since scheduling if (oldLight == currentLight) { world.notifyLightSet(currentPos); if (currentLight > 1) spreadLightFromCursor(currentLight, lightType); } } } profiler.endSection(); updating = false; } /// Gets data for neighbors of [#currentPos] and saves the results into neighbor state data members. /// If a neighbor can't be accessed/doesn't exist, the corresponding entry in neighborChunks is null - others are not reset private void fetchNeighborDataFromCursor(final EnumSkyBlock lightType) { // Only update if curPos was changed if (isNeighborDataValid) return; isNeighborDataValid = true; for (int i = 0; i < neighborInfos.length; ++i) { final NeighborInfo neighborInfo = neighborInfos[i]; final long neighborLongPos = neighborInfo.key = currentData + neighborShifts[i]; if ((neighborLongPos & Y_CHECK) != 0) { neighborInfo.chunk = null; continue; } final MutableBlockPos neighborPos = decodeWorldCoord(neighborInfo.mutableBlockPos, neighborLongPos); final Chunk neighborChunk; if ((neighborLongPos & M_CHUNK) == currentChunkIdentifier) { neighborChunk = neighborInfo.chunk = currentChunk; } else { neighborChunk = neighborInfo.chunk = getChunk(neighborPos); } if (neighborChunk != null) { final ExtendedBlockStorage neighborSection = neighborChunk.getBlockStorageArray()[neighborPos.getY() >> 4]; neighborInfo.light = getCachedLightFor(neighborChunk, neighborSection, neighborPos, lightType); } } } private static byte getCachedLightFor(final Chunk chunk, final ExtendedBlockStorage storage, final BlockPos blockPos, final EnumSkyBlock type) { final int x = blockPos.getX() & 15; final int y = blockPos.getY(); final int z = blockPos.getZ() & 15; if (storage == Chunk.NULL_BLOCK_STORAGE) { return type == EnumSkyBlock.SKY && chunk.canSeeSky(blockPos) ? (byte) type.defaultLightValue : 0; } else if (type == EnumSkyBlock.SKY) { return chunk.getWorld().provider.hasSkyLight() ? (byte) storage.getSkyLight(x, y & 15, z) : 0; } else { return type == EnumSkyBlock.BLOCK ? (byte) storage.getBlockLight(x, y & 15, z) : (byte) type.defaultLightValue; } } private byte calculateNewLightFromCursor(final EnumSkyBlock lightType) { final IBlockState blockState = currentChunk.getBlockState(currentPos); final byte luminosity = getCursorLuminosity(blockState, lightType); final byte opacity; if (luminosity >= MAX_LIGHT_LEVEL - 1) { opacity = 1; } else { opacity = getPosOpacity(currentPos, blockState); } return calculateNewLightFromCursor(luminosity, opacity, lightType); } private byte calculateNewLightFromCursor(final byte luminosity, final byte opacity, final EnumSkyBlock lightType) { if (luminosity >= MAX_LIGHT_LEVEL - opacity) return luminosity; byte newLight = luminosity; fetchNeighborDataFromCursor(lightType); for (final NeighborInfo neighborInfo : neighborInfos) { if (neighborInfo.chunk == null) continue; newLight = (byte) Math.max(neighborInfo.light - opacity, newLight); } return newLight; } private void spreadLightFromCursor(final byte currentLight, final EnumSkyBlock lightType) { fetchNeighborDataFromCursor(lightType); for (final NeighborInfo neighborInfo : neighborInfos) { final Chunk neighborChunk = neighborInfo.chunk; if (neighborChunk == null || currentLight < neighborInfo.light) continue; final BlockPos neighborBlockPos = neighborInfo.mutableBlockPos; final byte newLight = (byte) (currentLight - getPosOpacity(neighborBlockPos, neighborChunk.getBlockState(neighborBlockPos))); if (newLight > neighborInfo.light) enqueueBrightening(neighborBlockPos, neighborInfo.key, newLight, neighborChunk, lightType); } } private void enqueueBrighteningFromCursor(final byte newLight, final EnumSkyBlock lightType) { enqueueBrightening(currentPos, currentData, newLight, currentChunk, lightType); } /// Enqueues the blockPos for brightening and sets its light value to newLight private void enqueueBrightening(final BlockPos blockPos, final long longPos, final byte newLight, final Chunk chunk, final EnumSkyBlock lightType) { brighteningQueues[newLight].enqueue(longPos); chunk.setLightFor(lightType, blockPos, newLight); } /// Enqueues the blockPos for darkening and sets its light value to 0 private void enqueueDarkening(final BlockPos blockPos, final long longPos, final byte oldLight, final Chunk chunk, final EnumSkyBlock lightType) { darkeningQueues[oldLight].enqueue(longPos); chunk.setLightFor(lightType, blockPos, 0); } private static MutableBlockPos decodeWorldCoord(final MutableBlockPos mutableBlockPos, final long longPos) { return mutableBlockPos.setPos((int) (longPos >> S_X & M_X) - (1 << L_X - 1), (int) (longPos >> S_Y & M_Y), (int) (longPos >> S_Z & M_Z) - (1 << L_Z - 1)); } private static long encodeWorldCoord(final BlockPos pos) { return ((long) pos.getY() << S_Y) | ((long) pos.getX() + (1 << L_X - 1) << S_X) | ((long) pos.getZ() + (1 << L_Z - 1) << S_Z); } /// Polls a new item from [#currentQueue] and fills in state data members /// /// @return If there was an item to poll private boolean nextItem() { if (currentQueue.isEmpty()) { currentQueue = null; return false; } currentData = currentQueue.dequeue(); isNeighborDataValid = false; decodeWorldCoord(currentPos, currentData); final long chunkIdentifier = currentData & M_CHUNK; if (currentChunkIdentifier != chunkIdentifier) { currentChunk = getChunk(currentPos); currentChunkIdentifier = chunkIdentifier; } return true; } private byte getCursorCachedLight(final EnumSkyBlock lightType) { return ((IChunkLightingData) currentChunk).alfheim$getCachedLightFor(lightType, currentPos); } /// Calculates the luminosity for [#currentPos], taking into account the light type private byte getCursorLuminosity(final IBlockState state, final EnumSkyBlock lightType) { if (lightType == EnumSkyBlock.SKY) return currentChunk.canSeeSky(currentPos) ? (byte) EnumSkyBlock.SKY.defaultLightValue : 0; return (byte) ClampUtil.clampMinFirst(LightUtil.getLightValueForState(state, world, currentPos), 0, MAX_LIGHT_LEVEL); } private byte getPosOpacity(final BlockPos blockPos, final IBlockState blockState) { return (byte) ClampUtil.clampMinFirst(blockState.getLightOpacity(world, blockPos), 1, MAX_LIGHT_LEVEL); } private Chunk getChunk(final BlockPos blockPos) { return world.getChunkProvider().getLoadedChunk(blockPos.getX() >> 4, blockPos.getZ() >> 4); } private static final class NeighborInfo { public final MutableBlockPos mutableBlockPos = new MutableBlockPos(); public Chunk chunk; public byte light; public long key; } }
Alfheim
src\main\java\dev\redstudio\alfheim\lighting\LightUtil.java
package dev.redstudio.alfheim.lighting; import atomicstryker.dynamiclights.client.DynamicLights; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import static dev.redstudio.alfheim.Alfheim.IS_DYNAMIC_LIGHTS_LOADED; /// @author Luna Mira Lage (Desoroxxx) /// @author embeddedt /// @since 1.0 public final class LightUtil { public static int getLightValueForState(final IBlockState blockState, final IBlockAccess blockAccess, final BlockPos blockPos) { if (IS_DYNAMIC_LIGHTS_LOADED) { return DynamicLights.getLightValue(blockState.getBlock(), blockState, blockAccess, blockPos); // Use the Dynamic Lights implementation } else { return blockState.getLightValue(blockAccess, blockPos); // Use the vanilla implementation } } }
Alfheim
src\main\java\dev\redstudio\alfheim\mixin\AnvilChunkLoaderMixin.java
package dev.redstudio.alfheim.mixin; import dev.redstudio.alfheim.Alfheim; import dev.redstudio.alfheim.api.IChunkLightingData; import dev.redstudio.alfheim.api.ILightingEngineProvider; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagShort; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.AnvilChunkLoader; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import static dev.redstudio.alfheim.ProjectConstants.LOGGER; /// @author Luna Mira Lage (Desoroxxx) /// @author Angeline (@jellysquid) /// @since 1.0 @Mixin(AnvilChunkLoader.class) public abstract class AnvilChunkLoaderMixin { @Unique private static final String NEIGHBOR_LIGHT_CHECKS_KEY = "NeighborLightChecks"; /// Injects into the head of saveChunk() to forcefully process all pending light updates. Fail-safe. /// /// @author Angeline (@jellysquid) @Inject(method = "saveChunk", at = @At("HEAD")) private void onConstructed(final World world, final Chunk chunk, final CallbackInfo callbackInfo) { ((ILightingEngineProvider) world).getAlfheim$lightingEngine().processLightUpdates(); } /// Injects the deserialization logic for chunk data on load so we can extract whether or not we've populated light yet. /// /// @author Angeline (@jellysquid) @Inject(method = "readChunkFromNBT", at = @At("RETURN")) private void onReadChunkFromNBT(final World world, final NBTTagCompound compound, final CallbackInfoReturnable<Chunk> callbackInfoReturnable) { final Chunk chunk = callbackInfoReturnable.getReturnValue(); alfheim$readNeighborLightChecksFromNBT(chunk, compound); ((IChunkLightingData) chunk).alfheim$setLightInitialized(compound.getBoolean("LightPopulated")); } /// Injects the serialization logic for chunk data on save, so we can store whether or not we've populated light yet. /// /// @author Angeline (@jellysquid) @Inject(method = "writeChunkToNBT", at = @At("RETURN")) private void onWriteChunkToNBT(final Chunk chunk, final World world, final NBTTagCompound compound, final CallbackInfo callbackInfo) { alfheim$writeNeighborLightChecksToNBT(chunk, compound); compound.setBoolean("LightPopulated", ((IChunkLightingData) chunk).alfheim$isLightInitialized()); } @Unique private static void alfheim$readNeighborLightChecksFromNBT(final Chunk chunk, final NBTTagCompound compound) { if (!compound.hasKey(NEIGHBOR_LIGHT_CHECKS_KEY, 9)) return; final NBTTagList tagList = compound.getTagList(NEIGHBOR_LIGHT_CHECKS_KEY, 2); if (tagList.tagCount() != Alfheim.FLAG_COUNT) { LOGGER.warn("Chunk field {} had invalid length, ignoring it (chunk coordinates: {} {})", NEIGHBOR_LIGHT_CHECKS_KEY, chunk.x, chunk.z); return; } ((IChunkLightingData) chunk).alfheim$initNeighborLightChecks(); final short[] neighborLightChecks = ((IChunkLightingData) chunk).alfheim$getNeighborLightChecks(); for (int i = 0; i < Alfheim.FLAG_COUNT; ++i) neighborLightChecks[i] = ((NBTTagShort) tagList.get(i)).getShort(); } @Unique private static void alfheim$writeNeighborLightChecksToNBT(final Chunk chunk, final NBTTagCompound compound) { final short[] neighborLightChecks = ((IChunkLightingData) chunk).alfheim$getNeighborLightChecks(); if (neighborLightChecks == null) return; boolean empty = true; final NBTTagList list = new NBTTagList(); for (final short flags : neighborLightChecks) { list.appendTag(new NBTTagShort(flags)); if (flags != 0) empty = false; } if (!empty) compound.setTag(NEIGHBOR_LIGHT_CHECKS_KEY, list); } }
Alfheim
src\main\java\dev\redstudio\alfheim\mixin\BlockMixin.java
package dev.redstudio.alfheim.mixin; import com.llamalad7.mixinextras.sugar.Local; import com.llamalad7.mixinextras.sugar.ref.LocalBooleanRef; import dev.redstudio.alfheim.api.ILightInfoProvider; import dev.redstudio.alfheim.api.ILightLevelProvider; import dev.redstudio.alfheim.api.ILitBlock; import dev.redstudio.redcore.math.ClampUtil; import net.minecraft.block.Block; import net.minecraft.block.BlockLiquid; import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.IBlockAccess; import net.minecraftforge.fluids.BlockFluidBase; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; /// @author Luna Mira Lage (Desoroxxx) /// @since 1.0 @Mixin(Block.class) public abstract class BlockMixin implements ILitBlock { @Shadow @Deprecated public abstract int getLightValue(final IBlockState blockState); /// @reason Part of non-full block lighting fix /// @author Luna Mira Lage (Desoroxxx) @Overwrite @SideOnly(Side.CLIENT) public int getPackedLightmapCoords(final IBlockState blockState, final IBlockAccess source, final BlockPos blockPos) { return source.getCombinedLight(blockPos, blockState.getLightValue(source, blockPos)); } @Inject(method = "registerBlocks", at = @At(value = "FIELD", target = "Lnet/minecraft/block/Block;useNeighborBrightness:Z", ordinal = 1, shift = At.Shift.BEFORE), locals = LocalCapture.CAPTURE_FAILEXCEPTION) private static void checkForLiquid(final CallbackInfo callbackInfo, @Local(ordinal = 15) final Block block, @Local(ordinal = 0) LocalBooleanRef flag) { boolean result = flag.get(); result |= block instanceof BlockFluidBase; result |= block instanceof BlockLiquid; flag.set(result); } /// @reason Part of non-full block lighting fix /// @author Luna Mira Lage (Desoroxxx) @Overwrite @SideOnly(Side.CLIENT) public float getAmbientOcclusionLightValue(final IBlockState blockState) { final byte lightValue = (byte) ClampUtil.clampMinFirst(blockState.getLightValue() - 1, 0, 15); if (lightValue == 0) { return blockState.isBlockNormalCube() ? 0.2F : 1; } else { return 1; } } @Override public int alfheim$getLightFor(final IBlockState blockState, final IBlockAccess blockAccess, final EnumSkyBlock lightType, final BlockPos blockPos) { int lightLevel = ((ILightLevelProvider) blockAccess).alfheim$getLight(lightType, blockPos); if (lightLevel == 15) return lightLevel; if (!blockState.useNeighborBrightness()) return lightLevel; for (EnumFacing facing : EnumFacing.VALUES) { if (((ILightInfoProvider) blockState).alfheim$useNeighborBrightness(facing, blockAccess, blockPos)) { int opacity = ((ILightInfoProvider) blockState).alfheim$getLightOpacity(facing, blockAccess, blockPos); final int neighborLightLevel = ((ILightLevelProvider) blockAccess).alfheim$getLight(lightType, blockPos.offset(facing)); if (opacity == 0 && (lightType != EnumSkyBlock.SKY || neighborLightLevel != EnumSkyBlock.SKY.defaultLightValue)) opacity = 1; lightLevel = Math.max(lightLevel, neighborLightLevel - opacity); if (lightLevel == 15) return lightLevel; } } return lightLevel; } @Override public boolean alfheim$useNeighborBrightness(final IBlockState blockState, final EnumFacing facing, final IBlockAccess blockAccess, final BlockPos blockPos) { return facing == EnumFacing.UP; } @Override public int alfheim$getLightOpacity(final IBlockState blockState, final EnumFacing facing, final IBlockAccess blockAccess, final BlockPos blockPos) { return 0; } }
Alfheim
src\main\java\dev\redstudio\alfheim\mixin\BlockSlabMixin.java
package dev.redstudio.alfheim.mixin; import dev.redstudio.alfheim.api.ILitBlock; import net.minecraft.block.BlockSlab; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import static net.minecraft.block.BlockSlab.EnumBlockHalf.TOP; /// @author Luna Mira Lage (Desoroxxx) /// @since 1.0 @Mixin(BlockSlab.class) public abstract class BlockSlabMixin extends BlockMixin implements ILitBlock { @Shadow @Final public static PropertyEnum<BlockSlab.EnumBlockHalf> HALF; @Override public boolean alfheim$useNeighborBrightness(final IBlockState blockState, final EnumFacing facing, final IBlockAccess blockAccess, final BlockPos blockPos) { if (facing.getAxis() != EnumFacing.Axis.Y) return false; if (((BlockSlab) (Object) this).isFullCube(blockState)) return false; return facing == (blockState.getValue(HALF) == TOP ? EnumFacing.DOWN : EnumFacing.UP); } }
Alfheim
src\main\java\dev\redstudio\alfheim\mixin\BlockStairsMixin.java
package dev.redstudio.alfheim.mixin; import dev.redstudio.alfheim.api.ILitBlock; import net.minecraft.block.BlockStairs; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import static net.minecraft.block.BlockStairs.EnumHalf.TOP; /// @author Luna Mira Lage (Desoroxxx) /// @since 1.0 @Mixin(BlockStairs.class) public abstract class BlockStairsMixin extends BlockMixin implements ILitBlock { @Shadow @Final public static PropertyEnum<BlockStairs.EnumHalf> HALF; @Override public boolean alfheim$useNeighborBrightness(final IBlockState blockState, final EnumFacing facing, final IBlockAccess blockAccess, final BlockPos blockPos) { if (facing.getAxis() != EnumFacing.Axis.Y) return false; return facing == (blockState.getValue(HALF) == TOP ? EnumFacing.DOWN : EnumFacing.UP); } }
Alfheim
src\main\java\dev\redstudio\alfheim\mixin\BlockStateContainerMixin.java
package dev.redstudio.alfheim.mixin; import dev.redstudio.alfheim.api.ILightInfoProvider; import dev.redstudio.alfheim.api.ILitBlock; import net.minecraft.block.Block; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.IBlockAccess; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; /// @author Luna Mira Lage (Desoroxxx) /// @since 1.0 @Mixin(BlockStateContainer.class) public abstract class BlockStateContainerMixin implements ILightInfoProvider { @Shadow @Final private Block block; @Override public int alfheim$getLightFor(IBlockAccess iBlockAccess, EnumSkyBlock lightType, BlockPos blockPos) { return ((ILitBlock) block).alfheim$getLightFor(((IBlockState) this), iBlockAccess, lightType, blockPos); } @Override public boolean alfheim$useNeighborBrightness(EnumFacing facing, IBlockAccess blockAccess, BlockPos blockPos) { return ((ILitBlock) block).alfheim$useNeighborBrightness(((IBlockState) this), facing, blockAccess, blockPos); } @Override public int alfheim$getLightOpacity(EnumFacing facing, IBlockAccess blockAccess, BlockPos blockPos) { return ((ILitBlock) block).alfheim$getLightOpacity(((IBlockState) this), facing, blockAccess, blockPos); } @Mixin(BlockStateContainer.StateImplementation.class) public static class StateImplementationMixin implements ILightInfoProvider { @Shadow @Final private Block block; @Override public int alfheim$getLightFor(IBlockAccess iBlockAccess, EnumSkyBlock lightType, BlockPos blockPos) { return ((ILitBlock) block).alfheim$getLightFor(((IBlockState) this), iBlockAccess, lightType, blockPos); } @Override public boolean alfheim$useNeighborBrightness(EnumFacing facing, IBlockAccess blockAccess, BlockPos blockPos) { return ((ILitBlock) block).alfheim$useNeighborBrightness(((IBlockState) this), facing, blockAccess, blockPos); } @Override public int alfheim$getLightOpacity(EnumFacing facing, IBlockAccess blockAccess, BlockPos blockPos) { return ((ILitBlock) block).alfheim$getLightOpacity(((IBlockState) this), facing, blockAccess, blockPos); } } }
Alfheim
src\main\java\dev\redstudio\alfheim\mixin\ChunkCacheMixin.java
package dev.redstudio.alfheim.mixin; import dev.redstudio.alfheim.api.ILightInfoProvider; import dev.redstudio.alfheim.api.ILightLevelProvider; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.world.ChunkCache; import net.minecraft.world.EnumSkyBlock; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; /// @author Luna Mira Lage (Desoroxxx) /// @since 1.0 @Mixin(ChunkCache.class) public abstract class ChunkCacheMixin implements ILightLevelProvider { @SideOnly(Side.CLIENT) @Shadow public abstract int getLightFor(final EnumSkyBlock lightType, final BlockPos blockPos); @Shadow public abstract IBlockState getBlockState(BlockPos pos); /// @reason Redirect to our lighting engine. /// @author Luna Mira Lage (Desoroxxx) @Overwrite @SideOnly(Side.CLIENT) private int getLightForExt(final EnumSkyBlock lightType, final BlockPos blockPos) { return ((ILightInfoProvider) getBlockState(blockPos)).alfheim$getLightFor(((ChunkCache) (Object) this), lightType, blockPos); } @Override public int alfheim$getLight(final EnumSkyBlock lightType, final BlockPos blockPos) { return getLightFor(lightType, blockPos); } }
Alfheim
src\main\java\dev\redstudio\alfheim\mixin\ChunkMixin.java
package dev.redstudio.alfheim.mixin; import dev.redstudio.alfheim.api.IChunkLightingData; import dev.redstudio.alfheim.api.ILightingEngineProvider; import dev.redstudio.alfheim.lighting.LightUtil; import dev.redstudio.alfheim.lighting.LightingEngine; import dev.redstudio.alfheim.utils.EnumBoundaryFacing; import dev.redstudio.alfheim.utils.WorldChunkSlice; import lombok.Getter; import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import org.spongepowered.asm.mixin.*; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import static dev.redstudio.alfheim.Alfheim.FLAG_COUNT; /// @author Luna Mira Lage (Desoroxxx) /// @author kappa-maintainer /// @author embeddedt /// @author Angeline (@jellysquid) /// @since 1.0 @Mixin(Chunk.class) public abstract class ChunkMixin implements IChunkLightingData, ILightingEngineProvider { @Final @Shadow private boolean[] updateSkylightColumns; @Shadow private boolean dirty; @Shadow private boolean isTerrainPopulated; @Shadow private boolean isGapLightingUpdated; @Final @Shadow public int x; @Final @Shadow public int z; @Shadow @Final private int[] heightMap; @Shadow private int heightMapMinimum; @Shadow @Final private World world; @Shadow @Final private ExtendedBlockStorage[] storageArrays; @Shadow protected abstract int getBlockLightOpacity(final int x, final int y, final int z); @Shadow public abstract boolean canSeeSky(final BlockPos blockPos); @Shadow protected abstract void setSkylightUpdated(); @Shadow public abstract int getHeightValue(final int x, final int z); @Unique private static final EnumFacing[] ENUM_FACING_HORIZONTAL = EnumFacing.Plane.HORIZONTAL.facings(); @Unique private static final EnumSkyBlock[] ENUM_SKY_BLOCK_VALUES = EnumSkyBlock.values(); @Unique private static final EnumFacing.AxisDirection[] ENUM_AXIS_DIRECTION_VALUES = EnumFacing.AxisDirection.values(); @Unique private boolean alfheim$isLightInitialized; @Unique private short[] alfheim$neighborLightChecks; @Unique @Getter(onMethod_ = {@Override}) private LightingEngine alfheim$lightingEngine; /// Callback injected into the Chunk ctor to cache a reference to the lighting engine from the world. /// /// @author Angeline (@jellysquid) @Inject(method = "<init>*", at = @At("RETURN")) private void onConstructed(final CallbackInfo callbackInfo) { alfheim$lightingEngine = ((ILightingEngineProvider) world).getAlfheim$lightingEngine(); } /// Callback injected to the head of [#getLightSubtracted(BlockPos,int)] to force deferred light updates to be processed. /// /// @author Angeline (@jellysquid) @Inject(method = "getLightSubtracted", at = @At("HEAD")) private void onGetLightSubtracted(final BlockPos blockPos, final int amount, final CallbackInfoReturnable<Integer> callbackInfoReturnable) { alfheim$lightingEngine.processLightUpdates(); } /// Callback injected at the end of [#onLoad()] to have previously scheduled light updates scheduled again. /// /// @author Angeline (@jellysquid) @Inject(method = "onLoad", at = @At("RETURN")) private void onLoad(final CallbackInfo callbackInfo) { final Chunk chunk = (Chunk) (Object) this; for (final EnumFacing facing : EnumFacing.HORIZONTALS) { final int xOffset = facing.getXOffset(); final int zOffset = facing.getZOffset(); final Chunk nChunk = world.getChunkProvider().getLoadedChunk(chunk.x + xOffset, chunk.z + zOffset); if (nChunk == null) { continue; } for (final EnumSkyBlock lightType : ENUM_SKY_BLOCK_VALUES) { for (final EnumFacing.AxisDirection axisDir : ENUM_AXIS_DIRECTION_VALUES) { // Merge flags upon loading of a chunk. This ensures that all flags are always already on the IN boundary below alfheim$mergeFlags(lightType, chunk, nChunk, facing, axisDir); alfheim$mergeFlags(lightType, nChunk, chunk, facing.getOpposite(), axisDir); // Check everything that might have been canceled due to this chunk not being loaded. // Also, pass in chunks if already known // The boundary to the neighbor chunk (both ways) alfheim$scheduleRelightChecksForBoundary(chunk, nChunk, null, lightType, xOffset, zOffset, axisDir); alfheim$scheduleRelightChecksForBoundary(nChunk, chunk, null, lightType, -xOffset, -zOffset, axisDir); // The boundary to the diagonal neighbor (since the checks in that chunk were aborted if this chunk wasn't loaded, see alfheim$scheduleRelightChecksForBoundary) alfheim$scheduleRelightChecksForBoundary(nChunk, null, chunk, lightType, (zOffset != 0 ? axisDir.getOffset() : 0), (xOffset != 0 ? axisDir.getOffset() : 0), facing.getAxisDirection() == EnumFacing.AxisDirection.POSITIVE ? EnumFacing.AxisDirection.NEGATIVE : EnumFacing.AxisDirection.POSITIVE); } } } } /// Replaces the call in [#setLightFor(EnumSkyBlock,BlockPos,int)] with our hook. /// /// @author Angeline (@jellysquid) @Redirect(method = "setLightFor", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/chunk/Chunk;generateSkylightMap()V"), expect = 0) private void setLightForRedirectGenerateSkylightMap(final Chunk chunk, final EnumSkyBlock lightType, final BlockPos blockPos, final int value) { alfheim$initSkylightForSection(storageArrays[blockPos.getY() >> 4]); } /// @reason Overwrites relightBlock with a more efficient implementation. /// @author Angeline (@jellysquid) @Overwrite private void relightBlock(final int x, final int y, final int z) { int heightMapY = heightMap[z << 4 | x] & 255; int newHeightMapY = Math.max(y, heightMapY); while (newHeightMapY > 0 && getBlockLightOpacity(x, newHeightMapY - 1, z) == 0) --newHeightMapY; if (newHeightMapY == heightMapY) return; heightMap[z << 4 | x] = newHeightMapY; if (world.provider.hasSkyLight()) { alfheim$relightSkylightColumn(x, z, heightMapY, newHeightMapY); } final int heightMapY1 = heightMap[z << 4 | x]; if (heightMapY1 < heightMapMinimum) { heightMapMinimum = heightMapY1; } } /// @reason Calculate light updates only as needed. /// @author Angeline (@jellysquid) @Overwrite public int getLightFor(final EnumSkyBlock lightType, final BlockPos pos) { alfheim$lightingEngine.processLightUpdatesForType(lightType); return alfheim$getCachedLightFor(lightType, pos); } /// @reason Check chunk lighting and returns immediately after. /// @author Angeline (@jellysquid) @Overwrite public void checkLight() { isTerrainPopulated = true; final Chunk chunk = (Chunk) (Object) this; if (!((IChunkLightingData) chunk).alfheim$isLightInitialized()) { alfheim$initChunkLighting(chunk, world); } for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { if (x == 0 && z == 0) { continue; } final Chunk nChunk = world.getChunkProvider().getLoadedChunk(chunk.x + x, chunk.z + z); if (nChunk == null || !((IChunkLightingData) nChunk).alfheim$isLightInitialized()) { return; } } } chunk.setLightPopulated(true); } /// @reason Avoids chunk fetches as much as possible. /// @author Luna Mira Lage (Desoroxxx) /// @author Angeline (@jellysquid) @Overwrite private void recheckGaps(final boolean onlyOne) { if (!world.isAreaLoaded(new BlockPos((x << 4) + 8, 0, (z << 4) + 8), 16)) return; final WorldChunkSlice slice = new WorldChunkSlice(world.getChunkProvider(), x, z); for (int x = 0; x < 16; ++x) { for (int z = 0; z < 16; ++z) { if (!alfheim$recheckGapsForColumn(slice, x, z)) { continue; } if (onlyOne) { return; } } } isGapLightingUpdated = false; } /// Redirects the construction of the ExtendedBlockStorage in [#setBlockState(BlockPos,IBlockState)]. /// We need to initialize the skylight data for the constructed section as soon as possible. /// /// @author Angeline (@jellysquid) @Redirect(method = "setBlockState", at = @At(value = "NEW", args = "class=net/minecraft/world/chunk/storage/ExtendedBlockStorage"), expect = 0) private ExtendedBlockStorage setBlockStateCreateSectionVanilla(final int y, final boolean hasSkyLight) { final ExtendedBlockStorage extendedBlockStorage = new ExtendedBlockStorage(y, hasSkyLight); alfheim$initSkylightForSection(extendedBlockStorage); return extendedBlockStorage; } /// Modifies the flag variable of [#setBlockState(BlockPos,IBlockState)] to always be false after it is set, preventing the generation of the sky lightmap. /// /// @author Luna Mira Lage (Desoroxxx) /// @author Angeline (@jellysquid) @ModifyVariable(method = "setBlockState", at = @At(value = "STORE", ordinal = 1), name = "flag") private boolean preventGenerateSkylightMap(final boolean original) { return false; } /// Prevent propagateSkylightOcclusion from being called. /// /// @author embeddedt @Redirect(method = "setBlockState", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/chunk/Chunk;propagateSkylightOcclusion(II)V")) private void doPropagateSkylight(final Chunk chunk, final int x, final int z) { /* No-op, we don't want skylight propagated */ } /// Prevent [Chunk#getLightFor] from being called. /// /// @author embeddedt @Redirect(method = "setBlockState", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/chunk/Chunk;getLightFor(Lnet/minecraft/world/EnumSkyBlock;Lnet/minecraft/util/math/BlockPos;)I")) private int fakeGetLightFor(final Chunk chunk, final EnumSkyBlock lightType, final BlockPos blockPos) { return 0; } @Unique private boolean alfheim$recheckGapsForColumn(final WorldChunkSlice slice, final int x, final int z) { final int i = x + z * 16; if (updateSkylightColumns[i]) { updateSkylightColumns[i] = false; final int x1 = this.x * 16 + x; final int z1 = this.z * 16 + z; alfheim$recheckGapsSkylightNeighborHeight(slice, x1, z1, getHeightValue(x, z), alfheim$recheckGapsGetLowestHeight(slice, x1, z1)); return true; } return false; } @Unique private int alfheim$recheckGapsGetLowestHeight(final WorldChunkSlice slice, final int x, final int z) { int max = Integer.MAX_VALUE; for (final EnumFacing facing : ENUM_FACING_HORIZONTAL) { final Chunk chunk = slice.getChunkFromWorldCoords(x + facing.getXOffset(), z + facing.getZOffset()); if (chunk != null) { max = Math.min(max, chunk.getLowestHeight()); } } return max; } @Unique private void alfheim$recheckGapsSkylightNeighborHeight(final WorldChunkSlice slice, final int x, final int z, final int height, final int max) { alfheim$checkSkylightNeighborHeight(slice, x, z, max); for (final EnumFacing facing : ENUM_FACING_HORIZONTAL) alfheim$checkSkylightNeighborHeight(slice, x + facing.getXOffset(), z + facing.getZOffset(), height); } @Unique private void alfheim$checkSkylightNeighborHeight(final WorldChunkSlice slice, final int x, final int z, final int maxValue) { if (slice.getChunkFromWorldCoords(x, z) == null) return; final int y = slice.getChunkFromWorldCoords(x, z).getHeightValue(x & 15, z & 15); if (y > maxValue) { alfheim$updateSkylightNeighborHeight(slice, x, z, maxValue, y + 1); } else if (y < maxValue) { alfheim$updateSkylightNeighborHeight(slice, x, z, y, maxValue + 1); } } @Unique private void alfheim$updateSkylightNeighborHeight(final WorldChunkSlice slice, final int x, final int z, final int startY, final int endY) { if (endY < startY) return; if (!slice.isLoaded(x, z, 16)) return; for (int y = startY; y < endY; ++y) world.checkLightFor(EnumSkyBlock.SKY, new BlockPos(x, y, z)); dirty = true; } @Unique private static void alfheim$mergeFlags(final EnumSkyBlock lightType, final Chunk inChunk, final Chunk outChunk, final EnumFacing dir, final EnumFacing.AxisDirection axisDirection) { final IChunkLightingData outChunkLightingData = (IChunkLightingData) outChunk; if (outChunkLightingData.alfheim$getNeighborLightChecks() == null) return; ((IChunkLightingData) inChunk).alfheim$initNeighborLightChecks(); final int inIndex = alfheim$getFlagIndex(lightType, dir, axisDirection, EnumBoundaryFacing.IN); final int outIndex = alfheim$getFlagIndex(lightType, dir.getOpposite(), axisDirection, EnumBoundaryFacing.OUT); ((IChunkLightingData) inChunk).alfheim$getNeighborLightChecks()[inIndex] |= outChunkLightingData.alfheim$getNeighborLightChecks()[outIndex]; // No need to call Chunk.setModified() since checks are not deleted from outChunk } @Unique private void alfheim$scheduleRelightChecksForBoundary(final Chunk chunk, Chunk nChunk, Chunk sChunk, final EnumSkyBlock lightType, final int xOffset, final int zOffset, final EnumFacing.AxisDirection axisDirection) { final IChunkLightingData chunkLightingData = (IChunkLightingData) chunk; if (chunkLightingData.alfheim$getNeighborLightChecks() == null) return; final int flagIndex = alfheim$getFlagIndex(lightType, xOffset, zOffset, axisDirection, EnumBoundaryFacing.IN); // OUT checks from neighbor are already merged final int flags = chunkLightingData.alfheim$getNeighborLightChecks()[flagIndex]; if (flags == 0) return; if (nChunk == null) { nChunk = world.getChunkProvider().getLoadedChunk(chunk.x + xOffset, chunk.z + zOffset); if (nChunk == null) { return; } } if (sChunk == null) { sChunk = world.getChunkProvider() .getLoadedChunk(chunk.x + (zOffset != 0 ? axisDirection.getOffset() : 0), chunk.z + (xOffset != 0 ? axisDirection.getOffset() : 0)); if (sChunk == null) { return; // Cancel, since the checks in the corner columns require the corner column of sChunk } } final int reverseIndex = alfheim$getFlagIndex(lightType, -xOffset, -zOffset, axisDirection, EnumBoundaryFacing.OUT); chunkLightingData.alfheim$getNeighborLightChecks()[flagIndex] = 0; final IChunkLightingData nChunkLightingData = (IChunkLightingData) nChunk; if (nChunkLightingData.alfheim$getNeighborLightChecks() != null) { nChunkLightingData.alfheim$getNeighborLightChecks()[reverseIndex] = 0; // Clear only now that it's clear that the checks are processed } chunk.markDirty(); nChunk.markDirty(); // Get the area to check // Start in the corner... int xMin = chunk.x << 4; int zMin = chunk.z << 4; // Move to other side of chunk if the direction is positive if ((xOffset | zOffset) > 0) { xMin += 15 * xOffset; zMin += 15 * zOffset; } // Shift to other half if necessary (shift perpendicular to dir) if (axisDirection == EnumFacing.AxisDirection.POSITIVE) { xMin += 8 * (zOffset & 1); //x & 1 is same as abs(x) for x=-1,0,1 zMin += 8 * (xOffset & 1); } // Get maximal values (shift perpendicular to dir) final int xMax = xMin + 7 * (zOffset & 1); final int zMax = zMin + 7 * (xOffset & 1); for (int y = 0; y < 16; ++y) if ((flags & (1 << y)) != 0) { for (int x = xMin; x <= xMax; ++x) for (int z = zMin; z <= zMax; ++z) alfheim$scheduleRelightChecksForColumn(lightType, x, z, y << 4, (y << 4) + 15); } } @Unique private void alfheim$initSkylightForSection(final ExtendedBlockStorage extendedBlockStorage) { if (!world.provider.hasSkyLight()) return; for (int x = 0; x < 16; ++x) { for (int z = 0; z < 16; ++z) { if (((Chunk) (Object) this).getHeightValue(x, z) > extendedBlockStorage.getYLocation()) { continue; } for (int y = 0; y < 16; ++y) extendedBlockStorage.setSkyLight(x, y, z, EnumSkyBlock.SKY.defaultLightValue); } } } @Unique private void alfheim$scheduleRelightChecksForColumn(final EnumSkyBlock lightType, final int x, final int z, final int yMin, final int yMax) { final BlockPos.MutableBlockPos mutableBlockPos = new BlockPos.MutableBlockPos(); for (int y = yMin; y <= yMax; ++y) world.checkLightFor(lightType, mutableBlockPos.setPos(x, y, z)); } @Unique private static int alfheim$getFlagIndex(final EnumSkyBlock lightType, final int xOffset, final int zOffset, final EnumFacing.AxisDirection axisDirection, final EnumBoundaryFacing boundaryFacing) { return (lightType == EnumSkyBlock.BLOCK ? 0 : 16) | ((xOffset + 1) << 2) | ((zOffset + 1) << 1) | (axisDirection.getOffset() + 1) | boundaryFacing.ordinal(); } @Unique private static int alfheim$getFlagIndex(final EnumSkyBlock lightType, final EnumFacing facing, final EnumFacing.AxisDirection axisDirection, final EnumBoundaryFacing boundaryFacing) { return alfheim$getFlagIndex(lightType, facing.getXOffset(), facing.getZOffset(), axisDirection, boundaryFacing); } @Unique private static void alfheim$initChunkLighting(final Chunk chunk, final World world) { final int xBase = chunk.x << 4; final int zBase = chunk.z << 4; final BlockPos.PooledMutableBlockPos mutableBlockPos = BlockPos.PooledMutableBlockPos.retain(xBase, 0, zBase); if (world.isAreaLoaded(mutableBlockPos.add(-16, 0, -16), mutableBlockPos.add(31, 255, 31), false)) { final ExtendedBlockStorage[] extendedBlockStorage = chunk.getBlockStorageArray(); for (int i = 0; i < extendedBlockStorage.length; ++i) { final ExtendedBlockStorage storage = extendedBlockStorage[i]; if (storage == Chunk.NULL_BLOCK_STORAGE) { continue; } int yBase = i * 16; for (int y = 0; y < 16; y++) { for (int z = 0; z < 16; z++) { for (int x = 0; x < 16; x++) { mutableBlockPos.setPos(xBase + x, yBase + y, zBase + z); if (LightUtil.getLightValueForState(storage.getData().get(x, y, z), world, mutableBlockPos) > 0) { world.checkLightFor(EnumSkyBlock.BLOCK, mutableBlockPos); } } } } } if (world.provider.hasSkyLight()) { ((IChunkLightingData) chunk).alfheim$setSkylightUpdatedPublic(); } ((IChunkLightingData) chunk).alfheim$setLightInitialized(true); } mutableBlockPos.release(); } @Unique private void alfheim$relightSkylightColumn(final int x, final int z, final int height1, final int height2) { final int yMin = Math.min(height1, height2); final int yMax = Math.max(height1, height2) - 1; final Chunk chunk = ((Chunk) (Object) this); final ExtendedBlockStorage[] sections = chunk.getBlockStorageArray(); final int xBase = (chunk.x << 4) + x; final int zBase = (chunk.z << 4) + z; alfheim$scheduleRelightChecksForColumn(EnumSkyBlock.SKY, xBase, zBase, yMin, yMax); if (sections[yMin >> 4] == Chunk.NULL_BLOCK_STORAGE && yMin > 0) { world.checkLightFor(EnumSkyBlock.SKY, new BlockPos(xBase, yMin - 1, zBase)); } short emptySections = 0; for (int sec = yMax >> 4; sec >= yMin >> 4; --sec) { if (sections[sec] == Chunk.NULL_BLOCK_STORAGE) { emptySections |= (short) (1 << sec); } } if (emptySections != 0) { for (final EnumFacing facing : EnumFacing.HORIZONTALS) { final int xOffset = facing.getXOffset(); final int zOffset = facing.getZOffset(); final boolean neighborColumnExists = (((x + xOffset) | (z + zOffset)) & 16) == 0 //Checks whether the position is at the specified border (the 16 bit is set for both 15+1 and 0-1) || world.getChunkProvider().getLoadedChunk(chunk.x + xOffset, chunk.z + zOffset) != null; if (neighborColumnExists) { for (int sec = yMax >> 4; sec >= yMin >> 4; --sec) { if ((emptySections & (1 << sec)) != 0) { alfheim$scheduleRelightChecksForColumn(EnumSkyBlock.SKY, xBase + xOffset, zBase + zOffset, sec << 4, (sec << 4) + 15); } } } else { ((IChunkLightingData) chunk).alfheim$initNeighborLightChecks(); final EnumFacing.AxisDirection axisDirection = ((facing.getAxis() == EnumFacing.Axis.X ? z : x) & 15) < 8 ? EnumFacing.AxisDirection.NEGATIVE : EnumFacing.AxisDirection.POSITIVE; ((IChunkLightingData) chunk).alfheim$getNeighborLightChecks()[alfheim$getFlagIndex(EnumSkyBlock.SKY, facing, axisDirection, EnumBoundaryFacing.OUT)] |= emptySections; chunk.markDirty(); } } } } @Override public short[] alfheim$getNeighborLightChecks() { return alfheim$neighborLightChecks; } @Override public void alfheim$setNeighborLightChecks(final short[] data) { alfheim$neighborLightChecks = data; } @Override public boolean alfheim$isLightInitialized() { return alfheim$isLightInitialized; } @Override public void alfheim$setLightInitialized(final boolean lightInitialized) { alfheim$isLightInitialized = lightInitialized; } @Override public void alfheim$setSkylightUpdatedPublic() { setSkylightUpdated(); } @Override public void alfheim$initNeighborLightChecks() { if (alfheim$getNeighborLightChecks() == null) { alfheim$setNeighborLightChecks(new short[FLAG_COUNT]); } } @Override public byte alfheim$getCachedLightFor(final EnumSkyBlock lightType, final BlockPos blockPos) { final int x = blockPos.getX() & 15; final int y = blockPos.getY(); final int z = blockPos.getZ() & 15; final ExtendedBlockStorage extendedblockstorage = storageArrays[y >> 4]; if (extendedblockstorage == Chunk.NULL_BLOCK_STORAGE) { return canSeeSky(blockPos) ? (byte) lightType.defaultLightValue : 0; } else if (lightType == EnumSkyBlock.SKY) { return world.provider.hasSkyLight() ? (byte) extendedblockstorage.getSkyLight(x, y & 15, z) : 0; } else { return lightType == EnumSkyBlock.BLOCK ? (byte) extendedblockstorage.getBlockLight(x, y & 15, z) : (byte) lightType.defaultLightValue; } } }
Alfheim
src\main\java\dev\redstudio\alfheim\mixin\ChunkProviderServerMixin.java
package dev.redstudio.alfheim.mixin; import dev.redstudio.alfheim.api.ILightingEngineProvider; import net.minecraft.world.WorldServer; import net.minecraft.world.gen.ChunkProviderServer; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; /// @author Luna Mira Lage (Desoroxxx) /// @author Angeline (@jellysquid) /// @since 1.0 @Mixin(ChunkProviderServer.class) public abstract class ChunkProviderServerMixin { @Shadow @Final public WorldServer world; /// Injects a callback into the start of saveChunks(boolean) to force all light updates to be processed before saving. /// /// @author Angeline (@jellysquid) @Inject(method = "saveChunks", at = @At("HEAD")) private void onSaveChunks(final boolean all, final CallbackInfoReturnable<Boolean> callbackInfoReturnable) { ((ILightingEngineProvider) world).getAlfheim$lightingEngine().processLightUpdates(); } /// Injects a callback into the start of the tick() method after the save checks to process all pending light updates. /// This is not necessarily required, but we don't want our work queues getting too large. /// /// @author Angeline (@jellysquid) @Inject(method = "tick", at = @At(value = "INVOKE", target = "Ljava/util/Set;isEmpty()Z", shift = At.Shift.AFTER)) private void onTick(final CallbackInfoReturnable<Boolean> callbackInfoReturnable) { ((ILightingEngineProvider) world).getAlfheim$lightingEngine().processLightUpdates(); } }
Alfheim
src\main\java\dev\redstudio\alfheim\mixin\ExtendedBlockStorageMixin.java
package dev.redstudio.alfheim.mixin; import net.minecraft.world.chunk.NibbleArray; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; /// @author Luna Mira Lage (Desoroxxx) /// @author Angeline (@jellysquid) /// @since 1.0 @Mixin(ExtendedBlockStorage.class) public abstract class ExtendedBlockStorageMixin { @Shadow private int blockRefCount; @Shadow private NibbleArray blockLight; @Shadow private NibbleArray skyLight; @Unique private int alfheim$lightRefCount = -1; /// @reason Reset [#alfheim$lightRefCount] on call /// @author Angeline (@jellysquid) @Overwrite public void setSkyLight(final int x, final int y, final int z, final int value) { skyLight.set(x, y, z, value); alfheim$lightRefCount = -1; } /// @reason Reset [#alfheim$lightRefCount] on call /// @author Angeline (@jellysquid) @Overwrite public void setBlockLight(final int x, final int y, final int z, final int value) { blockLight.set(x, y, z, value); alfheim$lightRefCount = -1; } /// @reason Reset [#alfheim$lightRefCount] on call /// @author Angeline (@jellysquid) @Overwrite public void setBlockLight(final NibbleArray array) { blockLight = array; alfheim$lightRefCount = -1; } /// @reason Reset [#alfheim$lightRefCount] on call /// @author Angeline (@jellysquid) @Overwrite public void setSkyLight(final NibbleArray array) { skyLight = array; alfheim$lightRefCount = -1; } /// @reason Send light data to clients when lighting is non-trivial /// @author Angeline (@jellysquid) @Overwrite public boolean isEmpty() { if (blockRefCount != 0) { return false; } // -1 indicates the lightRefCount needs to be re-calculated if (alfheim$lightRefCount == -1) { if (alfheim$checkLightArrayEqual(skyLight, (byte) 255) && alfheim$checkLightArrayEqual(blockLight, (byte) 0)) { alfheim$lightRefCount = 0; // Lighting is trivial, don't send to clients } else { alfheim$lightRefCount = 1; // Lighting is not trivial, send to clients } } return alfheim$lightRefCount == 0; } /// Check light array equality /// /// @author Angeline (@jellysquid) /// @author Luna Mira Lage (Desoroxxx) @Unique private boolean alfheim$checkLightArrayEqual(final NibbleArray storage, final byte targetValue) { if (storage == null) { return true; } for (final byte currentByte : storage.getData()) if (currentByte != targetValue) { return false; } return true; } }
Alfheim
src\main\java\dev\redstudio\alfheim\mixin\SPacketChunkDataMixin.java
package dev.redstudio.alfheim.mixin; import dev.redstudio.alfheim.api.ILightingEngineProvider; import net.minecraft.network.play.server.SPacketChunkData; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; /// @author Luna Mira Lage (Desoroxxx) /// @since 1.0 @Mixin(SPacketChunkData.class) public abstract class SPacketChunkDataMixin { /// Redirect a call to [Chunk#getWorld()] in the ctor to force light updates to be processed before creating the client payload. @Redirect(method = "<init>(Lnet/minecraft/world/chunk/Chunk;I)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/chunk/Chunk;getWorld()Lnet/minecraft/world/World;")) private World processLightUpdates(final Chunk chunk) { ((ILightingEngineProvider) chunk).getAlfheim$lightingEngine().processLightUpdates(); return chunk.getWorld(); } }
Alfheim
src\main\java\dev\redstudio\alfheim\mixin\WorldMixin.java
package dev.redstudio.alfheim.mixin; import dev.redstudio.alfheim.api.ILightInfoProvider; import dev.redstudio.alfheim.api.ILightLevelProvider; import dev.redstudio.alfheim.api.ILightingEngineProvider; import dev.redstudio.alfheim.lighting.LightingEngine; import lombok.Getter; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; /// @author Luna Mira Lage (Desoroxxx) /// @author Angeline (@jellysquid) /// @since 1.0 @Mixin(World.class) public abstract class WorldMixin implements ILightingEngineProvider, ILightLevelProvider { @Unique @Getter(lazy = true, onMethod_ = {@Override}) private final LightingEngine alfheim$lightingEngine = new LightingEngine((World) (Object) this); @Shadow private int skylightSubtracted; @Shadow public abstract int getLightFor(final EnumSkyBlock lightType, final BlockPos blockPos); @Shadow public abstract int getLight(final BlockPos blockPos); @Shadow public abstract IBlockState getBlockState(final BlockPos blockPos); /// @reason Redirect to our lighting engine. /// @author Luna Mira Lage (Desoroxxx) @Overwrite public boolean checkLightFor(final EnumSkyBlock lightType, final BlockPos blockPos) { getAlfheim$lightingEngine().scheduleLightUpdate(lightType, blockPos); return true; } /// @reason Redirect to our lighting engine. /// @author Luna Mira Lage (Desoroxxx) @Overwrite public int getLight(final BlockPos blockPos, final boolean checkNeighbors) { if (!checkNeighbors) return getLight(blockPos); final IBlockState blockState = getBlockState(blockPos); return Math.max(((ILightInfoProvider) blockState).alfheim$getLightFor(((World) (Object) this), EnumSkyBlock.BLOCK, blockPos), ((ILightInfoProvider) blockState).alfheim$getLightFor(((World) (Object) this), EnumSkyBlock.SKY, blockPos) - skylightSubtracted); } /// @reason Redirect to our lighting engine. /// @author Luna Mira Lage (Desoroxxx) @Overwrite @SideOnly(Side.CLIENT) public int getLightFromNeighborsFor(final EnumSkyBlock lightType, final BlockPos blockPos) { return ((ILightInfoProvider) getBlockState(blockPos)).alfheim$getLightFor(((World) (Object) this), lightType, blockPos); } @Override public int alfheim$getLight(final EnumSkyBlock lightType, final BlockPos blockPos) { return getLightFor(lightType, blockPos); } }
Alfheim
src\main\java\dev\redstudio\alfheim\utils\DeduplicatedLongQueue.java
package dev.redstudio.alfheim.utils; import it.unimi.dsi.fastutil.longs.LongArrayFIFOQueue; import it.unimi.dsi.fastutil.longs.LongOpenHashSet; /// A queue implementation for long values that are deduplicated on addition. /// /// This is achieved by storing the values in a [LongOpenHashSet] and a [LongArrayFIFOQueue]. /// /// @author Luna Mira Lage (Desoroxxx) /// @since 1.3 public final class DeduplicatedLongQueue { // TODO: Fully Implement my own implementation to get rid of the downsides of reduce etc... private final LongArrayFIFOQueue queue; private LongOpenHashSet set; /// Creates a new deduplicated queue with the given capacity. /// /// @param capacity The capacity of the deduplicated queue public DeduplicatedLongQueue(final int capacity) { set = new LongOpenHashSet(capacity); queue = new LongArrayFIFOQueue(capacity); } /// Adds a value to the queue. /// /// @param value The value to add to the queue public void enqueue(final long value) { if (set.add(value)) queue.enqueue(value); } /// Removes and returns the first value in the queue. /// /// @return The first value in the queue public long dequeue() { return queue.dequeueLong(); } /// Returns whether the queue is empty. /// /// @return `true` if the queue is empty,`false` otherwise public boolean isEmpty() { return queue.isEmpty(); } /// Creates a new deduplication set. public void newDeduplicationSet() { set = new LongOpenHashSet(queue.size()); } }
Alfheim
src\main\java\dev\redstudio\alfheim\utils\EnumBoundaryFacing.java
package dev.redstudio.alfheim.utils; public enum EnumBoundaryFacing { IN, OUT }
Alfheim
src\main\java\dev\redstudio\alfheim\utils\WorldChunkSlice.java
package dev.redstudio.alfheim.utils; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkProvider; /// Represents a slice of a world containing a collection of chunks. /// /// @author Luna Mira Lage (Desoroxxx) /// @author Angeline (@jellysquid) /// @since 1.0 public class WorldChunkSlice { private static final int DIAMETER = 5; private static final int RADIUS = DIAMETER / 2; private final int x, z; private final Chunk[] chunks; /// Initializes a [WorldChunkSlice] object using a given chunk provider and coordinates. /// /// @param chunkProvider The chunk provider to get chunks from /// @param x The X-coordinate of the center chunk /// @param z The Z-coordinate of the center chunk public WorldChunkSlice(final IChunkProvider chunkProvider, final int x, final int z) { chunks = new Chunk[DIAMETER * DIAMETER]; for (int xDiff = -RADIUS; xDiff <= RADIUS; xDiff++) for (int zDiff = -RADIUS; zDiff <= RADIUS; zDiff++) chunks[((xDiff + RADIUS) * DIAMETER) + (zDiff + RADIUS)] = chunkProvider.getLoadedChunk(x + xDiff, z + zDiff); this.x = x - RADIUS; this.z = z - RADIUS; } /// Checks if all chunks within a radius around a coordinate are loaded. /// /// @param x The X-coordinate to check around /// @param z The Z-coordinate to check around /// @param radius The radius around the coordinates to check /// /// @return true if all chunks are loaded, false otherwise public boolean isLoaded(final int x, final int z, final int radius) { final int xStart = ((x - radius) >> 4) - this.x; final int zStart = ((z - radius) >> 4) - this.z; final int xEnd = ((x + radius) >> 4) - this.x; final int zEnd = ((z + radius) >> 4) - this.z; for (int currentX = xStart; currentX <= xEnd; ++currentX) for (int currentZ = zStart; currentZ <= zEnd; ++currentZ) if (getChunk(currentX, currentZ) == null) return false; return true; } /// Retrieves the chunk that includes the provided world coordinates. /// /// @param x The X-coordinate in the world /// @param z The Z-coordinate in the world /// /// @return The Chunk object that includes these coordinates public Chunk getChunkFromWorldCoords(final int x, final int z) { return getChunk((x >> 4) - this.x, (z >> 4) - this.z); } /// Retrieves the chunk located at the given coordinates within this chunk slice. /// /// @param x The X-coordinate within the slice /// @param z The Z-coordinate within the slice /// /// @return The Chunk object at these coordinates private Chunk getChunk(final int x, final int z) { return chunks[(x * DIAMETER) + z]; } }
Alfheim
src\main\java\dev\redstudio\alfheim\mixin\client\BlockModelRendererMixin.java
package dev.redstudio.alfheim.mixin.client; import dev.redstudio.redcore.math.ClampUtil; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.BlockModelRenderer; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; /// @author Luna Mira Lage (Desoroxxx) /// @since 1.0 @SideOnly(Side.CLIENT) @Mixin(BlockModelRenderer.class) public abstract class BlockModelRendererMixin { /// This fixes [MC-225516](https://bugs.mojang.com/browse/MC-225516) the original intent was that block that emit lights shouldn't have an ambient occlusion applied to them which is logical. /// But some light-emitting blocks have very low light values which are barely visible for these blocks ambient occlusion should still be applied. /// In Vanilla, I found that these low light values emitting blocks have a value of one which allows us to fix the issue by subtracting one to the light value check and then clamping it to 0-15. @Redirect( method = "renderModel(Lnet/minecraft/world/IBlockAccess;Lnet/minecraft/client/renderer/block/model/IBakedModel;Lnet/minecraft/block/state/IBlockState;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/client/renderer/BufferBuilder;ZJ)Z", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/state/IBlockState;getLightValue(Lnet/minecraft/world/IBlockAccess;Lnet/minecraft/util/math/BlockPos;)I", remap = false), require = 0 ) private int adjustGetLightValue(final IBlockState blockState, final IBlockAccess blockAccess, final BlockPos blockPos) { return ClampUtil.clampMinFirst(blockState.getLightValue(blockAccess, blockPos) - 1, 0, 15); } /// This fixes [MC-225516](https://bugs.mojang.com/browse/MC-225516) for OptiFine, the original intent was that block that emit lights shouldn't have an ambient occlusion applied to them which is logical. /// But some light-emitting blocks have very low light values which are barely visible for these blocks ambient occlusion should still be applied. /// In Vanilla, I found that these low light values emitting blocks have a value of one which allows us to fix the issue by subtracting one to the light value check and then clamping it to 0-15. @Redirect( method = "renderModel(Lnet/minecraft/world/IBlockAccess;Lnet/minecraft/client/renderer/block/model/IBakedModel;Lnet/minecraft/block/state/IBlockState;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/client/renderer/BufferBuilder;ZJ)Z", at = @At(value = "INVOKE", target = "Lnet/optifine/reflect/ReflectorForge;getLightValue(Lnet/minecraft/block/state/IBlockState;Lnet/minecraft/world/IBlockAccess;Lnet/minecraft/util/math/BlockPos;)I", remap = false), require = 0 ) private int adjustGetLightValueOptiFine(final IBlockState blockState, final IBlockAccess blockAccess, final BlockPos blockPos) { return ClampUtil.clampMinFirst(blockState.getLightValue(blockAccess, blockPos) - 1, 0, 15); } }
Alfheim
src\main\java\dev\redstudio\alfheim\mixin\client\MinecraftMixin.java
package dev.redstudio.alfheim.mixin.client; import dev.redstudio.alfheim.api.ILightUpdatesProcessor; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.profiler.Profiler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; /// @author Luna Mira Lage (Desoroxxx) /// @since 1.0 @SideOnly(Side.CLIENT) @Mixin(Minecraft.class) public abstract class MinecraftMixin { @Shadow @Final public Profiler profiler; @Shadow public RenderGlobal renderGlobal; @Shadow private boolean isGamePaused; @Inject(method = "runTick", at = @At(value = "CONSTANT", args = "stringValue=level", shift = At.Shift.BEFORE)) private void onRunTick(final CallbackInfo callbackInfo) { profiler.endStartSection("processRenderGlobalLightUpdates"); if (!isGamePaused) ((ILightUpdatesProcessor) renderGlobal).alfheim$processLightUpdates(); } }
Alfheim
src\main\java\dev\redstudio\alfheim\mixin\client\RenderGlobalMixin.java
package dev.redstudio.alfheim.mixin.client; import dev.redstudio.alfheim.api.ILightUpdatesProcessor; import dev.redstudio.alfheim.utils.DeduplicatedLongQueue; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.client.renderer.chunk.ChunkRenderDispatcher; import net.minecraft.util.math.BlockPos; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Set; import static dev.redstudio.alfheim.Alfheim.*; import static net.minecraft.util.math.BlockPos.*; /// @author Luna Mira Lage (Desoroxxx) /// @since 1.0 @SideOnly(Side.CLIENT) @Mixin(RenderGlobal.class) public abstract class RenderGlobalMixin implements ILightUpdatesProcessor { @Unique private final DeduplicatedLongQueue alfheim$lightUpdatesQueue = new DeduplicatedLongQueue(8192); @Shadow private ChunkRenderDispatcher renderDispatcher; @Shadow protected abstract void markBlocksForUpdate(int minX, int minY, int minZ, int maxX, int maxY, int maxZ, boolean updateImmediately); /// @author Luna Mira Lage (Desoroxxx) /// @reason Use a deduplicated long queue instead of a set /// @since 1.5 @Overwrite public void notifyLightSet(final BlockPos blockPos) { alfheim$lightUpdatesQueue.enqueue(blockPos.toLong()); } /// Disable vanilla code to replace it with [#alfheim$processLightUpdates] /// /// @since 1.0 @Redirect(method = "updateClouds", at = @At(value = "INVOKE", target = "Ljava/util/Set;isEmpty()Z", ordinal = 0)) private boolean disableVanillaLightUpdates(final Set<BlockPos> instance) { return true; } /// Fixes [MC-80966](https://bugs.mojang.com/browse/MC-80966) by not checking if the chunk is empty or not. /// /// It also improves performance by using a [DeduplicatedLongQueue] instead of a set. /// This removes the need to use an expensive iterator. /// It also reduces memory usage and GC pressure by using long primitives instead of a [BlockPos] object. /// /// Another performance improvement is using || instead of && allowing to skip earlier when there is nothing to update. /// /// @since 1.0 @Override public void alfheim$processLightUpdates() { if (alfheim$lightUpdatesQueue.isEmpty() || (!IS_NOTHIRIUM_LOADED && !IS_VINTAGIUM_LOADED && !IS_CELERITAS_LOADED && renderDispatcher.hasNoFreeRenderBuilders())) return; while (!alfheim$lightUpdatesQueue.isEmpty()) { final long longPos = alfheim$lightUpdatesQueue.dequeue(); final int x = (int) (longPos << 64 - X_SHIFT - NUM_X_BITS >> 64 - NUM_X_BITS); final int y = (int) (longPos << 64 - Y_SHIFT - NUM_Y_BITS >> 64 - NUM_Y_BITS); final int z = (int) (longPos << 64 - NUM_Z_BITS >> 64 - NUM_Z_BITS); markBlocksForUpdate(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1, false); } alfheim$lightUpdatesQueue.newDeduplicationSet(); } }
almostpacked
src\main\java\com\almostreliable\almostpacked\AlmostPacked.java
package com.almostreliable.almostpacked; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.util.stream.Stream; @SuppressWarnings("CallToPrintStackTrace") public final class AlmostPacked { static final Gson GSON = new Gson(); static final Gson PRETTY_GSON = new GsonBuilder().setPrettyPrinting().create(); private static final String VERSION = AlmostPacked.class.getPackage().getImplementationVersion(); @SuppressWarnings({"NonConstantFieldWithUpperCaseName", "RedundantFieldInitialization"}) private static String FLAG = null; private static boolean SHOULD_FAIL = false; private AlmostPacked() {} public static void main(String... args) { System.out.println(); System.out.println("AlmostPacked v" + VERSION); System.out.println("Author: Almost Reliable"); // help for invalid usage if (args.length != 1 || Stream.of("-m", "--merge", "-p", "--push").noneMatch(args[0]::equals)) { System.out.println("\nNot enough arguments provided!"); System.out.println("Usage: java -jar AlmostPacked.jar <flag>"); System.out.println("Flags:"); System.out.println(" -m, --merge\t\texecutes the post-merge tasks"); System.out.println(" -p, --push\t\texecutes the pre-push tasks"); System.exit(1); } FLAG = args[0]; var startTime = System.currentTimeMillis(); var fileProcessor = new FileProcessor(); try { fileProcessor.readConfig(); printHeader("Processing..."); fileProcessor.readFiles(); fileProcessor.readDirectories(); fileProcessor.readMods(); var packVerifier = new PackValidator(fileProcessor); packVerifier.handleSyncing(); packVerifier.validate(); } catch (IOException e) { System.out.println("\nERROR: " + e.getMessage()); e.printStackTrace(); System.exit(1); } var elapsedTime = (System.currentTimeMillis() - startTime) / 1_000F; printHeader("Done! " + String.format("Duration: %.2fs", elapsedTime)); if (fileProcessor.getConfig().failOnChange && SHOULD_FAIL) { printHeader("Hook failed because the sync file was changed!\nReview the changes."); System.exit(1); } } static void abort(String message) { System.out.println(message); System.out.println("Aborting..."); } static void printHeader(String message) { System.out.println("\n\n############################################"); System.out.println(message + "\n"); } static void shouldFail() { SHOULD_FAIL = true; } static boolean isMerging() { assert FLAG != null; return FLAG.equals("-m") || FLAG.equals("--merge"); } static boolean isPushing() { assert FLAG != null; return FLAG.equals("-p") || FLAG.equals("--push"); } }
almostpacked
src\main\java\com\almostreliable\almostpacked\Config.java
package com.almostreliable.almostpacked; class Config { String fileName; boolean subFolder; boolean prettyJson; int concurrentDownloads; boolean failOnChange; boolean devMode; }
almostpacked
src\main\java\com\almostreliable\almostpacked\FileProcessor.java
package com.almostreliable.almostpacked; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.io.*; import java.text.SimpleDateFormat; import java.util.Comparator; import java.util.Locale; import java.util.stream.StreamSupport; class FileProcessor { private final File dir; private Config config; private File modDir; private File mcInstanceFile; private File syncFile; private JsonObject mcInstance; private JsonArray installedMods; private JsonArray syncedMods; FileProcessor() { dir = new File("."); System.out.println("Working directory: " + dir.getAbsoluteFile().getParentFile()); } void readConfig() throws IOException { AlmostPacked.printHeader("Reading config..."); var subFolder = false; if (!new File(dir, "minecraftinstance.json").exists()) { if (!new File(getParentDir(dir), "minecraftinstance.json").exists()) { AlmostPacked.abort("Not running in a valid Minecraft instance!"); System.exit(1); } subFolder = true; } var configFile = getOrCreateFile( "config.json", """ { "fileName": "sync", "subFolder": %s, "prettyJson": true, "concurrentDownloads": 10, "failOnChange": true, "devMode": false } """.formatted(subFolder) ); config = readFile(configFile, Config.class); } void readFiles() throws IOException { System.out.println("Searching 'minecraftinstance.json' file..."); mcInstanceFile = new File(getDirByConfig(), "minecraftinstance.json"); if (!mcInstanceFile.exists()) { AlmostPacked.abort("File 'minecraftinstance.json' does not exist!"); } System.out.println("Found 'minecraftinstance.json' file!"); mcInstance = readFile(mcInstanceFile, JsonObject.class); System.out.println(); syncFile = getOrCreateFile(config.fileName + ".json", "[]"); System.out.println(); } void readDirectories() { System.out.println("Searching 'mods' directory..."); modDir = new File(getDirByConfig(), "mods"); if (modDir.exists() && !modDir.isDirectory()) { AlmostPacked.abort("Directory 'mods' exists but is a file!"); System.exit(1); } if (!modDir.exists()) { System.out.println("Directory 'mods' does not exist! Creating..."); if (!modDir.mkdir()) { AlmostPacked.abort("Directory 'mods' couldn't be created!"); System.exit(1); } } System.out.println("Found 'mods' directory!"); System.out.println(); } void readMods() throws IOException { System.out.println("Reading installed mods..."); installedMods = mcInstance.getAsJsonArray("installedAddons"); if (installedMods == null) { AlmostPacked.abort("File 'minecraftinstance.json' is invalid!"); System.exit(1); } if (installedMods.isEmpty() && AlmostPacked.isPushing()) { AlmostPacked.abort("No mods installed!"); System.exit(0); } installedMods = sortMods(installedMods); System.out.println("Found " + installedMods.size() + " installed mods!"); System.out.println(); syncedMods = readFile(syncFile, JsonArray.class); syncedMods = sortMods(syncedMods); System.out.println("Found " + syncedMods.size() + " synced mods!"); } void overwriteInstance() throws IOException { var sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSXXX", Locale.getDefault()); var time = sdf.format(System.currentTimeMillis()); mcInstance.addProperty("lastPreviousMatchUpdate", time); mcInstance.addProperty("lastRefreshAttempt", time); mcInstance.add("installedAddons", syncedMods); writeFile(mcInstanceFile, mcInstance, false); } void overwriteSync(JsonArray content) throws IOException { writeFile(syncFile, sortMods(content), config.prettyJson); AlmostPacked.shouldFail(); } private JsonArray sortMods(JsonArray mods) { var sortedModList = StreamSupport.stream(mods.spliterator(), false) .map(JsonElement::getAsJsonObject) .sorted(Comparator.comparingInt( o -> o.get("addonID").getAsInt())) .toList(); var sortedMods = new JsonArray(); for (var mod : sortedModList) { sortedMods.add(mod); } return sortedMods; } private File getParentDir(File dir) { return dir.getAbsoluteFile().getParentFile().getParentFile(); } private File getOrCreateFile(String fileName, String defaultValue) throws IOException { System.out.println("Searching '" + fileName + "' file..."); var file = new File(dir, fileName); if (!file.exists()) { System.out.println("File '" + fileName + "' does not exist! Creating..."); if (!file.createNewFile()) { AlmostPacked.abort("File '" + fileName + "' couldn't be created!"); System.exit(1); } try (var writer = new FileWriter(file)) { writer.write(defaultValue); } } System.out.println("Found '" + fileName + "' file!"); return file; } private <T> T readFile(File file, Class<T> clazz) throws FileNotFoundException { System.out.println("Reading '" + file.getName() + "' file..."); var content = AlmostPacked.GSON.fromJson(new FileReader(file), clazz); System.out.println("Read '" + file.getName() + "' file!"); return content; } private void writeFile(File file, JsonElement content, boolean pretty) throws IOException { var writer = new FileWriter(file); if (pretty) { AlmostPacked.PRETTY_GSON.toJson(content, writer); } else { AlmostPacked.GSON.toJson(content, writer); } writer.flush(); writer.close(); } private File getDirByConfig() { if (config.subFolder) { return getParentDir(dir); } return dir; } Config getConfig() { return config; } File getModDir() { return modDir; } JsonArray getInstalledMods() { return installedMods; } JsonArray getSyncedMods() { return syncedMods; } }
almostpacked
src\main\java\com\almostreliable\almostpacked\ModData.java
package com.almostreliable.almostpacked; class ModData { AddonFile installedFile; @Override public int hashCode() { return installedFile.hashCode(); } @Override public boolean equals(Object o) { return o instanceof ModData modData && modData.installedFile != null && modData.installedFile.equals(installedFile); } @Override public String toString() { return installedFile == null ? "NO FILE" : installedFile.toString(); } @SuppressWarnings({"unused", "FieldNamingConvention", "java:S116"}) public static class AddonFile { private int id; private String downloadUrl; private String fileName; private int projectId; private String FileNameOnDisk; @Override public int hashCode() { var result = id; result = 31 * result + downloadUrl.hashCode(); result = 31 * result + fileName.hashCode(); result = 31 * result + projectId; result = 31 * result + FileNameOnDisk.hashCode(); return result; } @Override public boolean equals(Object o) { return this == o || o instanceof AddonFile addonFile && id == addonFile.id && downloadUrl.equals(addonFile.downloadUrl) && fileName.equals(addonFile.fileName) && projectId == addonFile.projectId && FileNameOnDisk.equals(addonFile.FileNameOnDisk); } @Override public String toString() { return projectId + " | " + FileNameOnDisk; } String getDownloadUrl() { return downloadUrl.replace(" ", "%20"); } String getFileName() { return fileName; } String getFileNameOnDisk() { return FileNameOnDisk; } int getProjectId() { return projectId; } boolean isDisabled() { return FileNameOnDisk.endsWith(".disabled"); } } }
almostpacked
src\main\java\com\almostreliable\almostpacked\PackValidator.java
package com.almostreliable.almostpacked; import com.almostreliable.almostpacked.ModData.AddonFile; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; // download logic credits: Vazkii @SuppressWarnings("CallToPrintStackTrace") class PackValidator { private final FileProcessor fileProcessor; private final File modDir; private final Config config; private final List<String> removalFilter; private ExecutorService executor; private int downloadCount; private ModData[] toValidate; PackValidator(FileProcessor fileProcessor) { this.fileProcessor = fileProcessor; modDir = fileProcessor.getModDir(); config = fileProcessor.getConfig(); removalFilter = new LinkedList<>(); } void handleSyncing() throws IOException { AlmostPacked.printHeader("Checking for sync requirements..."); var installedMods = fileProcessor.getInstalledMods(); var installedModData = AlmostPacked.GSON.fromJson(installedMods, ModData[].class); if (fileProcessor.getSyncedMods().isEmpty()) { System.out.println("This appears to be the first run of the tool.\nInitial data will be written."); fileProcessor.overwriteSync(installedMods); System.out.println("All mods have been written to the '" + config.fileName + ".json' file!"); toValidate = installedModData; return; } var syncedMods = fileProcessor.getSyncedMods(); var syncedModData = AlmostPacked.GSON.fromJson(syncedMods, ModData[].class); if (Arrays.equals(installedModData, syncedModData)) { System.out.println("No sync changes detected!"); if (AlmostPacked.isMerging()) { toValidate = installedModData; } return; } if (AlmostPacked.isMerging()) { System.out.println("Changes in the sync file detected! Updating instance..."); fileProcessor.overwriteInstance(); toValidate = syncedModData; return; } if (AlmostPacked.isPushing()) { System.out.println("Changes in the instance detected! Updating sync file..."); printDevLog(installedMods.size() + " mods found inside 'minecraftinstance.json':"); var installedContainer = createContainer(installedMods, installedModData); printDevLog("\n"); printDevLog(syncedMods.size() + " mods found inside '" + config.fileName + ".json':"); var syncedContainer = createContainer(syncedMods, syncedModData); Set<Integer> modsToRemove = new HashSet<>(syncedContainer.keySet()); installedContainer.forEach((projectId, installedMod) -> { modsToRemove.remove(projectId); var syncedMod = syncedContainer.get(projectId); if (syncedMod == null || !syncedMod.modData().equals(installedMod.modData())) { syncedContainer.put(projectId, installedMod); } }); modsToRemove.forEach(syncedContainer::remove); printDevLog("\n"); printDevLog(syncedContainer.size() + " mods after syncing:"); syncedContainer.forEach((projectId, mod) -> printDevLog("\t - " + mod.modData())); var syncArray = new JsonArray(); syncedContainer.values().forEach(mod -> syncArray.add(mod.json)); fileProcessor.overwriteSync(syncArray); } } void validate() { if (toValidate == null) return; AlmostPacked.printHeader("Checking pack completeness..."); System.out.println("Downloading missing mods..."); downloadMissingMods(); System.out.println(); System.out.println("Deleting removed mods..."); deleteRemovedMods(); } private Map<Integer, ModDataContainer> createContainer(JsonArray mods, ModData... modData) { Map<Integer, ModDataContainer> container = new HashMap<>(); for (var i = 0; i < mods.size(); i++) { var modDataContainer = new ModDataContainer(mods.get(i), modData[i]); container.put(modDataContainer.modData().installedFile.getProjectId(), modDataContainer); printDevLog("\t - " + modDataContainer.modData()); } return container; } @SuppressWarnings("java:S2142") private void downloadMissingMods() { executor = Executors.newFixedThreadPool(config.concurrentDownloads); var startTime = System.currentTimeMillis(); Set<AddonFile> toDownload = new HashSet<>(); Set<File> toEnable = new HashSet<>(); Set<File> toDisable = new HashSet<>(); for (var data : toValidate) { var modFile = data.installedFile; if (modFile == null) continue; var fileName = modFile.getFileNameOnDisk(); var file = new File(modDir, fileName); if (file.exists()) { removalFilter.add(fileName); continue; } if (modFile.isDisabled()) { var enabledFile = new File(modDir, modFile.getFileName()); toDisable.add(enabledFile); if (enabledFile.exists()) continue; } else { var disabledFile = new File(modDir, modFile.getFileName() + ".disabled"); if (disabledFile.exists()) { toEnable.add(disabledFile); continue; } } toDownload.add(modFile); } toDownload.forEach(mod -> download(new File(modDir, mod.getFileName()), mod.getDownloadUrl())); try { executor.shutdown(); // noinspection ResultOfMethodCallIgnored executor.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException e) { System.out.println("Downloads were interrupted!"); e.printStackTrace(); } if (downloadCount == 0) { System.out.println("No mods needed to be downloaded!"); } else { var elapsedTime = (System.currentTimeMillis() - startTime) / 1_000F; System.out.printf("Downloaded %d mods! Duration: %.2fs%n", downloadCount, elapsedTime); } toEnable.forEach(modFile -> { var enabled = new File(modDir, modFile.getName().replace(".disabled", "")); if (modFile.renameTo(enabled)) { System.out.println("Enabled " + enabled.getName()); } else { System.out.println("Failed to enable " + enabled.getName()); } removalFilter.add(enabled.getName()); }); toDisable.forEach(modFile -> { var disabled = new File(modDir, modFile.getName() + ".disabled"); if (modFile.renameTo(disabled)) { System.out.println("Disabled " + modFile.getName()); } else { System.out.println("Failed to disable " + modFile.getName()); } removalFilter.add(disabled.getName()); }); } private void download(File modFile, String downloadUrl) { Runnable downloadTask = () -> { var modName = modFile.getName(); System.out.println("Downloading " + modName); try { var time = System.currentTimeMillis(); var url = new URL(downloadUrl); var out = new FileOutputStream(modFile); var connection = url.openConnection(); var in = connection.getInputStream(); var buf = new byte[4_096]; var read = 0; do { out.write(buf, 0, read); read = in.read(buf); } while (read > 0); out.close(); in.close(); var secs = (System.currentTimeMillis() - time) / 1_000F; System.out.printf("Downloaded %s (took %.2fs)%n", modName, secs); } catch (Exception e) { System.out.println("Failed to download " + modName); e.printStackTrace(); } }; removalFilter.add(modFile.getName()); downloadCount++; executor.submit(downloadTask); } private void deleteRemovedMods() { var toRemove = modDir.listFiles(f -> !f.isDirectory() && !removalFilter.contains(f.getName())); if (toRemove == null || toRemove.length == 0) { System.out.println("No mods needed to be removed!"); return; } var removed = 0; for (var mod : toRemove) { System.out.println("Removing " + mod.getName()); try { Files.delete(mod.toPath()); System.out.println("Removed " + mod.getName()); removed++; } catch (IOException e) { System.out.println("Failed to download " + mod.getName()); } } System.out.println("Deleted " + removed + " old mods!"); } private void printDevLog(String message) { if (!config.devMode) return; System.out.println(message); } private record ModDataContainer(JsonElement json, ModData modData) {} }
alternate-current
build.gradle
plugins { id 'net.fabricmc.fabric-loom-remap' version '1.14-SNAPSHOT' id 'maven-publish' } base { archivesName = "${project.archives_base_name}-mc${project.minecraft_version}" } version = project.mod_version group = project.maven_group repositories { } dependencies { minecraft "com.mojang:minecraft:${project.minecraft_version}" mappings loom.officialMojangMappings() modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" } processResources { inputs.property "version", project.version filesMatching("fabric.mod.json") { expand "version": project.version } } tasks.withType(JavaCompile).configureEach { it.options.release = 21 } java { // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task // if it is present. // If you remove this line, sources will not be generated. withSourcesJar() sourceCompatibility = JavaVersion.VERSION_21 targetCompatibility = JavaVersion.VERSION_21 } jar { from("LICENSE") { rename { "${it}_${project.base.archivesName.get()}"} } } // configure the maven publication publishing { publications { mavenJava(MavenPublication) { from components.java } } // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. repositories { } }
alternate-current
settings.gradle
pluginManagement { repositories { maven { name = 'Fabric' url = 'https://maven.fabricmc.net/' } mavenCentral() gradlePluginPortal() } }
alternate-current
src\main\resources\alternate-current.mixins.json
{ "required": true, "minVersion": "0.8", "package": "alternate.current.mixin", "compatibilityLevel": "JAVA_16", "mixins": [ "CommandsMixin", "ExperimentalRedstoneUtilsMixin", "MinecraftServerMixin", "RedStoneWireBlockMixin", "ServerLevelMixin" ], "injectors": { "defaultRequire": 1 } }
alternate-current
src\main\resources\fabric.mod.json
{ "schemaVersion": 1, "id": "alternate-current", "version": "${version}", "name": "Alternate Current", "description": "An efficient and non-locational redstone dust implementation.", "authors": [ "Space Walker" ], "contact": { "homepage": "https://modrinth.com/mod/alternate-current", "sources": "https://github.com/SpaceWalkerRS/alternate-current", "issues": "https://github.com/SpaceWalkerRS/alternate-current/issues" }, "license": "MIT Licence", "icon": "assets/alternate/current/icon.png", "environment": "*", "entrypoints": { "main": [ "alternate.current.AlternateCurrentMod" ] }, "mixins": [ "alternate-current.mixins.json" ], "depends": { "minecraft": "1.21.x" }, "breaks": { "alternate-current-plus": "*" }, "custom": { "modmenu": { "links": { "modmenu.discord": "https://discord.gg/EJC9zkX" } } } }
alternate-current
src\main\java\alternate\current\AlternateCurrentMod.java
package alternate.current; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import alternate.current.util.profiler.ACProfiler; import alternate.current.util.profiler.Profiler; import net.fabricmc.api.ModInitializer; public class AlternateCurrentMod implements ModInitializer { public static final String MOD_ID = "alternate-current"; public static final String MOD_NAME = "Alternate Current"; public static final String MOD_VERSION = "1.9.0"; public static final Logger LOGGER = LogManager.getLogger(MOD_NAME); public static final boolean DEBUG = false; public static boolean on = true; @Override public void onInitialize() { if (DEBUG) { LOGGER.warn(String.format("You are running a DEBUG version of %s!", MOD_NAME)); } } public static Profiler createProfiler() { return DEBUG ? new ACProfiler() : Profiler.DUMMY; } }