-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathRecipeMap.java
More file actions
1460 lines (1323 loc) · 62.7 KB
/
RecipeMap.java
File metadata and controls
1460 lines (1323 loc) · 62.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gregtech.api.recipes;
import gregtech.api.GTValues;
import gregtech.api.GregTechAPI;
import gregtech.api.capability.IMultipleTankHandler;
import gregtech.api.capability.impl.FluidTankList;
import gregtech.api.gui.ModularUI;
import gregtech.api.gui.resources.TextureArea;
import gregtech.api.gui.widgets.ProgressWidget.MoveType;
import gregtech.api.recipes.category.GTRecipeCategory;
import gregtech.api.recipes.chance.boost.ChanceBoostFunction;
import gregtech.api.recipes.ingredients.GTRecipeInput;
import gregtech.api.recipes.ingredients.IntCircuitIngredient;
import gregtech.api.recipes.map.AbstractMapIngredient;
import gregtech.api.recipes.map.Branch;
import gregtech.api.recipes.map.Either;
import gregtech.api.recipes.map.MapFluidIngredient;
import gregtech.api.recipes.map.MapItemStackIngredient;
import gregtech.api.recipes.map.MapOreDictIngredient;
import gregtech.api.recipes.map.MapOreDictNBTIngredient;
import gregtech.api.recipes.ui.RecipeMapUI;
import gregtech.api.recipes.ui.RecipeMapUIFunction;
import gregtech.api.unification.material.Material;
import gregtech.api.unification.ore.OrePrefix;
import gregtech.api.util.EnumValidationResult;
import gregtech.api.util.GTLog;
import gregtech.api.util.GTUtility;
import gregtech.api.util.LocalizationUtils;
import gregtech.api.util.Mods;
import gregtech.api.util.ValidationResult;
import gregtech.common.ConfigHolder;
import gregtech.integration.crafttweaker.CTRecipeHelper;
import gregtech.integration.crafttweaker.recipe.CTRecipe;
import gregtech.integration.crafttweaker.recipe.CTRecipeBuilder;
import gregtech.integration.groovy.GroovyScriptModule;
import gregtech.integration.groovy.VirtualizedRecipeMap;
import gregtech.modules.GregTechModules;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.common.Optional.Method;
import net.minecraftforge.items.IItemHandlerModifiable;
import net.minecraftforge.oredict.OreDictionary;
import com.cleanroommc.groovyscript.api.GroovyLog;
import com.google.common.collect.ImmutableList;
import crafttweaker.CraftTweakerAPI;
import crafttweaker.annotations.ZenRegister;
import crafttweaker.api.item.IItemStack;
import crafttweaker.api.liquid.ILiquidStack;
import crafttweaker.api.minecraft.CraftTweakerMC;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ReferenceOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.UnmodifiableView;
import stanhebben.zenscript.annotations.Optional;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenGetter;
import stanhebben.zenscript.annotations.ZenMethod;
import stanhebben.zenscript.annotations.ZenSetter;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.function.DoubleSupplier;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@ZenClass("mods.gregtech.recipe.RecipeMap")
@ZenRegister
public class RecipeMap<R extends RecipeBuilder<R>> {
private static final Map<String, RecipeMap<?>> RECIPE_MAP_REGISTRY = new Object2ReferenceOpenHashMap<>();
private static final Comparator<Recipe> RECIPE_DURATION_THEN_EU = Comparator.comparingInt(Recipe::getDuration)
.thenComparingLong(Recipe::getEUt)
.thenComparing(Recipe::hashCode);
private static boolean foundInvalidRecipe = false;
public static final ChanceBoostFunction DEFAULT_CHANCE_FUNCTION = ChanceBoostFunction.OVERCLOCK;
protected RecipeMapUI<?> recipeMapUI;
public ChanceBoostFunction chanceFunction = DEFAULT_CHANCE_FUNCTION;
public final String unlocalizedName;
private final R recipeBuilderSample;
private int maxInputs;
private int maxOutputs;
private int maxFluidInputs;
private int maxFluidOutputs;
private final GTRecipeCategory primaryRecipeCategory;
/**
* @deprecated {@link RecipeMapUI#isJEIVisible()}
*/
@ApiStatus.ScheduledForRemoval(inVersion = "2.9")
@Deprecated
public final boolean isHidden = false;
private boolean allowEmptyOutput;
private final Object grsVirtualizedRecipeMap;
private final Branch lookup = new Branch();
private boolean hasOreDictedInputs = false;
private boolean hasNBTMatcherInputs = false;
private static final WeakHashMap<AbstractMapIngredient, WeakReference<AbstractMapIngredient>> ingredientRoot = new WeakHashMap<>();
private final WeakHashMap<AbstractMapIngredient, WeakReference<AbstractMapIngredient>> fluidIngredientRoot = new WeakHashMap<>();
private final Map<GTRecipeCategory, List<Recipe>> recipeByCategory = new Object2ObjectOpenHashMap<>();
private final Map<ResourceLocation, RecipeBuildAction<R>> recipeBuildActions = new Object2ObjectOpenHashMap<>();
protected @Nullable SoundEvent sound;
private @Nullable RecipeMap<?> smallRecipeMap;
/**
* Create and register new instance of RecipeMap with specified properties.
*
* @param unlocalizedName the unlocalized name for the RecipeMap
* @param defaultRecipeBuilder the default RecipeBuilder for the RecipeMap
* @param recipeMapUI the ui to represent this recipemap
* @param maxInputs the maximum item inputs
* @param maxOutputs the maximum item outputs
* @param maxFluidInputs the maximum fluid inputs
* @param maxFluidOutputs the maximum fluid outputs
*/
public RecipeMap(@NotNull String unlocalizedName, @NotNull R defaultRecipeBuilder,
@NotNull RecipeMapUIFunction recipeMapUI, int maxInputs, int maxOutputs, int maxFluidInputs,
int maxFluidOutputs) {
this.unlocalizedName = unlocalizedName;
this.recipeMapUI = recipeMapUI.apply(this);
this.maxInputs = maxInputs;
this.maxFluidInputs = maxFluidInputs;
this.maxOutputs = maxOutputs;
this.maxFluidOutputs = maxFluidOutputs;
this.primaryRecipeCategory = GTRecipeCategory.create(GTValues.MODID, unlocalizedName, getTranslationKey(),
this);
defaultRecipeBuilder.setRecipeMap(this);
defaultRecipeBuilder.category(primaryRecipeCategory);
this.recipeBuilderSample = defaultRecipeBuilder;
RECIPE_MAP_REGISTRY.put(unlocalizedName, this);
this.grsVirtualizedRecipeMap = GregTechAPI.moduleManager.isModuleEnabled(GregTechModules.MODULE_GRS) ?
new VirtualizedRecipeMap(this) : null;
}
@ZenMethod
public static List<RecipeMap<? extends RecipeBuilder<?>>> getRecipeMaps() {
return ImmutableList.copyOf(RECIPE_MAP_REGISTRY.values());
}
@ZenMethod
public static RecipeMap<? extends RecipeBuilder<?>> getByName(String unlocalizedName) {
return RECIPE_MAP_REGISTRY.get(unlocalizedName);
}
@ZenMethod
public ChanceBoostFunction getChanceFunction() {
return chanceFunction;
}
public static boolean isFoundInvalidRecipe() {
return foundInvalidRecipe;
}
public static void setFoundInvalidRecipe(boolean foundInvalidRecipe) {
RecipeMap.foundInvalidRecipe = RecipeMap.foundInvalidRecipe || foundInvalidRecipe;
OrePrefix currentOrePrefix = OrePrefix.getCurrentProcessingPrefix();
if (currentOrePrefix != null) {
Material currentMaterial = OrePrefix.getCurrentMaterial();
GTLog.logger.error(
"Error happened during processing ore registration of prefix {} and material {}. " +
"Seems like cross-mod compatibility issue. Report to GTCEu github.",
currentOrePrefix, currentMaterial);
}
}
/**
* @deprecated {@link RecipeMapUI#setProgressBar(TextureArea, MoveType)}
*/
@ApiStatus.ScheduledForRemoval(inVersion = "2.9")
@Deprecated
public RecipeMap<R> setProgressBar(TextureArea progressBar, MoveType moveType) {
this.recipeMapUI.setProgressBar(progressBar, moveType);
return this;
}
/**
* @deprecated {@link RecipeMapUI#setItemSlotOverlay(TextureArea, boolean, boolean)}
* {@link RecipeMapUI#setFluidSlotOverlay(TextureArea, boolean, boolean)}
*/
@ApiStatus.ScheduledForRemoval(inVersion = "2.9")
@Deprecated
public RecipeMap<R> setSlotOverlay(boolean isOutput, boolean isFluid, TextureArea slotOverlay) {
return this.setSlotOverlay(isOutput, isFluid, false, slotOverlay).setSlotOverlay(isOutput, isFluid, true,
slotOverlay);
}
/**
* @deprecated {@link RecipeMapUI#setItemSlotOverlay(TextureArea, boolean, boolean)}
* {@link RecipeMapUI#setFluidSlotOverlay(TextureArea, boolean, boolean)}
*/
@ApiStatus.ScheduledForRemoval(inVersion = "2.9")
@Deprecated
public RecipeMap<R> setSlotOverlay(boolean isOutput, boolean isFluid, boolean isLast, TextureArea slotOverlay) {
if (isFluid) {
this.recipeMapUI.setFluidSlotOverlay(slotOverlay, isOutput, isLast);
} else {
this.recipeMapUI.setItemSlotOverlay(slotOverlay, isOutput, isLast);
}
return this;
}
public RecipeMap<R> setSound(SoundEvent sound) {
this.sound = sound;
return this;
}
public RecipeMap<R> setChanceFunction(@NotNull ChanceBoostFunction function) {
chanceFunction = function;
return this;
}
/**
* Add a recipe build action to be performed upon this RecipeMap's builder's recipe registration.
*
* @param name the unique name of the action
* @param action the action to perform
* @return this
*/
public RecipeMap<R> onRecipeBuild(@NotNull ResourceLocation name, @NotNull RecipeBuildAction<R> action) {
if (recipeBuildActions.containsKey(name)) {
throw new IllegalArgumentException("Cannot register RecipeBuildAction with duplicate name: " + name);
}
recipeBuildActions.put(name, action);
return this;
}
/**
* @param name the name of the build action to remove
*/
public void removeBuildAction(@NotNull ResourceLocation name) {
recipeBuildActions.remove(name);
}
/**
* Add a recipe build action to be performed upon this RecipeMap's builder's recipe registration.
*
* @param actions the actions to perform
*/
@ApiStatus.Internal
protected void onRecipeBuild(@NotNull Map<ResourceLocation, RecipeBuildAction<R>> actions) {
recipeBuildActions.putAll(actions);
}
/**
* @return the build actions for this RecipeMap's default RecipeBuilder
*/
@ApiStatus.Internal
protected @UnmodifiableView @NotNull Map<ResourceLocation, RecipeBuildAction<R>> getBuildActions() {
return this.recipeBuildActions;
}
public RecipeMap<R> allowEmptyOutput() {
this.allowEmptyOutput = true;
return this;
}
public RecipeMap<R> setSmallRecipeMap(RecipeMap<?> recipeMap) {
this.smallRecipeMap = recipeMap;
return this;
}
public RecipeMap<? extends RecipeBuilder<?>> getSmallRecipeMap() {
return smallRecipeMap;
}
/**
* Internal usage <strong>only</strong>, use {@link RecipeBuilder#buildAndRegister()}
*
* @param validationResult the validation result from building the recipe
* @return if adding the recipe was successful
*/
public boolean addRecipe(@NotNull ValidationResult<Recipe> validationResult) {
validationResult = postValidateRecipe(validationResult);
switch (validationResult.getType()) {
case SKIP -> {
return false;
}
case INVALID -> {
setFoundInvalidRecipe(true);
return false;
}
}
Recipe recipe = validationResult.getResult();
if (recipe.isGroovyRecipe()) {
this.getGroovyScriptRecipeMap().addScripted(recipe);
}
return compileRecipe(recipe);
}
/**
* Compiles a recipe and adds it to the ingredient tree
*
* @param recipe the recipe to compile
* @return if the recipe was successfully compiled
*/
public boolean compileRecipe(Recipe recipe) {
if (recipe == null) {
return false;
}
List<List<AbstractMapIngredient>> items = fromRecipe(recipe);
if (recurseIngredientTreeAdd(recipe, items, lookup, 0, 0)) {
recipeByCategory.compute(recipe.getRecipeCategory(), (k, v) -> {
if (v == null) v = new ArrayList<>();
v.add(recipe);
return v;
});
return true;
}
return false;
}
/**
* @param recipe the recipe to remove
* @return if removal was successful
*/
public boolean removeRecipe(@NotNull Recipe recipe) {
List<List<AbstractMapIngredient>> items = fromRecipe(recipe);
if (recurseIngredientTreeRemove(recipe, items, lookup, 0) != null) {
if (GroovyScriptModule.isCurrentlyRunning()) {
this.getGroovyScriptRecipeMap().addBackup(recipe);
}
recipeByCategory.compute(recipe.getRecipeCategory(), (k, v) -> {
if (v != null) v.remove(recipe);
return v == null || v.isEmpty() ? null : v;
});
return true;
}
return false;
}
/**
* Removes all recipes.
*
* @see GTRecipeHandler#removeAllRecipes(RecipeMap)
*/
@ApiStatus.Internal
protected void removeAllRecipes() {
if (GroovyScriptModule.isCurrentlyRunning()) {
this.lookup.getRecipes(false).forEach(this.getGroovyScriptRecipeMap()::addBackup);
}
this.lookup.getNodes().clear();
this.lookup.getSpecialNodes().clear();
this.recipeByCategory.clear();
}
/**
* Performs additional validation of recipes before adding to the ingredient tree.
*
* @param validationResult the current validation result
* @return the new result based on validation
*/
@NotNull
protected ValidationResult<Recipe> postValidateRecipe(@NotNull ValidationResult<Recipe> validationResult) {
EnumValidationResult recipeStatus = validationResult.getType();
Recipe recipe = validationResult.getResult();
if (recipe.isGroovyRecipe()) {
return validationResult;
}
boolean emptyInputs = recipe.getInputs().isEmpty() && recipe.getFluidInputs().isEmpty();
if (emptyInputs) {
GTLog.logger.error("Invalid amount of recipe inputs. Recipe inputs are empty.", new Throwable());
if (recipe.getIsCTRecipe()) {
CraftTweakerAPI.logError("Invalid amount of recipe inputs. Recipe inputs are empty.", new Throwable());
}
recipeStatus = EnumValidationResult.INVALID;
}
boolean emptyOutputs = !this.allowEmptyOutput && recipe.getEUt() > 0 && recipe.getOutputs().isEmpty() &&
recipe.getFluidOutputs().isEmpty() && recipe.getChancedOutputs().getChancedEntries().isEmpty() &&
recipe.getChancedFluidOutputs().getChancedEntries().isEmpty();
if (emptyOutputs) {
GTLog.logger.error("Invalid amount of recipe outputs. Recipe outputs are empty.", new Throwable());
if (recipe.getIsCTRecipe()) {
CraftTweakerAPI.logError("Invalid amount of outputs inputs. Recipe outputs are empty.",
new Throwable());
}
recipeStatus = EnumValidationResult.INVALID;
}
int amount = recipe.getInputs().size();
if (amount > getMaxInputs()) {
GTLog.logger.error("Invalid amount of recipe inputs. Actual: {}. Should be at most {}.", amount,
getMaxInputs(), new Throwable());
if (recipe.getIsCTRecipe()) {
CraftTweakerAPI.logError(String.format(
"Invalid amount of recipe inputs. Actual: %s. Should be at most %s.", amount, getMaxInputs()),
new Throwable());
}
recipeStatus = EnumValidationResult.INVALID;
}
amount = recipe.getOutputs().size() + recipe.getChancedOutputs().getChancedEntries().size();
if (amount > getMaxOutputs()) {
GTLog.logger.error("Invalid amount of recipe outputs. Actual: {}. Should be at most {}.", amount,
getMaxOutputs(), new Throwable());
if (recipe.getIsCTRecipe()) {
CraftTweakerAPI
.logError(String.format("Invalid amount of recipe outputs. Actual: %s. Should be at most %s.",
amount, getMaxOutputs()), new Throwable());
}
recipeStatus = EnumValidationResult.INVALID;
}
amount = recipe.getFluidInputs().size();
if (amount > getMaxFluidInputs()) {
GTLog.logger.error("Invalid amount of recipe fluid inputs. Actual: {}. Should be at most {}.", amount,
getMaxFluidInputs(), new Throwable());
if (recipe.getIsCTRecipe()) {
CraftTweakerAPI.logError(
String.format("Invalid amount of recipe fluid inputs. Actual: %s. Should be at most %s.",
amount, getMaxFluidInputs()),
new Throwable());
}
recipeStatus = EnumValidationResult.INVALID;
}
amount = recipe.getFluidOutputs().size() + recipe.getChancedFluidOutputs().getChancedEntries().size();
if (amount > getMaxFluidOutputs()) {
GTLog.logger.error("Invalid amount of recipe fluid outputs. Actual: {}. Should be at most {}.", amount,
getMaxFluidOutputs(), new Throwable());
if (recipe.getIsCTRecipe()) {
CraftTweakerAPI.logError(
String.format("Invalid amount of recipe fluid outputs. Actual: %s. Should be at most %s.",
amount, getMaxFluidOutputs()),
new Throwable());
}
recipeStatus = EnumValidationResult.INVALID;
}
return ValidationResult.newResult(recipeStatus, recipe);
}
@Nullable
public Recipe findRecipe(long voltage, IItemHandlerModifiable inputs, IMultipleTankHandler fluidInputs) {
return this.findRecipe(voltage, GTUtility.itemHandlerToList(inputs), GTUtility.fluidHandlerToList(fluidInputs));
}
/**
* Finds a Recipe matching the Fluid and/or ItemStack Inputs.
*
* @param voltage Voltage of the Machine or Long.MAX_VALUE if it has no Voltage
* @param inputs the Item Inputs
* @param fluidInputs the Fluid Inputs
* @return the Recipe it has found or null for no matching Recipe
*/
@Nullable
public Recipe findRecipe(long voltage, List<ItemStack> inputs, List<FluidStack> fluidInputs) {
return findRecipe(voltage, inputs, fluidInputs, false);
}
/**
* Finds a Recipe matching the Fluid and/or ItemStack Inputs.
*
* @param voltage Voltage of the Machine or Long.MAX_VALUE if it has no Voltage
* @param inputs the Item Inputs
* @param fluidInputs the Fluid Inputs
* @param exactVoltage should require exact voltage matching on recipe. used by craftweaker
* @return the Recipe it has found or null for no matching Recipe
*/
@Nullable
public Recipe findRecipe(long voltage, final List<ItemStack> inputs, final List<FluidStack> fluidInputs,
boolean exactVoltage) {
final List<ItemStack> items = inputs.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
final List<FluidStack> fluids = fluidInputs.stream().filter(f -> f != null && f.amount != 0)
.collect(Collectors.toList());
return find(items, fluids, recipe -> {
if (exactVoltage && recipe.getEUt() != voltage) {
// if exact voltage is required, the recipe is not considered valid
return false;
}
if (recipe.getEUt() > voltage) {
// there is not enough voltage to consider the recipe valid
return false;
}
return recipe.matches(false, inputs, fluidInputs);
});
}
/**
* Prepares Items and Fluids for use in recipe search
*
* @param items the items to prepare
* @param fluids the fluids to prepare
* @return a List of Lists of AbstractMapIngredients used for finding recipes
*/
@Nullable
protected List<List<AbstractMapIngredient>> prepareRecipeFind(@NotNull Collection<ItemStack> items,
@NotNull Collection<FluidStack> fluids) {
// First, check if items and fluids are valid.
if (items.size() == Integer.MAX_VALUE || fluids.size() == Integer.MAX_VALUE) {
return null;
}
if (items.size() == 0 && fluids.size() == 0) {
return null;
}
// Build input.
List<List<AbstractMapIngredient>> list = new ObjectArrayList<>(items.size() + fluids.size());
if (items.size() > 0) buildFromItemStacks(list, uniqueItems(items));
if (fluids.size() > 0) buildFromFluidStacks(list, fluids);
// nothing was added, so return nothing
if (list.size() == 0) return null;
return list;
}
/**
* Finds a recipe using Items and Fluids.
*
* @param items a collection of items
* @param fluids a collection of fluids
* @param canHandle a predicate for determining if a recipe is valid
* @return the recipe found
*/
@Nullable
public Recipe find(@NotNull Collection<ItemStack> items, @NotNull Collection<FluidStack> fluids,
@NotNull Predicate<Recipe> canHandle) {
List<List<AbstractMapIngredient>> list = prepareRecipeFind(items, fluids);
// couldn't build any inputs to use for search, so no recipe could be found
if (list == null) return null;
return recurseIngredientTreeFindRecipe(list, lookup, canHandle);
}
/**
* Builds a list of unique ItemStacks from the given Collection of ItemStacks.
* Used to reduce the number inputs, if for example there is more than one of the same input,
* pack them into one.
* This uses a strict comparison, so it will not pack the same item with different NBT tags,
* to allow the presence of, for example, more than one configured circuit in the input.
*
* @param inputs The Collection of GTRecipeInputs.
* @return an array of unique itemstacks.
*/
@NotNull
public static ItemStack[] uniqueItems(@NotNull Collection<ItemStack> inputs) {
int index = 0;
ItemStack[] uniqueItems = new ItemStack[inputs.size()];
main:
for (ItemStack input : inputs) {
if (input.isEmpty()) {
continue;
}
if (index > 0) {
for (ItemStack unique : uniqueItems) {
if (unique == null) break;
else if (input.isItemEqual(unique) && ItemStack.areItemStackTagsEqual(input, unique)) {
continue main;
}
}
}
uniqueItems[index++] = input;
}
if (index == uniqueItems.length) {
return uniqueItems;
}
ItemStack[] retUniqueItems = new ItemStack[index];
System.arraycopy(uniqueItems, 0, retUniqueItems, 0, index);
return retUniqueItems;
}
/**
* Builds a list of unique inputs from the given list GTRecipeInputs.
* Used to reduce the number inputs, if for example there is more than one of the same input, pack them into one.
*
* @param inputs The list of GTRecipeInputs.
* @return The list of unique inputs.
*/
@NotNull
public static List<GTRecipeInput> uniqueIngredientsList(@NotNull Collection<GTRecipeInput> inputs) {
List<GTRecipeInput> list = new ObjectArrayList<>(inputs.size());
for (GTRecipeInput item : inputs) {
boolean isEqual = false;
for (GTRecipeInput obj : list) {
if (item.equalIgnoreAmount(obj)) {
isEqual = true;
break;
}
}
if (isEqual) continue;
if (item instanceof IntCircuitIngredient) {
list.add(0, item);
} else {
list.add(item);
}
}
return list;
}
/**
* Recursively finds a recipe, top level.
*
* @param ingredients the ingredients part
* @param branchRoot the root branch to search from.
* @param canHandle if the found recipe is valid
* @return a recipe
*/
@Nullable
private Recipe recurseIngredientTreeFindRecipe(@NotNull List<List<AbstractMapIngredient>> ingredients,
@NotNull Branch branchRoot, @NotNull Predicate<Recipe> canHandle) {
// Try each ingredient as a starting point, adding it to the skip-list.
// The skip-list is a packed long, where each 1 bit represents an index to skip
for (int i = 0; i < ingredients.size(); i++) {
Recipe r = recurseIngredientTreeFindRecipe(ingredients, branchRoot, canHandle, i, 0, (1L << i));
if (r != null) {
return r;
}
}
return null;
}
/**
* Recursively finds a recipe
*
* @param ingredients the ingredients part
* @param branchMap the current branch of the tree
* @param canHandle predicate to test found recipe.
* @param index the index of the wrapper to get
* @param count how deep we are in recursion, < ingredients.length
* @param skip bitmap of ingredients to skip, i.e. which ingredients are already used in the recursion.
* @return a recipe
*/
@Nullable
private Recipe recurseIngredientTreeFindRecipe(@NotNull List<List<AbstractMapIngredient>> ingredients,
@NotNull Branch branchMap, @NotNull Predicate<Recipe> canHandle,
int index, int count, long skip) {
// exhausted all the ingredients, and didn't find anything
if (count == ingredients.size()) return null;
// Iterate over current level of nodes.
for (AbstractMapIngredient obj : ingredients.get(index)) {
// determine the root nodes
Map<AbstractMapIngredient, Either<Recipe, Branch>> targetMap = determineRootNodes(obj, branchMap);
Either<Recipe, Branch> result = targetMap.get(obj);
if (result != null) {
// if there is a recipe (left mapping), return it immediately as found, if it can be handled
// Otherwise, recurse and go to the next branch.
Recipe r = result.map(potentialRecipe -> canHandle.test(potentialRecipe) ? potentialRecipe : null,
potentialBranch -> diveIngredientTreeFindRecipe(ingredients, potentialBranch, canHandle, index,
count, skip));
if (r != null) {
return r;
}
}
}
return null;
}
/**
* Recursively finds a recipe
*
* @param ingredients the ingredients part
* @param map the current branch of the tree
* @param canHandle predicate to test found recipe.
* @param currentIndex the index of the wrapper to get
* @param count how deep we are in recursion, < ingredients.length
* @param skip bitmap of ingredients to skip, i.e. which ingredients are already used in the recursion.
* @return a recipe
*/
@Nullable
private Recipe diveIngredientTreeFindRecipe(@NotNull List<List<AbstractMapIngredient>> ingredients,
@NotNull Branch map,
@NotNull Predicate<Recipe> canHandle, int currentIndex, int count,
long skip) {
// We loop around ingredients.size() if we reach the end.
// only end when all ingredients are exhausted, or a recipe is found
int i = (currentIndex + 1) % ingredients.size();
while (i != currentIndex) {
// Have we already used this ingredient? If so, skip this one.
if (((skip & (1L << i)) == 0)) {
// Recursive call
// Increase the count, so the recursion can terminate if needed (ingredients is exhausted)
// Append the current index to the skip list
Recipe found = recurseIngredientTreeFindRecipe(ingredients, map, canHandle, i, count + 1,
skip | (1L << i));
if (found != null) {
return found;
}
}
// increment the index if the current index is skipped, or the recipe is not found
i = (i + 1) % ingredients.size();
}
return null;
}
/**
* Exhaustively gathers all recipes that can be crafted with the given ingredients, into a Set.
*
* @param items the ingredients, in the form of a List of ItemStack. Usually the inputs of a Recipe
* @param fluids the ingredients, in the form of a List of FluidStack. Usually the inputs of a Recipe
* @return a Set of recipes that can be crafted with the given ingredients
*/
@Nullable
public Set<Recipe> findRecipeCollisions(Collection<ItemStack> items, Collection<FluidStack> fluids) {
List<List<AbstractMapIngredient>> list = prepareRecipeFind(items, fluids);
if (list == null) return null;
Set<Recipe> collidingRecipes = new ObjectOpenHashSet<>();
recurseIngredientTreeFindRecipeCollisions(list, lookup, collidingRecipes);
return collidingRecipes;
}
/**
* @param ingredients the ingredients to search with
* @param branchRoot the root branch to start searching from
* @param collidingRecipes the list to store recipe collisions
*/
private void recurseIngredientTreeFindRecipeCollisions(@NotNull List<List<AbstractMapIngredient>> ingredients,
@NotNull Branch branchRoot,
@NotNull Set<Recipe> collidingRecipes) {
// Try each ingredient as a starting point, adding it to the skip-list.
// The skip-list is a packed long, where each 1 bit represents an index to skip
for (int i = 0; i < ingredients.size(); i++) {
recurseIngredientTreeFindRecipeCollisions(ingredients, branchRoot, i, 0, (1L << i), collidingRecipes);
}
}
/**
* Recursively finds all colliding recipes
*
* @param ingredients the ingredients part
* @param branchMap the current branch of the tree
* @param index the index of the wrapper to get
* @param count how deep we are in recursion, < ingredients.length
* @param skip bitmap of ingredients to skip, i.e. which ingredients are already used in the recursion.
* @param collidingRecipes the set to store the recipes in
*/
@Nullable
private Recipe recurseIngredientTreeFindRecipeCollisions(@NotNull List<List<AbstractMapIngredient>> ingredients,
@NotNull Branch branchMap, int index, int count, long skip,
@NotNull Set<Recipe> collidingRecipes) {
// exhausted all the ingredients, and didn't find anything
if (count == ingredients.size()) return null;
List<AbstractMapIngredient> wr = ingredients.get(index);
// Iterate over current level of nodes.
for (AbstractMapIngredient obj : wr) {
// determine the root nodes
Map<AbstractMapIngredient, Either<Recipe, Branch>> targetMap = determineRootNodes(obj, branchMap);
Either<Recipe, Branch> result = targetMap.get(obj);
if (result != null) {
// if there is a recipe (left mapping), return it immediately as found
// Otherwise, recurse and go to the next branch.
Recipe r = result.map(recipe -> recipe,
right -> diveIngredientTreeFindRecipeCollisions(ingredients, right, index, count, skip,
collidingRecipes));
if (r != null) {
collidingRecipes.add(r);
}
}
}
return null;
}
/**
* Recursively finds a recipe
*
* @param ingredients the ingredients part
* @param map the current branch of the tree
* @param currentIndex the index of the wrapper to get
* @param count how deep we are in recursion, < ingredients.length
* @param skip bitmap of ingredients to skip, i.e. which ingredients are already used in the recursion.
* @param collidingRecipes the set to store the recipes in
* @return a recipe
*/
@Nullable
private Recipe diveIngredientTreeFindRecipeCollisions(@NotNull List<List<AbstractMapIngredient>> ingredients,
@NotNull Branch map, int currentIndex, int count, long skip,
@NotNull Set<Recipe> collidingRecipes) {
// We loop around ingredients.size() if we reach the end.
// only end when all ingredients are exhausted, or a recipe is found
int i = (currentIndex + 1) % ingredients.size();
while (i != currentIndex) {
// Have we already used this ingredient? If so, skip this one.
if (((skip & (1L << i)) == 0)) {
// Recursive call
// Increase the count, so the recursion can terminate if needed (ingredients is exhausted)
// Append the current index to the skip list
Recipe r = recurseIngredientTreeFindRecipeCollisions(ingredients, map, i, count + 1, skip | (1L << i),
collidingRecipes);
if (r != null) {
return r;
}
}
// increment the index if the current index is skipped, or the recipe is not found
i = (i + 1) % ingredients.size();
}
return null;
}
/**
* @deprecated {@link RecipeMapUI#createJeiUITemplate(IItemHandlerModifiable, IItemHandlerModifiable, FluidTankList, FluidTankList, int)}
*/
@ApiStatus.ScheduledForRemoval(inVersion = "2.9")
@Deprecated
public ModularUI.Builder createJeiUITemplate(IItemHandlerModifiable importItems, IItemHandlerModifiable exportItems,
FluidTankList importFluids, FluidTankList exportFluids, int yOffset) {
return recipeMapUI.createJeiUITemplate(importItems, exportItems, importFluids, exportFluids, yOffset);
}
/**
* @deprecated {@link RecipeMapUI#createUITemplate(DoubleSupplier, IItemHandlerModifiable, IItemHandlerModifiable, FluidTankList, FluidTankList, int)}
*/
@ApiStatus.ScheduledForRemoval(inVersion = "2.9")
@Deprecated
public ModularUI.Builder createUITemplate(DoubleSupplier progressSupplier, IItemHandlerModifiable importItems,
IItemHandlerModifiable exportItems, FluidTankList importFluids,
FluidTankList exportFluids, int yOffset) {
return recipeMapUI.createUITemplate(progressSupplier, importItems, exportItems, importFluids, exportFluids,
yOffset);
}
/**
* @deprecated {@link RecipeMapUI#createUITemplateNoOutputs(DoubleSupplier, IItemHandlerModifiable, IItemHandlerModifiable, FluidTankList, FluidTankList, int)}
*/
@ApiStatus.ScheduledForRemoval(inVersion = "2.9")
@Deprecated
public ModularUI.Builder createUITemplateNoOutputs(DoubleSupplier progressSupplier,
IItemHandlerModifiable importItems,
IItemHandlerModifiable exportItems, FluidTankList importFluids,
FluidTankList exportFluids, int yOffset) {
return recipeMapUI.createUITemplateNoOutputs(progressSupplier, importItems, exportItems, importFluids,
exportFluids, yOffset);
}
/**
* @deprecated {@link RecipeMapUI#addInventorySlotGroup(ModularUI.Builder, IItemHandlerModifiable, FluidTankList, boolean, int)}
*/
@ApiStatus.ScheduledForRemoval(inVersion = "2.9")
@Deprecated
protected void addInventorySlotGroup(ModularUI.Builder builder, IItemHandlerModifiable itemHandler,
FluidTankList fluidHandler, boolean isOutputs, int yOffset) {}
/**
* @deprecated {@link RecipeMapUI#addSlot(ModularUI.Builder, int, int, int, IItemHandlerModifiable, FluidTankList, boolean, boolean)}
*/
@ApiStatus.ScheduledForRemoval(inVersion = "2.9")
@Deprecated
protected void addSlot(ModularUI.Builder builder, int x, int y, int slotIndex, IItemHandlerModifiable itemHandler,
FluidTankList fluidHandler, boolean isFluid, boolean isOutputs) {}
/**
* @deprecated {@link RecipeMapUI#getOverlaysForSlot(boolean, boolean, boolean)}
*/
@ApiStatus.ScheduledForRemoval(inVersion = "2.9")
@Deprecated
protected TextureArea[] getOverlaysForSlot(boolean isOutput, boolean isFluid, boolean isLast) {
return null;
}
/**
* @deprecated {@link RecipeMapUI#getPropertyHeightShift()}
*/
@ApiStatus.ScheduledForRemoval(inVersion = "2.9")
@Deprecated
public int getPropertyHeightShift() {
return recipeMapUI.getPropertyHeightShift();
}
/**
* @deprecated {@link RecipeMapUI#shouldShiftWidgets()}
*/
@ApiStatus.ScheduledForRemoval(inVersion = "2.9")
@Deprecated
private boolean shouldShiftWidgets() {
return false;
}
@Method(modid = Mods.Names.GROOVY_SCRIPT)
private VirtualizedRecipeMap getGroovyScriptRecipeMap() {
return ((VirtualizedRecipeMap) grsVirtualizedRecipeMap);
}
/**
* This height is used to determine Y position to start drawing info on JEI.
*
* @deprecated remove overrides, this method is no longer used in any way.
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2.9")
public int getPropertyListHeight(Recipe recipe) {
return 0;
}
/**
* Adds a recipe to the map. (recursive part)
*
* @param recipe the recipe to add.
* @param ingredients list of input ingredients representing the recipe.
* @param branchMap the current branch in the recursion.
* @param index where in the ingredients list we are.
* @param count how many branches were added already.
*/
private boolean recurseIngredientTreeAdd(@NotNull Recipe recipe,
@NotNull List<List<AbstractMapIngredient>> ingredients,
@NotNull Branch branchMap, int index, int count) {
if (count >= ingredients.size()) return true;
if (index >= ingredients.size()) {
throw new IllegalStateException("Index out of bounds for recurseItemTreeAdd, should not happen");
}
// Loop through NUMBER_OF_INGREDIENTS times.
// the current contents to be added to a node in the branch
final List<AbstractMapIngredient> current = ingredients.get(index);
final Branch branchRight = new Branch();
Either<Recipe, Branch> r;
// for every ingredient, add it to a node
for (AbstractMapIngredient obj : current) {
// determine the root nodes
Map<AbstractMapIngredient, Either<Recipe, Branch>> targetMap = determineRootNodes(obj, branchMap);
// Either add the recipe or create a branch.
r = targetMap.compute(obj, (k, v) -> {
if (count == ingredients.size() - 1) {
// handle very last ingredient
if (v != null) {
// handle the existing branch
if (!v.left().isPresent() || v.left().get() != recipe) {
// the recipe already there was not the one being added, so there is a conflict
if (recipe.getIsCTRecipe()) {
CraftTweakerAPI.logError(String.format(
"Recipe duplicate or conflict found in RecipeMap %s and was not added. See next lines for details.",
this.unlocalizedName));
CraftTweakerAPI.logError(String.format("Attempted to add Recipe: %s",
CTRecipeHelper.getRecipeAddLine(this, recipe)));
if (v.left().isPresent()) {
CraftTweakerAPI.logError(String.format("Which conflicts with: %s",
CTRecipeHelper.getRecipeAddLine(this, v.left().get())));
} else {
CraftTweakerAPI.logError("Could not identify exact duplicate/conflict.");
}
}
if (recipe.isGroovyRecipe()) {
GroovyLog log = GroovyLog.get();
log.warn(
"Recipe duplicate or conflict found in RecipeMap {} and was not added. See next lines for details",
this.unlocalizedName);
log.warn("Attempted to add Recipe: {}", recipe.toString());
if (v.left().isPresent()) {
log.warn("Which conflicts with: {}", v.left().get().toString());
} else {
log.warn("Could not find exact duplicate/conflict.");
}
}
if (ConfigHolder.misc.debug || GTValues.isDeobfEnvironment()) {
GTLog.logger.warn(
"Recipe duplicate or conflict found in RecipeMap {} and was not added. See next lines for details",
this.unlocalizedName);
GTLog.logger.warn("Attempted to add Recipe: {}", recipe.toString());
if (v.left().isPresent()) {
GTLog.logger.warn("Which conflicts with: {}", v.left().get().toString());
} else {
GTLog.logger.warn("Could not find exact duplicate/conflict.");
}
}
}
// Return the existing recipe, even on conflicts.
// If there was no conflict but a recipe was still present, it was added on an earlier recurse,
// and this will carry the result further back in the call stack
return v;
} else {
// nothing exists for this path, so end with the recipe