RoughlyEnoughItemsCore.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /*
  2. * Roughly Enough Items by Danielshe.
  3. * Licensed under the MIT License.
  4. */
  5. package me.shedaniel.rei;
  6. import com.google.common.collect.Lists;
  7. import com.google.common.collect.Maps;
  8. import me.shedaniel.cloth.api.ClientUtils;
  9. import me.shedaniel.cloth.hooks.ClothClientHooks;
  10. import me.shedaniel.rei.api.*;
  11. import me.shedaniel.rei.api.plugins.REIPluginV0;
  12. import me.shedaniel.rei.client.*;
  13. import me.shedaniel.rei.gui.ContainerScreenOverlay;
  14. import me.shedaniel.rei.gui.widget.ItemListOverlay;
  15. import me.shedaniel.rei.listeners.RecipeBookButtonWidgetHooks;
  16. import me.shedaniel.rei.listeners.RecipeBookGuiHooks;
  17. import net.fabricmc.api.ClientModInitializer;
  18. import net.fabricmc.fabric.api.network.ClientSidePacketRegistry;
  19. import net.fabricmc.loader.api.FabricLoader;
  20. import net.fabricmc.loader.api.ModContainer;
  21. import net.minecraft.client.MinecraftClient;
  22. import net.minecraft.client.gui.Element;
  23. import net.minecraft.client.gui.screen.Screen;
  24. import net.minecraft.client.gui.screen.ingame.AbstractContainerScreen;
  25. import net.minecraft.client.gui.screen.ingame.CraftingTableScreen;
  26. import net.minecraft.client.gui.screen.ingame.CreativeInventoryScreen;
  27. import net.minecraft.client.gui.screen.ingame.InventoryScreen;
  28. import net.minecraft.client.gui.screen.recipebook.RecipeBookGhostSlots;
  29. import net.minecraft.client.gui.screen.recipebook.RecipeBookProvider;
  30. import net.minecraft.client.gui.screen.recipebook.RecipeBookWidget;
  31. import net.minecraft.client.gui.widget.TextFieldWidget;
  32. import net.minecraft.client.gui.widget.TexturedButtonWidget;
  33. import net.minecraft.client.resource.language.I18n;
  34. import net.minecraft.container.CraftingTableContainer;
  35. import net.minecraft.container.Slot;
  36. import net.minecraft.item.ItemStack;
  37. import net.minecraft.item.Items;
  38. import net.minecraft.recipe.Ingredient;
  39. import net.minecraft.text.LiteralText;
  40. import net.minecraft.util.ActionResult;
  41. import net.minecraft.util.Identifier;
  42. import org.apache.logging.log4j.LogManager;
  43. import org.apache.logging.log4j.Logger;
  44. import java.util.LinkedList;
  45. import java.util.List;
  46. import java.util.Map;
  47. import java.util.Optional;
  48. import java.util.concurrent.CompletableFuture;
  49. import java.util.concurrent.ExecutorService;
  50. import java.util.concurrent.Executors;
  51. public class RoughlyEnoughItemsCore implements ClientModInitializer {
  52. public static final Logger LOGGER;
  53. private static final RecipeHelper RECIPE_HELPER = new RecipeHelperImpl();
  54. private static final PluginDisabler PLUGIN_DISABLER = new PluginDisablerImpl();
  55. private static final ItemRegistry ITEM_REGISTRY = new ItemRegistryImpl();
  56. private static final DisplayHelper DISPLAY_HELPER = new DisplayHelperImpl();
  57. private static final Map<Identifier, REIPluginEntry> plugins = Maps.newHashMap();
  58. private static final ExecutorService SYNC_RECIPES = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "REI-SyncRecipes"));
  59. private static ConfigManagerImpl configManager;
  60. static {
  61. LOGGER = LogManager.getFormatterLogger("REI");
  62. }
  63. public static RecipeHelper getRecipeHelper() {
  64. return RECIPE_HELPER;
  65. }
  66. public static me.shedaniel.rei.api.ConfigManager getConfigManager() {
  67. return configManager;
  68. }
  69. public static ItemRegistry getItemRegisterer() {
  70. return ITEM_REGISTRY;
  71. }
  72. public static PluginDisabler getPluginDisabler() {
  73. return PLUGIN_DISABLER;
  74. }
  75. public static DisplayHelper getDisplayHelper() {
  76. return DISPLAY_HELPER;
  77. }
  78. /**
  79. * Registers a REI plugin
  80. *
  81. * @param identifier the identifier of the plugin
  82. * @param plugin the plugin instance
  83. * @return the plugin itself
  84. * @deprecated Check REI wiki
  85. */
  86. @Deprecated
  87. public static REIPluginEntry registerPlugin(REIPluginEntry plugin) {
  88. plugins.put(plugin.getPluginIdentifier(), plugin);
  89. RoughlyEnoughItemsCore.LOGGER.info("[REI] Registered plugin %s from %s", plugin.getPluginIdentifier().toString(), plugin.getClass().getSimpleName());
  90. return plugin;
  91. }
  92. public static List<REIPluginEntry> getPlugins() {
  93. return new LinkedList<>(plugins.values());
  94. }
  95. public static Optional<Identifier> getPluginIdentifier(REIPluginEntry plugin) {
  96. for (Identifier identifier : plugins.keySet())
  97. if (identifier != null && plugins.get(identifier).equals(plugin))
  98. return Optional.of(identifier);
  99. return Optional.empty();
  100. }
  101. public static boolean hasPermissionToUsePackets() {
  102. try {
  103. MinecraftClient.getInstance().getNetworkHandler().getCommandSource().hasPermissionLevel(0);
  104. return hasOperatorPermission() && canUsePackets();
  105. } catch (NullPointerException e) {
  106. return true;
  107. }
  108. }
  109. public static boolean hasOperatorPermission() {
  110. try {
  111. return MinecraftClient.getInstance().getNetworkHandler().getCommandSource().hasPermissionLevel(1);
  112. } catch (NullPointerException e) {
  113. return true;
  114. }
  115. }
  116. public static boolean canUsePackets() {
  117. return ClientSidePacketRegistry.INSTANCE.canServerReceive(RoughlyEnoughItemsNetwork.CREATE_ITEMS_PACKET) && ClientSidePacketRegistry.INSTANCE.canServerReceive(RoughlyEnoughItemsNetwork.DELETE_ITEMS_PACKET);
  118. }
  119. @Override
  120. public void onInitializeClient() {
  121. configManager = new ConfigManagerImpl();
  122. registerClothEvents();
  123. discoverPluginEntries();
  124. FabricLoader.getInstance().getAllMods().stream().map(ModContainer::getMetadata).filter(metadata -> metadata.containsCustomElement("roughlyenoughitems:plugins")).forEach(modMetadata -> {
  125. RoughlyEnoughItemsCore.LOGGER.error("[REI] REI plugin from " + modMetadata.getId() + " is not loaded because it is too old!");
  126. });
  127. ClientSidePacketRegistry.INSTANCE.register(RoughlyEnoughItemsNetwork.CREATE_ITEMS_MESSAGE_PACKET, (packetContext, packetByteBuf) -> {
  128. ItemStack stack = packetByteBuf.readItemStack();
  129. String player = packetByteBuf.readString(32767);
  130. packetContext.getPlayer().addChatMessage(new LiteralText(I18n.translate("text.rei.cheat_items").replaceAll("\\{item_name}", ItemListOverlay.tryGetItemStackName(stack.copy())).replaceAll("\\{item_count}", stack.copy().getCount() + "").replaceAll("\\{player_name}", player)), false);
  131. });
  132. ClientSidePacketRegistry.INSTANCE.register(RoughlyEnoughItemsNetwork.NOT_ENOUGH_ITEMS_PACKET, (packetContext, packetByteBuf) -> {
  133. Screen currentScreen = MinecraftClient.getInstance().currentScreen;
  134. if (currentScreen instanceof CraftingTableScreen) {
  135. RecipeBookWidget recipeBookGui = ((RecipeBookProvider) currentScreen).getRecipeBookGui();
  136. RecipeBookGhostSlots ghostSlots = ((RecipeBookGuiHooks) recipeBookGui).rei_getGhostSlots();
  137. ghostSlots.reset();
  138. List<List<ItemStack>> input = Lists.newArrayList();
  139. int mapSize = packetByteBuf.readInt();
  140. for (int i = 0; i < mapSize; i++) {
  141. List<ItemStack> list = Lists.newArrayList();
  142. int count = packetByteBuf.readInt();
  143. for (int j = 0; j < count; j++) {
  144. list.add(packetByteBuf.readItemStack());
  145. }
  146. input.add(list);
  147. }
  148. ghostSlots.addSlot(Ingredient.ofItems(Items.STONE), 381203812, 12738291);
  149. CraftingTableContainer container = ((CraftingTableScreen) currentScreen).getContainer();
  150. for (int i = 0; i < input.size(); i++) {
  151. List<ItemStack> stacks = input.get(i);
  152. if (!stacks.isEmpty()) {
  153. Slot slot = container.getSlot(i + container.getCraftingResultSlotIndex() + 1);
  154. ghostSlots.addSlot(Ingredient.ofStacks(stacks.toArray(new ItemStack[0])), slot.xPosition, slot.yPosition);
  155. }
  156. }
  157. }
  158. });
  159. }
  160. @SuppressWarnings("deprecation")
  161. private void discoverPluginEntries() {
  162. for (REIPluginEntry reiPlugin : FabricLoader.getInstance().getEntrypoints("rei_plugins", REIPluginEntry.class)) {
  163. try {
  164. if (!REIPluginV0.class.isAssignableFrom(reiPlugin.getClass()))
  165. throw new IllegalArgumentException("REI plugin is too old!");
  166. registerPlugin(reiPlugin);
  167. if (reiPlugin instanceof REIPluginV0)
  168. ((REIPluginV0) reiPlugin).onFirstLoad(getPluginDisabler());
  169. } catch (Exception e) {
  170. e.printStackTrace();
  171. RoughlyEnoughItemsCore.LOGGER.error("[REI] Can't load REI plugins from %s: %s", reiPlugin.getClass(), e.getLocalizedMessage());
  172. }
  173. }
  174. }
  175. private void registerClothEvents() {
  176. final Identifier recipeButtonTex = new Identifier("textures/gui/recipe_button.png");
  177. ClothClientHooks.SYNC_RECIPES.register((minecraftClient, recipeManager, synchronizeRecipesS2CPacket) -> {
  178. if (RoughlyEnoughItemsCore.getConfigManager().getConfig().registerRecipesInAnotherThread)
  179. CompletableFuture.runAsync(() -> ((RecipeHelperImpl) RoughlyEnoughItemsCore.getRecipeHelper()).recipesLoaded(recipeManager), SYNC_RECIPES);
  180. else
  181. ((RecipeHelperImpl) RoughlyEnoughItemsCore.getRecipeHelper()).recipesLoaded(recipeManager);
  182. });
  183. ClothClientHooks.SCREEN_ADD_BUTTON.register((minecraftClient, screen, abstractButtonWidget) -> {
  184. if (RoughlyEnoughItemsCore.getConfigManager().getConfig().disableRecipeBook && screen instanceof AbstractContainerScreen && abstractButtonWidget instanceof TexturedButtonWidget)
  185. if (((RecipeBookButtonWidgetHooks) abstractButtonWidget).rei_getTexture().equals(recipeButtonTex))
  186. return ActionResult.FAIL;
  187. return ActionResult.PASS;
  188. });
  189. ClothClientHooks.SCREEN_INIT_POST.register((minecraftClient, screen, screenHooks) -> {
  190. if (screen instanceof AbstractContainerScreen) {
  191. if (screen instanceof InventoryScreen && minecraftClient.interactionManager.hasCreativeInventory())
  192. return;
  193. ScreenHelper.setLastContainerScreen((AbstractContainerScreen<?>) screen);
  194. boolean alreadyAdded = false;
  195. for (Element element : Lists.newArrayList(screenHooks.cloth_getInputListeners()))
  196. if (ContainerScreenOverlay.class.isAssignableFrom(element.getClass()))
  197. if (alreadyAdded)
  198. screenHooks.cloth_getInputListeners().remove(element);
  199. else
  200. alreadyAdded = true;
  201. if (!alreadyAdded)
  202. screenHooks.cloth_getInputListeners().add(ScreenHelper.getLastOverlay(true, false));
  203. }
  204. });
  205. ClothClientHooks.SCREEN_RENDER_POST.register((minecraftClient, screen, i, i1, v) -> {
  206. if (screen instanceof AbstractContainerScreen)
  207. ScreenHelper.getLastOverlay().render(i, i1, v);
  208. });
  209. ClothClientHooks.SCREEN_MOUSE_CLICKED.register((minecraftClient, screen, v, v1, i) -> {
  210. if (screen instanceof CreativeInventoryScreen)
  211. if (ScreenHelper.isOverlayVisible() && ScreenHelper.getLastOverlay().mouseClicked(v, v1, i)) {
  212. screen.setFocused(ScreenHelper.getLastOverlay());
  213. if (i == 0)
  214. screen.setDragging(true);
  215. return ActionResult.SUCCESS;
  216. }
  217. return ActionResult.PASS;
  218. });
  219. ClothClientHooks.SCREEN_MOUSE_SCROLLED.register((minecraftClient, screen, v, v1, v2) -> {
  220. if (screen instanceof AbstractContainerScreen)
  221. if (ScreenHelper.isOverlayVisible() && ScreenHelper.getLastOverlay().isInside(ClientUtils.getMouseLocation()) && ScreenHelper.getLastOverlay().mouseScrolled(v, v1, v2))
  222. return ActionResult.SUCCESS;
  223. return ActionResult.PASS;
  224. });
  225. ClothClientHooks.SCREEN_CHAR_TYPED.register((minecraftClient, screen, character, keyCode) -> {
  226. if (screen instanceof AbstractContainerScreen)
  227. if (ScreenHelper.getLastOverlay().charTyped(character, keyCode))
  228. return ActionResult.SUCCESS;
  229. return ActionResult.PASS;
  230. });
  231. ClothClientHooks.SCREEN_LATE_RENDER.register((minecraftClient, screen, i, i1, v) -> {
  232. if (!ScreenHelper.isOverlayVisible())
  233. return;
  234. if (screen instanceof AbstractContainerScreen)
  235. ScreenHelper.getLastOverlay().lateRender(i, i1, v);
  236. });
  237. ClothClientHooks.SCREEN_KEY_PRESSED.register((minecraftClient, screen, i, i1, i2) -> {
  238. if (screen.getFocused() != null && screen.getFocused() instanceof TextFieldWidget || (screen.getFocused() instanceof RecipeBookWidget && ((RecipeBookGuiHooks) screen.getFocused()).rei_getSearchField() != null && ((RecipeBookGuiHooks) screen.getFocused()).rei_getSearchField().isFocused()))
  239. return ActionResult.PASS;
  240. if (screen instanceof AbstractContainerScreen)
  241. if (ScreenHelper.getLastOverlay().keyPressed(i, i1, i2))
  242. return ActionResult.SUCCESS;
  243. return ActionResult.PASS;
  244. });
  245. }
  246. }