RecipeHelperImpl.java 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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.*;
  25. import me.shedaniel.math.Rectangle;
  26. import me.shedaniel.rei.RoughlyEnoughItemsCore;
  27. import me.shedaniel.rei.api.*;
  28. import me.shedaniel.rei.api.fluid.FluidSupportProvider;
  29. import me.shedaniel.rei.api.plugins.REIPluginV0;
  30. import me.shedaniel.rei.api.subsets.SubsetsRegistry;
  31. import me.shedaniel.rei.impl.subsets.SubsetsRegistryImpl;
  32. import me.shedaniel.rei.utils.CollectionUtils;
  33. import net.fabricmc.api.EnvType;
  34. import net.fabricmc.api.Environment;
  35. import net.minecraft.client.gui.screen.Screen;
  36. import net.minecraft.client.gui.screen.ingame.ContainerScreen;
  37. import net.minecraft.recipe.Recipe;
  38. import net.minecraft.recipe.RecipeManager;
  39. import net.minecraft.util.ActionResult;
  40. import net.minecraft.util.Identifier;
  41. import net.minecraft.util.TypedActionResult;
  42. import net.minecraft.util.Util;
  43. import org.jetbrains.annotations.ApiStatus;
  44. import org.jetbrains.annotations.NotNull;
  45. import org.jetbrains.annotations.Nullable;
  46. import java.util.*;
  47. import java.util.function.Consumer;
  48. import java.util.function.Function;
  49. import java.util.function.Predicate;
  50. import java.util.stream.Collectors;
  51. import java.util.stream.Stream;
  52. @ApiStatus.Internal
  53. @Environment(EnvType.CLIENT)
  54. public class RecipeHelperImpl implements RecipeHelper {
  55. private static final Comparator<FocusedStackProvider> FOCUSED_STACK_PROVIDER_COMPARATOR = Comparator.comparingDouble(FocusedStackProvider::getPriority).reversed();
  56. private static final Comparator<DisplayVisibilityHandler> VISIBILITY_HANDLER_COMPARATOR = Comparator.comparingDouble(DisplayVisibilityHandler::getPriority).reversed();
  57. @SuppressWarnings("rawtypes")
  58. private static final Comparator<Recipe> RECIPE_COMPARATOR = Comparator.comparing((Recipe o) -> o.getId().getNamespace()).thenComparing(o -> o.getId().getPath());
  59. private final List<FocusedStackProvider> focusedStackProviders = Lists.newArrayList();
  60. private final List<AutoTransferHandler> autoTransferHandlers = Lists.newArrayList();
  61. private final List<RecipeFunction> recipeFunctions = Lists.newArrayList();
  62. private final List<ScreenClickArea> screenClickAreas = Lists.newArrayList();
  63. private final int[] recipeCount = {0};
  64. private final Map<Identifier, List<RecipeDisplay>> recipeDisplays = Maps.newHashMap();
  65. private final BiMap<RecipeCategory<?>, Identifier> categories = HashBiMap.create();
  66. private final Map<Identifier, ButtonAreaSupplier> autoCraftAreaSupplierMap = Maps.newHashMap();
  67. private final Map<Identifier, List<List<EntryStack>>> categoryWorkingStations = Maps.newHashMap();
  68. private final List<DisplayVisibilityHandler> displayVisibilityHandlers = Lists.newArrayList();
  69. private final List<LiveRecipeGenerator<RecipeDisplay>> liveRecipeGenerators = Lists.newArrayList();
  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 : recipeDisplays.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. recipeDisplay.getResultingEntries().stream().flatMap(Collection::stream).collect(Collectors.toCollection(() -> craftables));
  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. recipeDisplays.put(category.getIdentifier(), Lists.newArrayList());
  106. categoryWorkingStations.put(category.getIdentifier(), Lists.newArrayList());
  107. }
  108. @SafeVarargs
  109. @Override
  110. public final void registerWorkingStations(Identifier category, List<EntryStack>... workingStations) {
  111. categoryWorkingStations.get(category).addAll(Arrays.asList(workingStations));
  112. }
  113. @Override
  114. public void registerWorkingStations(Identifier category, EntryStack... workingStations) {
  115. categoryWorkingStations.get(category).addAll(Stream.of(workingStations).map(Collections::singletonList).collect(Collectors.toList()));
  116. }
  117. @Override
  118. public List<List<EntryStack>> getWorkingStations(Identifier category) {
  119. return categoryWorkingStations.get(category);
  120. }
  121. @Override
  122. public void registerDisplay(RecipeDisplay display) {
  123. Identifier identifier = Objects.requireNonNull(display.getRecipeCategory());
  124. if (!recipeDisplays.containsKey(identifier))
  125. return;
  126. recipeCount[0]++;
  127. recipeDisplays.get(identifier).add(display);
  128. }
  129. private void registerDisplay(Identifier categoryIdentifier, RecipeDisplay display, int index) {
  130. if (!recipeDisplays.containsKey(categoryIdentifier))
  131. return;
  132. recipeCount[0]++;
  133. recipeDisplays.get(categoryIdentifier).add(index, display);
  134. }
  135. @Override
  136. public Map<RecipeCategory<?>, List<RecipeDisplay>> buildMapFor(ClientHelper.ViewSearchBuilder builder) {
  137. long start = Util.getMeasuringTimeNano();
  138. Set<Identifier> categories = builder.getCategories();
  139. List<EntryStack> recipesFor = builder.getRecipesFor();
  140. List<EntryStack> usagesFor = builder.getUsagesFor();
  141. Map<RecipeCategory<?>, List<RecipeDisplay>> result = Maps.newLinkedHashMap();
  142. for (Map.Entry<RecipeCategory<?>, Identifier> entry : this.categories.entrySet()) {
  143. RecipeCategory<?> category = entry.getKey();
  144. Identifier categoryId = entry.getValue();
  145. List<RecipeDisplay> allRecipesFromCategory = getAllRecipesFromCategory(category);
  146. Set<RecipeDisplay> set = Sets.newLinkedHashSet();
  147. if (categories.contains(categoryId)) {
  148. for (RecipeDisplay display : allRecipesFromCategory) {
  149. if (isDisplayVisible(display)) {
  150. set.add(display);
  151. }
  152. }
  153. if (!set.isEmpty()) {
  154. CollectionUtils.getOrPutEmptyList(result, category).addAll(set);
  155. }
  156. continue;
  157. }
  158. for (RecipeDisplay display : allRecipesFromCategory) {
  159. if (!isDisplayVisible(display)) continue;
  160. if (!recipesFor.isEmpty()) {
  161. back:
  162. for (List<EntryStack> results : display.getResultingEntries()) {
  163. for (EntryStack otherEntry : results) {
  164. for (EntryStack stack : recipesFor) {
  165. if (otherEntry.equals(stack)) {
  166. set.add(display);
  167. break back;
  168. }
  169. }
  170. }
  171. }
  172. }
  173. if (!usagesFor.isEmpty()) {
  174. back:
  175. for (List<EntryStack> input : display.getInputEntries()) {
  176. for (EntryStack otherEntry : input) {
  177. for (EntryStack stack : usagesFor) {
  178. if (otherEntry.equals(stack)) {
  179. set.add(display);
  180. break back;
  181. }
  182. }
  183. }
  184. }
  185. }
  186. }
  187. for (EntryStack stack : usagesFor) {
  188. if (isStackWorkStationOfCategory(categoryId, stack)) {
  189. set.addAll(allRecipesFromCategory);
  190. break;
  191. }
  192. }
  193. if (!set.isEmpty()) {
  194. CollectionUtils.getOrPutEmptyList(result, category).addAll(set);
  195. }
  196. }
  197. for (LiveRecipeGenerator<RecipeDisplay> liveRecipeGenerator : liveRecipeGenerators) {
  198. Set<RecipeDisplay> set = Sets.newLinkedHashSet();
  199. for (EntryStack stack : recipesFor) {
  200. Optional<List<RecipeDisplay>> recipeForDisplays = liveRecipeGenerator.getRecipeFor(stack);
  201. if (recipeForDisplays.isPresent()) {
  202. for (RecipeDisplay display : recipeForDisplays.get()) {
  203. if (isDisplayVisible(display))
  204. set.add(display);
  205. }
  206. }
  207. }
  208. for (EntryStack stack : usagesFor) {
  209. Optional<List<RecipeDisplay>> usageForDisplays = liveRecipeGenerator.getUsageFor(stack);
  210. if (usageForDisplays.isPresent()) {
  211. for (RecipeDisplay display : usageForDisplays.get()) {
  212. if (isDisplayVisible(display))
  213. set.add(display);
  214. }
  215. }
  216. }
  217. Optional<List<RecipeDisplay>> displaysGenerated = liveRecipeGenerator.getDisplaysGenerated(builder);
  218. if (displaysGenerated.isPresent()) {
  219. for (RecipeDisplay display : displaysGenerated.get()) {
  220. if (isDisplayVisible(display))
  221. set.add(display);
  222. }
  223. }
  224. if (!set.isEmpty()) {
  225. CollectionUtils.getOrPutEmptyList(result, getCategory(liveRecipeGenerator.getCategoryIdentifier())).addAll(set);
  226. }
  227. }
  228. long end = Util.getMeasuringTimeNano();
  229. String message = String.format("Built Recipe View in %dμs for %d categories, %d recipes for, %d usages for and %d live recipe generators.",
  230. (end - start) / 1000, categories.size(), recipesFor.size(), usagesFor.size(), liveRecipeGenerators.size());
  231. if (ConfigObject.getInstance().doDebugSearchTimeRequired()) {
  232. RoughlyEnoughItemsCore.LOGGER.info(message);
  233. } else {
  234. RoughlyEnoughItemsCore.LOGGER.trace(message);
  235. }
  236. return result;
  237. }
  238. @Override
  239. public Map<RecipeCategory<?>, List<RecipeDisplay>> getRecipesFor(EntryStack stack) {
  240. return buildMapFor(ClientHelper.ViewSearchBuilder.builder().addRecipesFor(stack));
  241. }
  242. @Override
  243. public RecipeCategory<?> getCategory(Identifier identifier) {
  244. return categories.inverse().get(identifier);
  245. }
  246. @Override
  247. public RecipeManager getRecipeManager() {
  248. return recipeManager;
  249. }
  250. private boolean isStackWorkStationOfCategory(Identifier category, EntryStack stack) {
  251. for (List<EntryStack> stacks : getWorkingStations(category)) {
  252. for (EntryStack entryStack : stacks) {
  253. if (entryStack.equalsIgnoreTagsAndAmount(stack))
  254. return true;
  255. }
  256. }
  257. return false;
  258. }
  259. @Override
  260. public Map<RecipeCategory<?>, List<RecipeDisplay>> getUsagesFor(EntryStack stack) {
  261. return buildMapFor(ClientHelper.ViewSearchBuilder.builder().addUsagesFor(stack));
  262. }
  263. @Override
  264. public List<RecipeCategory<?>> getAllCategories() {
  265. return Lists.newArrayList(categories.keySet());
  266. }
  267. @Override
  268. public Optional<ButtonAreaSupplier> getAutoCraftButtonArea(RecipeCategory<?> category) {
  269. if (!autoCraftAreaSupplierMap.containsKey(category.getIdentifier()))
  270. return Optional.ofNullable(bounds -> new Rectangle(bounds.getMaxX() - 16, bounds.getMaxY() - 16, 10, 10));
  271. return Optional.ofNullable(autoCraftAreaSupplierMap.get(category.getIdentifier()));
  272. }
  273. @Override
  274. public void registerAutoCraftButtonArea(Identifier category, ButtonAreaSupplier rectangle) {
  275. if (rectangle == null) {
  276. autoCraftAreaSupplierMap.remove(category);
  277. } else
  278. autoCraftAreaSupplierMap.put(category, rectangle);
  279. }
  280. private void startSection(Object[] sectionData, String section) {
  281. sectionData[0] = Util.getMeasuringTimeNano();
  282. sectionData[2] = section;
  283. RoughlyEnoughItemsCore.LOGGER.debug("Reloading Section: \"%s\"", section);
  284. }
  285. private void endSection(Object[] sectionData) {
  286. sectionData[1] = Util.getMeasuringTimeNano();
  287. long time = (long) sectionData[1] - (long) sectionData[0];
  288. String section = (String) sectionData[2];
  289. if (time >= 1000000) {
  290. RoughlyEnoughItemsCore.LOGGER.debug("Reloading Section: \"%s\" done in %.2fms", section, time / 1000000.0F);
  291. } else {
  292. RoughlyEnoughItemsCore.LOGGER.debug("Reloading Section: \"%s\" done in %.2fμs", section, time / 1000.0F);
  293. }
  294. }
  295. private void pluginSection(Object[] sectionData, String sectionName, List<REIPluginV0> list, Consumer<REIPluginV0> consumer) {
  296. for (REIPluginV0 plugin : list) {
  297. try {
  298. startSection(sectionData, sectionName + " for " + plugin.getPluginIdentifier().toString());
  299. consumer.accept(plugin);
  300. endSection(sectionData);
  301. } catch (Throwable e) {
  302. RoughlyEnoughItemsCore.LOGGER.error(plugin.getPluginIdentifier().toString() + " plugin failed to " + sectionName + "!", e);
  303. }
  304. }
  305. }
  306. public void tryRecipesLoaded(RecipeManager recipeManager) {
  307. try {
  308. recipesLoaded(recipeManager);
  309. } catch (Throwable throwable) {
  310. throwable.printStackTrace();
  311. }
  312. arePluginsLoading = false;
  313. }
  314. public void recipesLoaded(RecipeManager recipeManager) {
  315. long startTime = Util.getMeasuringTimeMs();
  316. Object[] sectionData = {0L, 0L, ""};
  317. startSection(sectionData, "reset-data");
  318. arePluginsLoading = true;
  319. ScreenHelper.clearLastRecipeScreenData();
  320. recipeCount[0] = 0;
  321. this.recipeManager = recipeManager;
  322. this.recipeDisplays.clear();
  323. this.categories.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. this.focusedStackProviders.clear();
  332. DisplayHelperImpl displayHelper = (DisplayHelperImpl) DisplayHelper.getInstance();
  333. EntryRegistryImpl entryRegistry = (EntryRegistryImpl) EntryRegistry.getInstance();
  334. ((SubsetsRegistryImpl) SubsetsRegistry.getInstance()).reset();
  335. ((FluidSupportProviderImpl) FluidSupportProvider.getInstance()).reset();
  336. displayHelper.resetData();
  337. displayHelper.resetCache();
  338. BaseBoundsHandler baseBoundsHandler = new BaseBoundsHandlerImpl();
  339. displayHelper.registerHandler(baseBoundsHandler);
  340. displayHelper.setBaseBoundsHandler(baseBoundsHandler);
  341. List<REIPluginEntry> plugins = RoughlyEnoughItemsCore.getPlugins();
  342. plugins.sort(Comparator.comparingInt(REIPluginEntry::getPriority).reversed());
  343. RoughlyEnoughItemsCore.LOGGER.info("Reloading REI, registered %d plugins: %s", plugins.size(), plugins.stream().map(REIPluginEntry::getPluginIdentifier).map(Identifier::toString).collect(Collectors.joining(", ")));
  344. Collections.reverse(plugins);
  345. entryRegistry.reset();
  346. List<REIPluginV0> reiPluginV0s = new ArrayList<>();
  347. endSection(sectionData);
  348. for (REIPluginEntry plugin : plugins) {
  349. try {
  350. if (plugin instanceof REIPluginV0) {
  351. startSection(sectionData, "pre-register for " + plugin.getPluginIdentifier().toString());
  352. ((REIPluginV0) plugin).preRegister();
  353. reiPluginV0s.add((REIPluginV0) plugin);
  354. endSection(sectionData);
  355. }
  356. } catch (Throwable e) {
  357. RoughlyEnoughItemsCore.LOGGER.error(plugin.getPluginIdentifier().toString() + " plugin failed to pre register!", e);
  358. }
  359. }
  360. pluginSection(sectionData, "register-bounds", reiPluginV0s, plugin -> plugin.registerBounds(displayHelper));
  361. pluginSection(sectionData, "register-entries", reiPluginV0s, plugin -> plugin.registerEntries(entryRegistry));
  362. pluginSection(sectionData, "register-categories", reiPluginV0s, plugin -> plugin.registerPluginCategories(this));
  363. pluginSection(sectionData, "register-displays", reiPluginV0s, plugin -> plugin.registerRecipeDisplays(this));
  364. pluginSection(sectionData, "register-others", reiPluginV0s, plugin -> plugin.registerOthers(this));
  365. pluginSection(sectionData, "post-register", reiPluginV0s, REIPluginV0::postRegister);
  366. startSection(sectionData, "recipe-functions");
  367. if (!recipeFunctions.isEmpty()) {
  368. @SuppressWarnings("rawtypes") List<Recipe> allSortedRecipes = getAllSortedRecipes();
  369. Collections.reverse(allSortedRecipes);
  370. for (RecipeFunction recipeFunction : recipeFunctions) {
  371. try {
  372. for (Recipe<?> recipe : CollectionUtils.filter(allSortedRecipes, recipe -> recipeFunction.recipeFilter.test(recipe))) {
  373. registerDisplay(recipeFunction.category, (RecipeDisplay) recipeFunction.mappingFunction.apply(recipe), 0);
  374. }
  375. } catch (Throwable e) {
  376. RoughlyEnoughItemsCore.LOGGER.error("Failed to add recipes!", e);
  377. }
  378. }
  379. }
  380. endSection(sectionData);
  381. startSection(sectionData, "fill-handlers");
  382. if (getDisplayVisibilityHandlers().isEmpty())
  383. registerRecipeVisibilityHandler(new DisplayVisibilityHandler() {
  384. @Override
  385. public ActionResult handleDisplay(RecipeCategory<?> category, RecipeDisplay display) {
  386. return ActionResult.SUCCESS;
  387. }
  388. @Override
  389. public float getPriority() {
  390. return -1f;
  391. }
  392. });
  393. registerFocusedStackProvider(new FocusedStackProvider() {
  394. @Override
  395. @NotNull
  396. public TypedActionResult<EntryStack> provide(Screen screen) {
  397. if (screen instanceof ContainerScreen) {
  398. ContainerScreen<?> containerScreen = (ContainerScreen<?>) screen;
  399. if (containerScreen.focusedSlot != null && !containerScreen.focusedSlot.getStack().isEmpty())
  400. return TypedActionResult.success(EntryStack.create(containerScreen.focusedSlot.getStack()));
  401. }
  402. return TypedActionResult.pass(EntryStack.empty());
  403. }
  404. @Override
  405. public double getPriority() {
  406. return -1.0;
  407. }
  408. });
  409. displayHelper.registerHandler(new OverlayDecider() {
  410. @Override
  411. public boolean isHandingScreen(Class<?> screen) {
  412. return true;
  413. }
  414. @Override
  415. public ActionResult shouldScreenBeOverlayed(Class<?> screen) {
  416. return ContainerScreen.class.isAssignableFrom(screen) ? ActionResult.SUCCESS : ActionResult.PASS;
  417. }
  418. @Override
  419. public float getPriority() {
  420. return -10;
  421. }
  422. });
  423. endSection(sectionData);
  424. // Clear Cache
  425. displayHelper.resetCache();
  426. REIHelper.getInstance().getOverlay().ifPresent(REIOverlay::queueReloadOverlay);
  427. startSection(sectionData, "entry-registry-finalise");
  428. // Finish Reload
  429. entryRegistry.finishReload();
  430. endSection(sectionData);
  431. startSection(sectionData, "entry-registry-refilter");
  432. arePluginsLoading = false;
  433. entryRegistry.refilter();
  434. endSection(sectionData);
  435. startSection(sectionData, "finalizing");
  436. // Clear Cache Again!
  437. displayHelper.resetCache();
  438. REIHelper.getInstance().getOverlay().ifPresent(REIOverlay::queueReloadOverlay);
  439. displayVisibilityHandlers.sort(VISIBILITY_HANDLER_COMPARATOR);
  440. endSection(sectionData);
  441. long usedTime = Util.getMeasuringTimeMs() - startTime;
  442. 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.",
  443. entryRegistry.getEntryStacks().count(), recipeCount[0], BaseBoundsHandler.getInstance().supplierSize(), displayHelper.getAllOverlayDeciders().size(), getDisplayVisibilityHandlers().size(), categories.size(), categories.keySet().stream().map(RecipeCategory::getCategoryName).collect(Collectors.joining(", ")), usedTime);
  444. }
  445. @Override
  446. public AutoTransferHandler registerAutoCraftingHandler(AutoTransferHandler handler) {
  447. autoTransferHandlers.add(handler);
  448. autoTransferHandlers.sort(Comparator.comparingDouble(AutoTransferHandler::getPriority).reversed());
  449. return handler;
  450. }
  451. @Override
  452. public void registerFocusedStackProvider(FocusedStackProvider provider) {
  453. focusedStackProviders.add(provider);
  454. focusedStackProviders.sort(FOCUSED_STACK_PROVIDER_COMPARATOR);
  455. }
  456. @Override
  457. @Nullable
  458. public EntryStack getScreenFocusedStack(Screen screen) {
  459. for (FocusedStackProvider provider : focusedStackProviders) {
  460. TypedActionResult<EntryStack> result = Objects.requireNonNull(provider.provide(screen));
  461. if (result.getResult() == ActionResult.SUCCESS) {
  462. if (!result.getValue().isEmpty())
  463. return result.getValue();
  464. return null;
  465. } else if (result.getResult() == ActionResult.FAIL)
  466. return null;
  467. }
  468. return null;
  469. }
  470. @Override
  471. public List<AutoTransferHandler> getSortedAutoCraftingHandler() {
  472. return autoTransferHandlers;
  473. }
  474. @Override
  475. public int getRecipeCount() {
  476. return recipeCount[0];
  477. }
  478. @Override
  479. @SuppressWarnings("rawtypes")
  480. public List<Recipe> getAllSortedRecipes() {
  481. return getRecipeManager().values().parallelStream().sorted(RECIPE_COMPARATOR).collect(Collectors.toList());
  482. }
  483. @Override
  484. public Map<RecipeCategory<?>, List<RecipeDisplay>> getAllRecipes() {
  485. return buildMapFor(ClientHelper.ViewSearchBuilder.builder().addAllCategories());
  486. }
  487. @Override
  488. public Map<RecipeCategory<?>, List<RecipeDisplay>> getAllRecipesNoHandlers() {
  489. Map<RecipeCategory<?>, List<RecipeDisplay>> result = Maps.newLinkedHashMap();
  490. for (Map.Entry<RecipeCategory<?>, Identifier> entry : categories.entrySet()) {
  491. RecipeCategory<?> category = entry.getKey();
  492. Identifier categoryId = entry.getValue();
  493. List<RecipeDisplay> displays = recipeDisplays.get(categoryId);
  494. if (displays != null && !displays.isEmpty()) {
  495. result.put(category, displays);
  496. }
  497. }
  498. return result;
  499. }
  500. @Override
  501. public List<RecipeDisplay> getAllRecipesFromCategory(RecipeCategory<?> category) {
  502. return recipeDisplays.get(category.getIdentifier());
  503. }
  504. @Override
  505. public void registerRecipeVisibilityHandler(DisplayVisibilityHandler visibilityHandler) {
  506. displayVisibilityHandlers.add(visibilityHandler);
  507. }
  508. @Override
  509. public void unregisterRecipeVisibilityHandler(DisplayVisibilityHandler visibilityHandler) {
  510. displayVisibilityHandlers.remove(visibilityHandler);
  511. }
  512. @Override
  513. public List<DisplayVisibilityHandler> getDisplayVisibilityHandlers() {
  514. return Collections.unmodifiableList(displayVisibilityHandlers);
  515. }
  516. @Override
  517. public boolean isDisplayNotVisible(RecipeDisplay display) {
  518. return !isDisplayVisible(display);
  519. }
  520. @Override
  521. public boolean isDisplayVisible(RecipeDisplay display) {
  522. RecipeCategory<?> category = getCategory(display.getRecipeCategory());
  523. try {
  524. for (DisplayVisibilityHandler displayVisibilityHandler : displayVisibilityHandlers) {
  525. ActionResult visibility = displayVisibilityHandler.handleDisplay(category, display);
  526. if (visibility != ActionResult.PASS)
  527. return visibility == ActionResult.SUCCESS;
  528. }
  529. } catch (Throwable throwable) {
  530. RoughlyEnoughItemsCore.LOGGER.error("Failed to check if the recipe is visible!", throwable);
  531. }
  532. return true;
  533. }
  534. @Override
  535. public void registerScreenClickArea(Rectangle rectangle, Class<? extends ContainerScreen<?>> screenClass, Identifier... categories) {
  536. this.screenClickAreas.add(new ScreenClickAreaImpl(screenClass, rectangle, categories));
  537. }
  538. @Override
  539. public <T extends Recipe<?>> void registerRecipes(Identifier category, Class<T> recipeClass, Function<T, RecipeDisplay> mappingFunction) {
  540. recipeFunctions.add(new RecipeFunction(category, recipe -> recipeClass.isAssignableFrom(recipe.getClass()), mappingFunction));
  541. }
  542. @Override
  543. public <T extends Recipe<?>> void registerRecipes(Identifier category,
  544. @SuppressWarnings("rawtypes") Function<Recipe, Boolean> recipeFilter, Function<T, RecipeDisplay> mappingFunction) {
  545. recipeFunctions.add(new RecipeFunction(category, recipeFilter::apply, mappingFunction));
  546. }
  547. @Override
  548. public <T extends Recipe<?>> void registerRecipes(Identifier category,
  549. @SuppressWarnings("rawtypes") Predicate<Recipe> recipeFilter, Function<T, RecipeDisplay> mappingFunction) {
  550. recipeFunctions.add(new RecipeFunction(category, recipeFilter, mappingFunction));
  551. }
  552. @Override
  553. public void registerLiveRecipeGenerator(LiveRecipeGenerator<?> liveRecipeGenerator) {
  554. liveRecipeGenerators.add((LiveRecipeGenerator<RecipeDisplay>) liveRecipeGenerator);
  555. }
  556. @Override
  557. public List<ScreenClickArea> getScreenClickAreas() {
  558. return screenClickAreas;
  559. }
  560. private static class ScreenClickAreaImpl implements ScreenClickArea {
  561. private Class<? extends ContainerScreen<?>> screenClass;
  562. private Rectangle rectangle;
  563. private Identifier[] categories;
  564. private ScreenClickAreaImpl(Class<? extends ContainerScreen<?>> screenClass, Rectangle rectangle, Identifier[] categories) {
  565. this.screenClass = screenClass;
  566. this.rectangle = rectangle;
  567. this.categories = categories;
  568. }
  569. public Class<? extends ContainerScreen<?>> getScreenClass() {
  570. return screenClass;
  571. }
  572. public Rectangle getRectangle() {
  573. return rectangle;
  574. }
  575. public Identifier[] getCategories() {
  576. return categories;
  577. }
  578. }
  579. @SuppressWarnings("rawtypes")
  580. private static class RecipeFunction {
  581. private Identifier category;
  582. private Predicate<Recipe> recipeFilter;
  583. private Function mappingFunction;
  584. public RecipeFunction(Identifier category, Predicate<Recipe> recipeFilter, Function<?, RecipeDisplay> mappingFunction) {
  585. this.category = category;
  586. this.recipeFilter = recipeFilter;
  587. this.mappingFunction = mappingFunction;
  588. }
  589. }
  590. }