RecipeHelperImpl.java 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. /*
  2. * This file is licensed under the MIT License, part of Roughly Enough Items.
  3. * Copyright (c) 2018, 2019, 2020 shedaniel
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6. * of this software and associated documentation files (the "Software"), to deal
  7. * in the Software without restriction, including without limitation the rights
  8. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in all
  13. * copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. * SOFTWARE.
  22. */
  23. package me.shedaniel.rei.impl;
  24. import com.google.common.collect.Lists;
  25. import com.google.common.collect.Maps;
  26. import com.google.common.collect.Sets;
  27. import me.shedaniel.math.Rectangle;
  28. import me.shedaniel.rei.RoughlyEnoughItemsCore;
  29. import me.shedaniel.rei.api.*;
  30. import me.shedaniel.rei.api.fluid.FluidSupportProvider;
  31. import me.shedaniel.rei.api.plugins.REIPluginV0;
  32. import me.shedaniel.rei.api.subsets.SubsetsRegistry;
  33. import me.shedaniel.rei.impl.subsets.SubsetsRegistryImpl;
  34. import me.shedaniel.rei.utils.CollectionUtils;
  35. import net.fabricmc.api.EnvType;
  36. import net.fabricmc.api.Environment;
  37. import net.minecraft.client.gui.screen.ingame.ContainerScreen;
  38. import net.minecraft.recipe.Recipe;
  39. import net.minecraft.recipe.RecipeManager;
  40. import net.minecraft.util.ActionResult;
  41. import net.minecraft.util.Identifier;
  42. import net.minecraft.util.Util;
  43. import org.jetbrains.annotations.ApiStatus;
  44. import java.util.*;
  45. import java.util.function.Consumer;
  46. import java.util.function.Function;
  47. import java.util.function.Predicate;
  48. import java.util.stream.Collectors;
  49. @ApiStatus.Internal
  50. @Environment(EnvType.CLIENT)
  51. public class RecipeHelperImpl implements RecipeHelper {
  52. private static final Comparator<DisplayVisibilityHandler> VISIBILITY_HANDLER_COMPARATOR;
  53. @SuppressWarnings("rawtypes")
  54. private static final Comparator<Recipe> RECIPE_COMPARATOR = Comparator.comparing((Recipe o) -> o.getId().getNamespace()).thenComparing(o -> o.getId().getPath());
  55. static {
  56. Comparator<DisplayVisibilityHandler> comparator = Comparator.comparingDouble(DisplayVisibilityHandler::getPriority);
  57. VISIBILITY_HANDLER_COMPARATOR = comparator.reversed();
  58. }
  59. private final List<AutoTransferHandler> autoTransferHandlers = Lists.newLinkedList();
  60. private final List<RecipeFunction> recipeFunctions = Lists.newLinkedList();
  61. private final List<ScreenClickArea> screenClickAreas = Lists.newLinkedList();
  62. private final int[] recipeCount = {0};
  63. private final Map<Identifier, List<RecipeDisplay>> recipeCategoryListMap = Maps.newLinkedHashMap();
  64. private final Map<RecipeCategory<?>, Identifier> categories = Maps.newLinkedHashMap();
  65. private final Map<Identifier, RecipeCategory<?>> reversedCategories = Maps.newHashMap();
  66. private final Map<Identifier, ButtonAreaSupplier> autoCraftAreaSupplierMap = Maps.newLinkedHashMap();
  67. private final Map<Identifier, List<List<EntryStack>>> categoryWorkingStations = Maps.newLinkedHashMap();
  68. private final List<DisplayVisibilityHandler> displayVisibilityHandlers = Lists.newLinkedList();
  69. private final List<LiveRecipeGenerator<RecipeDisplay>> liveRecipeGenerators = Lists.newLinkedList();
  70. private RecipeManager recipeManager;
  71. private boolean arePluginsLoading = false;
  72. @Override
  73. public List<EntryStack> findCraftableEntriesByItems(List<EntryStack> inventoryItems) {
  74. List<EntryStack> craftables = new ArrayList<>();
  75. for (List<RecipeDisplay> value : recipeCategoryListMap.values())
  76. for (RecipeDisplay recipeDisplay : Lists.newArrayList(value)) {
  77. int slotsCraftable = 0;
  78. List<List<EntryStack>> requiredInput = recipeDisplay.getRequiredEntries();
  79. for (List<EntryStack> slot : requiredInput) {
  80. if (slot.isEmpty()) {
  81. slotsCraftable++;
  82. continue;
  83. }
  84. back:
  85. for (EntryStack possibleType : inventoryItems) {
  86. for (EntryStack slotPossible : slot)
  87. if (possibleType.equals(slotPossible)) {
  88. slotsCraftable++;
  89. break back;
  90. }
  91. }
  92. }
  93. if (slotsCraftable == recipeDisplay.getRequiredEntries().size())
  94. craftables.addAll(recipeDisplay.getOutputEntries());
  95. }
  96. return craftables.stream().distinct().collect(Collectors.toList());
  97. }
  98. @Override
  99. public boolean arePluginsLoading() {
  100. return arePluginsLoading;
  101. }
  102. @Override
  103. public void registerCategory(RecipeCategory<?> category) {
  104. categories.put(category, category.getIdentifier());
  105. reversedCategories.put(category.getIdentifier(), category);
  106. recipeCategoryListMap.put(category.getIdentifier(), Lists.newArrayList());
  107. categoryWorkingStations.put(category.getIdentifier(), Lists.newArrayList());
  108. }
  109. @SafeVarargs
  110. @Override
  111. public final void registerWorkingStations(Identifier category, List<EntryStack>... workingStations) {
  112. categoryWorkingStations.get(category).addAll(Arrays.asList(workingStations));
  113. }
  114. @Override
  115. public void registerWorkingStations(Identifier category, EntryStack... workingStations) {
  116. categoryWorkingStations.get(category).addAll(Arrays.stream(workingStations).map(Collections::singletonList).collect(Collectors.toList()));
  117. }
  118. @Override
  119. public List<List<EntryStack>> getWorkingStations(Identifier category) {
  120. return categoryWorkingStations.get(category);
  121. }
  122. @Deprecated
  123. @Override
  124. public void registerDisplay(Identifier categoryIdentifier, RecipeDisplay display) {
  125. if (!recipeCategoryListMap.containsKey(categoryIdentifier))
  126. return;
  127. recipeCount[0]++;
  128. recipeCategoryListMap.get(categoryIdentifier).add(display);
  129. }
  130. @Override
  131. public void registerDisplay(RecipeDisplay display) {
  132. Identifier identifier = Objects.requireNonNull(display.getRecipeCategory());
  133. if (!recipeCategoryListMap.containsKey(identifier))
  134. return;
  135. recipeCount[0]++;
  136. recipeCategoryListMap.get(identifier).add(display);
  137. }
  138. private void registerDisplay(Identifier categoryIdentifier, RecipeDisplay display, int index) {
  139. if (!recipeCategoryListMap.containsKey(categoryIdentifier))
  140. return;
  141. recipeCount[0]++;
  142. recipeCategoryListMap.get(categoryIdentifier).add(index, display);
  143. }
  144. @Override
  145. public Map<RecipeCategory<?>, List<RecipeDisplay>> buildMapFor(ClientHelper.ViewSearchBuilder builder) {
  146. long start = Util.getMeasuringTimeNano();
  147. Set<Identifier> categories = builder.getCategories();
  148. List<EntryStack> recipesFor = builder.getRecipesFor();
  149. List<EntryStack> usagesFor = builder.getUsagesFor();
  150. Map<RecipeCategory<?>, List<RecipeDisplay>> result = Maps.newLinkedHashMap();
  151. for (Map.Entry<RecipeCategory<?>, Identifier> entry : this.categories.entrySet()) {
  152. RecipeCategory<?> category = entry.getKey();
  153. Identifier categoryId = entry.getValue();
  154. List<RecipeDisplay> allRecipesFromCategory = getAllRecipesFromCategory(category);
  155. Set<RecipeDisplay> set = Sets.newLinkedHashSet();
  156. if (categories.contains(categoryId)) {
  157. for (RecipeDisplay display : allRecipesFromCategory) {
  158. if (isDisplayVisible(display)) {
  159. set.add(display);
  160. }
  161. }
  162. if (!set.isEmpty()) {
  163. CollectionUtils.getOrPutEmptyList(result, category).addAll(set);
  164. }
  165. continue;
  166. }
  167. for (RecipeDisplay display : allRecipesFromCategory) {
  168. if (!isDisplayVisible(display)) continue;
  169. if (!recipesFor.isEmpty()) {
  170. label:
  171. for (EntryStack outputStack : display.getOutputEntries()) {
  172. for (EntryStack stack : recipesFor) {
  173. if (stack.equals(outputStack)) {
  174. set.add(display);
  175. break label;
  176. }
  177. }
  178. }
  179. }
  180. if (!usagesFor.isEmpty()) {
  181. back:
  182. for (List<EntryStack> input : display.getInputEntries()) {
  183. for (EntryStack otherEntry : input) {
  184. for (EntryStack stack : usagesFor) {
  185. if (otherEntry.equals(stack)) {
  186. set.add(display);
  187. break back;
  188. }
  189. }
  190. }
  191. }
  192. }
  193. }
  194. for (EntryStack stack : usagesFor) {
  195. if (isStackWorkStationOfCategory(categoryId, stack)) {
  196. set.addAll(allRecipesFromCategory);
  197. break;
  198. }
  199. }
  200. if (!set.isEmpty()) {
  201. CollectionUtils.getOrPutEmptyList(result, category).addAll(set);
  202. }
  203. }
  204. for (LiveRecipeGenerator<RecipeDisplay> liveRecipeGenerator : liveRecipeGenerators) {
  205. Set<RecipeDisplay> set = Sets.newLinkedHashSet();
  206. for (EntryStack stack : recipesFor) {
  207. Optional<List<RecipeDisplay>> recipeForDisplays = liveRecipeGenerator.getRecipeFor(stack);
  208. if (recipeForDisplays.isPresent()) {
  209. for (RecipeDisplay display : recipeForDisplays.get()) {
  210. if (isDisplayVisible(display))
  211. set.add(display);
  212. }
  213. }
  214. }
  215. for (EntryStack stack : usagesFor) {
  216. Optional<List<RecipeDisplay>> usageForDisplays = liveRecipeGenerator.getUsageFor(stack);
  217. if (usageForDisplays.isPresent()) {
  218. for (RecipeDisplay display : usageForDisplays.get()) {
  219. if (isDisplayVisible(display))
  220. set.add(display);
  221. }
  222. }
  223. }
  224. Optional<List<RecipeDisplay>> displaysGenerated = liveRecipeGenerator.getDisplaysGenerated(builder);
  225. if (displaysGenerated.isPresent()) {
  226. for (RecipeDisplay display : displaysGenerated.get()) {
  227. if (isDisplayVisible(display))
  228. set.add(display);
  229. }
  230. }
  231. if (!set.isEmpty()) {
  232. CollectionUtils.getOrPutEmptyList(result, getCategory(liveRecipeGenerator.getCategoryIdentifier())).addAll(set);
  233. }
  234. }
  235. long end = Util.getMeasuringTimeNano();
  236. String message = String.format("Built Recipe View in %dμs for %d categories, %d recipes for, %d usages for and %d live recipe generators.",
  237. (end - start) / 1000, categories.size(), recipesFor.size(), usagesFor.size(), liveRecipeGenerators.size());
  238. if (ConfigObject.getInstance().doDebugSearchTimeRequired()) {
  239. RoughlyEnoughItemsCore.LOGGER.info(message);
  240. } else {
  241. RoughlyEnoughItemsCore.LOGGER.trace(message);
  242. }
  243. return result;
  244. }
  245. @Override
  246. public Map<RecipeCategory<?>, List<RecipeDisplay>> getRecipesFor(EntryStack stack) {
  247. return buildMapFor(ClientHelper.ViewSearchBuilder.builder().addRecipesFor(stack));
  248. }
  249. @Override
  250. public RecipeCategory<?> getCategory(Identifier identifier) {
  251. return reversedCategories.get(identifier);
  252. }
  253. @Override
  254. public RecipeManager getRecipeManager() {
  255. return recipeManager;
  256. }
  257. private boolean isStackWorkStationOfCategory(Identifier category, EntryStack stack) {
  258. for (List<EntryStack> stacks : getWorkingStations(category)) {
  259. for (EntryStack entryStack : stacks) {
  260. if (entryStack.equalsIgnoreTagsAndAmount(stack))
  261. return true;
  262. }
  263. }
  264. return false;
  265. }
  266. @Override
  267. public Map<RecipeCategory<?>, List<RecipeDisplay>> getUsagesFor(EntryStack stack) {
  268. return buildMapFor(ClientHelper.ViewSearchBuilder.builder().addUsagesFor(stack));
  269. }
  270. @Override
  271. public List<RecipeCategory<?>> getAllCategories() {
  272. return Lists.newArrayList(categories.keySet());
  273. }
  274. @Override
  275. public Optional<ButtonAreaSupplier> getAutoCraftButtonArea(RecipeCategory<?> category) {
  276. if (!autoCraftAreaSupplierMap.containsKey(category.getIdentifier()))
  277. return Optional.ofNullable(bounds -> new Rectangle(bounds.getMaxX() - 16, bounds.getMaxY() - 16, 10, 10));
  278. return Optional.ofNullable(autoCraftAreaSupplierMap.get(category.getIdentifier()));
  279. }
  280. @Override
  281. public void registerAutoCraftButtonArea(Identifier category, ButtonAreaSupplier rectangle) {
  282. if (rectangle == null) {
  283. autoCraftAreaSupplierMap.remove(category);
  284. } else
  285. autoCraftAreaSupplierMap.put(category, rectangle);
  286. }
  287. private void startSection(Object[] sectionData, String section) {
  288. sectionData[0] = Util.getMeasuringTimeNano();
  289. sectionData[2] = section;
  290. RoughlyEnoughItemsCore.LOGGER.debug("Reloading Section: \"%s\"", section);
  291. }
  292. private void endSection(Object[] sectionData) {
  293. sectionData[1] = Util.getMeasuringTimeNano();
  294. long time = (long) sectionData[1] - (long) sectionData[0];
  295. String section = (String) sectionData[2];
  296. if (time >= 1000000) {
  297. RoughlyEnoughItemsCore.LOGGER.debug("Reloading Section: \"%s\" done in %.2fms", section, time / 1000000.0F);
  298. } else {
  299. RoughlyEnoughItemsCore.LOGGER.debug("Reloading Section: \"%s\" done in %.2fμs", section, time / 1000.0F);
  300. }
  301. }
  302. private void pluginSection(Object[] sectionData, String sectionName, List<REIPluginV0> list, Consumer<REIPluginV0> consumer) {
  303. for (REIPluginV0 plugin : list) {
  304. try {
  305. startSection(sectionData, sectionName + " for " + plugin.getPluginIdentifier().toString());
  306. consumer.accept(plugin);
  307. endSection(sectionData);
  308. } catch (Throwable e) {
  309. RoughlyEnoughItemsCore.LOGGER.error(plugin.getPluginIdentifier().toString() + " plugin failed to " + sectionName + "!", e);
  310. }
  311. }
  312. }
  313. public void recipesLoaded(RecipeManager recipeManager) {
  314. long startTime = Util.getMeasuringTimeMs();
  315. Object[] sectionData = {0L, 0L, ""};
  316. startSection(sectionData, "reset-data");
  317. arePluginsLoading = true;
  318. ScreenHelper.clearLastRecipeScreenData();
  319. recipeCount[0] = 0;
  320. this.recipeManager = recipeManager;
  321. this.recipeCategoryListMap.clear();
  322. this.categories.clear();
  323. this.reversedCategories.clear();
  324. this.autoCraftAreaSupplierMap.clear();
  325. this.screenClickAreas.clear();
  326. this.categoryWorkingStations.clear();
  327. this.recipeFunctions.clear();
  328. this.displayVisibilityHandlers.clear();
  329. this.liveRecipeGenerators.clear();
  330. this.autoTransferHandlers.clear();
  331. ((SubsetsRegistryImpl) SubsetsRegistry.INSTANCE).reset();
  332. ((FluidSupportProviderImpl) FluidSupportProvider.INSTANCE).reset();
  333. ((DisplayHelperImpl) DisplayHelper.getInstance()).resetData();
  334. ((DisplayHelperImpl) DisplayHelper.getInstance()).resetCache();
  335. BaseBoundsHandler baseBoundsHandler = new BaseBoundsHandlerImpl();
  336. DisplayHelper.getInstance().registerHandler(baseBoundsHandler);
  337. ((DisplayHelperImpl) DisplayHelper.getInstance()).setBaseBoundsHandler(baseBoundsHandler);
  338. List<REIPluginEntry> plugins = RoughlyEnoughItemsCore.getPlugins();
  339. plugins.sort(Comparator.comparingInt(REIPluginEntry::getPriority).reversed());
  340. RoughlyEnoughItemsCore.LOGGER.info("Reloading REI, registered %d plugins: %s", plugins.size(), plugins.stream().map(REIPluginEntry::getPluginIdentifier).map(Identifier::toString).collect(Collectors.joining(", ")));
  341. Collections.reverse(plugins);
  342. ((EntryRegistryImpl) EntryRegistry.getInstance()).reset();
  343. List<REIPluginV0> reiPluginV0s = new ArrayList<>();
  344. endSection(sectionData);
  345. for (REIPluginEntry plugin : plugins) {
  346. try {
  347. if (plugin instanceof REIPluginV0) {
  348. startSection(sectionData, "pre-register for " + plugin.getPluginIdentifier().toString());
  349. ((REIPluginV0) plugin).preRegister();
  350. reiPluginV0s.add((REIPluginV0) plugin);
  351. endSection(sectionData);
  352. }
  353. } catch (Throwable e) {
  354. RoughlyEnoughItemsCore.LOGGER.error(plugin.getPluginIdentifier().toString() + " plugin failed to pre register!", e);
  355. }
  356. }
  357. DisplayHelper displayHelper = DisplayHelper.getInstance();
  358. EntryRegistry entryRegistry = EntryRegistry.getInstance();
  359. pluginSection(sectionData, "register-bounds", reiPluginV0s, plugin -> plugin.registerBounds(displayHelper));
  360. pluginSection(sectionData, "register-entries", reiPluginV0s, plugin -> plugin.registerEntries(entryRegistry));
  361. pluginSection(sectionData, "register-categories", reiPluginV0s, plugin -> plugin.registerPluginCategories(this));
  362. pluginSection(sectionData, "register-displays", reiPluginV0s, plugin -> plugin.registerRecipeDisplays(this));
  363. pluginSection(sectionData, "register-others", reiPluginV0s, plugin -> plugin.registerOthers(this));
  364. pluginSection(sectionData, "post-register", reiPluginV0s, REIPluginV0::postRegister);
  365. startSection(sectionData, "recipe-functions");
  366. if (!recipeFunctions.isEmpty()) {
  367. @SuppressWarnings("rawtypes") List<Recipe> allSortedRecipes = getAllSortedRecipes();
  368. Collections.reverse(allSortedRecipes);
  369. for (RecipeFunction recipeFunction : recipeFunctions) {
  370. try {
  371. for (Recipe<?> recipe : CollectionUtils.filter(allSortedRecipes, recipe -> recipeFunction.recipeFilter.test(recipe))) {
  372. registerDisplay(recipeFunction.category, (RecipeDisplay) recipeFunction.mappingFunction.apply(recipe), 0);
  373. }
  374. } catch (Exception e) {
  375. RoughlyEnoughItemsCore.LOGGER.error("Failed to add recipes!", e);
  376. }
  377. }
  378. }
  379. endSection(sectionData);
  380. startSection(sectionData, "fill-handlers");
  381. if (getDisplayVisibilityHandlers().isEmpty())
  382. registerRecipeVisibilityHandler(new DisplayVisibilityHandler() {
  383. @Override
  384. public ActionResult handleDisplay(RecipeCategory<?> category, RecipeDisplay display) {
  385. return ActionResult.SUCCESS;
  386. }
  387. @Override
  388. public float getPriority() {
  389. return -1f;
  390. }
  391. });
  392. DisplayHelper.getInstance().registerHandler(new OverlayDecider() {
  393. @Override
  394. public boolean isHandingScreen(Class<?> screen) {
  395. return true;
  396. }
  397. @Override
  398. public ActionResult shouldScreenBeOverlayed(Class<?> screen) {
  399. return ContainerScreen.class.isAssignableFrom(screen) ? ActionResult.SUCCESS : ActionResult.PASS;
  400. }
  401. @Override
  402. public float getPriority() {
  403. return -10;
  404. }
  405. });
  406. endSection(sectionData);
  407. // Clear Cache
  408. ((DisplayHelperImpl) DisplayHelper.getInstance()).resetCache();
  409. ScreenHelper.getOptionalOverlay().ifPresent(overlay -> overlay.shouldReInit = true);
  410. startSection(sectionData, "entry-registry-distinct");
  411. // Remove duplicate entries
  412. ((EntryRegistryImpl) EntryRegistry.getInstance()).distinct();
  413. endSection(sectionData);
  414. startSection(sectionData, "entry-registry-refilter");
  415. arePluginsLoading = false;
  416. ((EntryRegistryImpl) EntryRegistry.getInstance()).refilter();
  417. endSection(sectionData);
  418. startSection(sectionData, "finalizing");
  419. // Clear Cache Again!
  420. ((DisplayHelperImpl) DisplayHelper.getInstance()).resetCache();
  421. ScreenHelper.getOptionalOverlay().ifPresent(overlay -> overlay.shouldReInit = true);
  422. displayVisibilityHandlers.sort(VISIBILITY_HANDLER_COMPARATOR);
  423. endSection(sectionData);
  424. long usedTime = Util.getMeasuringTimeMs() - startTime;
  425. RoughlyEnoughItemsCore.LOGGER.info("Reloaded %d stack entries, %d recipes displays, %d exclusion zones suppliers, %d overlay deciders, %d visibility handlers and %d categories (%s) in %dms.",
  426. EntryRegistry.getInstance().getStacksList().size(), recipeCount[0], BaseBoundsHandler.getInstance().supplierSize(), DisplayHelper.getInstance().getAllOverlayDeciders().size(), getDisplayVisibilityHandlers().size(), categories.size(), categories.keySet().stream().map(RecipeCategory::getCategoryName).collect(Collectors.joining(", ")), usedTime);
  427. }
  428. @Override
  429. public AutoTransferHandler registerAutoCraftingHandler(AutoTransferHandler handler) {
  430. autoTransferHandlers.add(handler);
  431. return handler;
  432. }
  433. @Override
  434. public List<AutoTransferHandler> getSortedAutoCraftingHandler() {
  435. return autoTransferHandlers.stream().sorted(Comparator.comparingDouble(AutoTransferHandler::getPriority).reversed()).collect(Collectors.toList());
  436. }
  437. @Override
  438. public int getRecipeCount() {
  439. return recipeCount[0];
  440. }
  441. @Override
  442. @SuppressWarnings("rawtypes")
  443. public List<Recipe> getAllSortedRecipes() {
  444. return getRecipeManager().values().stream().sorted(RECIPE_COMPARATOR).collect(Collectors.toList());
  445. }
  446. @Override
  447. public Map<RecipeCategory<?>, List<RecipeDisplay>> getAllRecipes() {
  448. return buildMapFor(ClientHelper.ViewSearchBuilder.builder().addAllCategories());
  449. }
  450. @Override
  451. public Map<RecipeCategory<?>, List<RecipeDisplay>> getAllRecipesNoHandlers() {
  452. Map<RecipeCategory<?>, List<RecipeDisplay>> result = Maps.newLinkedHashMap();
  453. for (Map.Entry<RecipeCategory<?>, Identifier> entry : categories.entrySet()) {
  454. RecipeCategory<?> category = entry.getKey();
  455. Identifier categoryId = entry.getValue();
  456. List<RecipeDisplay> displays = Lists.newArrayList(recipeCategoryListMap.get(categoryId));
  457. if (displays != null) {
  458. if (!displays.isEmpty())
  459. result.put(category, displays);
  460. }
  461. }
  462. return result;
  463. }
  464. @Override
  465. public List<RecipeDisplay> getAllRecipesFromCategory(RecipeCategory<?> category) {
  466. return Lists.newArrayList(recipeCategoryListMap.get(category.getIdentifier()));
  467. }
  468. @Override
  469. public void registerRecipeVisibilityHandler(DisplayVisibilityHandler visibilityHandler) {
  470. displayVisibilityHandlers.add(visibilityHandler);
  471. }
  472. @Override
  473. public void unregisterRecipeVisibilityHandler(DisplayVisibilityHandler visibilityHandler) {
  474. displayVisibilityHandlers.remove(visibilityHandler);
  475. }
  476. @Override
  477. public List<DisplayVisibilityHandler> getDisplayVisibilityHandlers() {
  478. return Collections.unmodifiableList(displayVisibilityHandlers);
  479. }
  480. @Override
  481. public boolean isDisplayNotVisible(RecipeDisplay display) {
  482. return !isDisplayVisible(display);
  483. }
  484. @Override
  485. public boolean isDisplayVisible(RecipeDisplay display) {
  486. RecipeCategory<?> category = getCategory(display.getRecipeCategory());
  487. try {
  488. for (DisplayVisibilityHandler displayVisibilityHandler : displayVisibilityHandlers) {
  489. ActionResult visibility = displayVisibilityHandler.handleDisplay(category, display);
  490. if (visibility != ActionResult.PASS)
  491. return visibility == ActionResult.SUCCESS;
  492. }
  493. } catch (Throwable throwable) {
  494. RoughlyEnoughItemsCore.LOGGER.error("Failed to check if the recipe is visible!", throwable);
  495. }
  496. return true;
  497. }
  498. @Override
  499. public void registerScreenClickArea(Rectangle rectangle, Class<? extends ContainerScreen<?>> screenClass, Identifier... categories) {
  500. this.screenClickAreas.add(new ScreenClickAreaImpl(screenClass, rectangle, categories));
  501. }
  502. @Override
  503. public <T extends Recipe<?>> void registerRecipes(Identifier category, Class<T> recipeClass, Function<T, RecipeDisplay> mappingFunction) {
  504. recipeFunctions.add(new RecipeFunction(category, recipe -> recipeClass.isAssignableFrom(recipe.getClass()), mappingFunction));
  505. }
  506. @Override
  507. public <T extends Recipe<?>> void registerRecipes(Identifier category,
  508. @SuppressWarnings("rawtypes") Function<Recipe, Boolean> recipeFilter, Function<T, RecipeDisplay> mappingFunction) {
  509. recipeFunctions.add(new RecipeFunction(category, recipeFilter::apply, mappingFunction));
  510. }
  511. @Override
  512. public <T extends Recipe<?>> void registerRecipes(Identifier category,
  513. @SuppressWarnings("rawtypes") Predicate<Recipe> recipeFilter, Function<T, RecipeDisplay> mappingFunction) {
  514. recipeFunctions.add(new RecipeFunction(category, recipeFilter, mappingFunction));
  515. }
  516. @Override
  517. public void registerLiveRecipeGenerator(LiveRecipeGenerator<?> liveRecipeGenerator) {
  518. liveRecipeGenerators.add((LiveRecipeGenerator<RecipeDisplay>) liveRecipeGenerator);
  519. }
  520. @Override
  521. public List<ScreenClickArea> getScreenClickAreas() {
  522. return screenClickAreas;
  523. }
  524. private static class ScreenClickAreaImpl implements ScreenClickArea {
  525. Class<? extends ContainerScreen<?>> screenClass;
  526. Rectangle rectangle;
  527. Identifier[] categories;
  528. private ScreenClickAreaImpl(Class<? extends ContainerScreen<?>> screenClass, Rectangle rectangle, Identifier[] categories) {
  529. this.screenClass = screenClass;
  530. this.rectangle = rectangle;
  531. this.categories = categories;
  532. }
  533. public Class<? extends ContainerScreen<?>> getScreenClass() {
  534. return screenClass;
  535. }
  536. public Rectangle getRectangle() {
  537. return rectangle;
  538. }
  539. public Identifier[] getCategories() {
  540. return categories;
  541. }
  542. }
  543. @SuppressWarnings("rawtypes")
  544. private static class RecipeFunction {
  545. Identifier category;
  546. Predicate<Recipe> recipeFilter;
  547. Function mappingFunction;
  548. public RecipeFunction(Identifier category, Predicate<Recipe> recipeFilter, Function<?, RecipeDisplay> mappingFunction) {
  549. this.category = category;
  550. this.recipeFilter = recipeFilter;
  551. this.mappingFunction = mappingFunction;
  552. }
  553. }
  554. }