/
StackHelper.java
619 lines (535 loc) · 18.5 KB
/
StackHelper.java
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
package mezz.jei.util;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import mezz.jei.Internal;
import mezz.jei.api.ISubtypeRegistry;
import mezz.jei.api.gui.IGuiIngredient;
import mezz.jei.api.recipe.IStackHelper;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.oredict.OreDictionary;
public class StackHelper implements IStackHelper {
public static final String nullItemInStack = "Found an itemStack with a null item. This is an error from another mod.";
/** Uids are cached during loading to improve startup performance. */
private final Map<UidMode, Map<ItemStack, String>> uidCache = new EnumMap<UidMode, Map<ItemStack, String>>(UidMode.class);
private boolean uidCacheEnabled = true;
public StackHelper() {
for (UidMode mode : UidMode.values()) {
uidCache.put(mode, new HashMap<ItemStack, String>());
}
}
public void enableUidCache() {
uidCacheEnabled = true;
}
public void disableUidCache() {
for (UidMode mode : UidMode.values()) {
uidCache.get(mode).clear();
}
uidCacheEnabled = false;
}
@Nullable
public String getOreDictEquivalent(Collection<ItemStack> itemStacks) {
if (itemStacks.size() < 2) {
return null;
}
final ItemStack firstStack = itemStacks.iterator().next();
if (firstStack != null) {
for (final int oreId : OreDictionary.getOreIDs(firstStack)) {
final String oreName = OreDictionary.getOreName(oreId);
List<ItemStack> ores = OreDictionary.getOres(oreName);
ores = getAllSubtypes(ores);
if (containsSameStacks(itemStacks, ores)) {
return oreName;
}
}
}
return null;
}
/**
* Returns a list of items in slots that complete the recipe defined by requiredStacksList.
* Returns a result that contains missingItems if there are not enough items in availableItemStacks.
*/
public MatchingItemsResult getMatchingItems(Map<Integer, ItemStack> availableItemStacks, Map<Integer, ? extends IGuiIngredient<ItemStack>> ingredientsMap) {
MatchingItemsResult matchingItemResult = new MatchingItemsResult();
int recipeSlotNumber = -1;
SortedSet<Integer> keys = new TreeSet<Integer>(ingredientsMap.keySet());
for (Integer key : keys) {
IGuiIngredient<ItemStack> ingredient = ingredientsMap.get(key);
if (!ingredient.isInput()) {
continue;
}
recipeSlotNumber++;
List<ItemStack> requiredStacks = ingredient.getAllIngredients();
if (requiredStacks.isEmpty()) {
continue;
}
Integer matching = containsAnyStackIndexed(availableItemStacks, requiredStacks);
if (matching == null) {
matchingItemResult.missingItems.add(key);
} else {
ItemStack matchingStack = availableItemStacks.get(matching);
matchingStack.stackSize--;
if (matchingStack.stackSize == 0) {
availableItemStacks.remove(matching);
}
matchingItemResult.matchingItems.put(recipeSlotNumber, matching);
}
}
return matchingItemResult;
}
/**
* Get the slot which contains a specific itemStack.
*
* @param container the container to search
* @param slotNumbers the slots in the container to search
* @param itemStack the itemStack to find
* @return the slot that contains the itemStack. returns null if no slot contains the itemStack.
*/
@Nullable
public Slot getSlotWithStack(Container container, Iterable<Integer> slotNumbers, ItemStack itemStack) {
for (Integer slotNumber : slotNumbers) {
if (slotNumber >= 0 && slotNumber < container.inventorySlots.size()) {
Slot slot = container.getSlot(slotNumber);
ItemStack slotStack = slot.getStack();
if (ItemStack.areItemsEqual(itemStack, slotStack) && ItemStack.areItemStackTagsEqual(itemStack, slotStack)) {
return slot;
}
}
}
return null;
}
public boolean containsSameStacks(Collection<ItemStack> stacks, Collection<ItemStack> contains) {
return containsSameStacks(new MatchingIterable(stacks), new MatchingIterable(contains));
}
/** Returns true if all stacks from "contains" are found in "stacks" and the opposite is true as well. */
public <R> boolean containsSameStacks(Iterable<ItemStackMatchable<R>> stacks, Iterable<ItemStackMatchable<R>> contains) {
for (ItemStackMatchable stack : contains) {
if (containsStack(stacks, stack) == null) {
return false;
}
}
for (ItemStackMatchable stack : stacks) {
if (containsStack(contains, stack) == null) {
return false;
}
}
return true;
}
@Nullable
public Integer containsAnyStackIndexed(@Nullable Map<Integer, ItemStack> stacks, @Nullable Iterable<ItemStack> contains) {
MatchingIndexed matchingStacks = new MatchingIndexed(stacks);
MatchingIterable matchingContains = new MatchingIterable(contains);
return containsStackMatchable(matchingStacks, matchingContains);
}
@Nullable
public ItemStack containsStack(@Nullable Iterable<ItemStack> stacks, @Nullable ItemStack contains) {
List<ItemStack> containsList = contains == null ? null : Collections.singletonList(contains);
return containsAnyStack(stacks, containsList);
}
@Nullable
public ItemStack containsAnyStack(@Nullable Iterable<ItemStack> stacks, @Nullable Iterable<ItemStack> contains) {
MatchingIterable matchingStacks = new MatchingIterable(stacks);
MatchingIterable matchingContains = new MatchingIterable(contains);
return containsStackMatchable(matchingStacks, matchingContains);
}
/* Returns an ItemStack from "stacks" if it isEquivalent to an ItemStack from "contains" */
@Nullable
public <R, T> R containsStackMatchable(Iterable<ItemStackMatchable<R>> stacks, Iterable<ItemStackMatchable<T>> contains) {
for (ItemStackMatchable<?> containStack : contains) {
R matchingStack = containsStack(stacks, containStack);
if (matchingStack != null) {
return matchingStack;
}
}
return null;
}
/* Returns an ItemStack from "stacks" if it isEquivalent to "contains" */
@Nullable
public <R> R containsStack(Iterable<ItemStackMatchable<R>> stacks, ItemStackMatchable<?> contains) {
for (ItemStackMatchable<R> stack : stacks) {
if (isEquivalent(contains.getStack(), stack.getStack())) {
return stack.getResult();
}
}
return null;
}
/**
* Similar to ItemStack.areItemStacksEqual but ignores NBT on items without subtypes, and uses the {@link ISubtypeRegistry}
*/
public boolean isEquivalent(@Nullable ItemStack lhs, @Nullable ItemStack rhs) {
if (lhs == rhs) {
return true;
}
if (lhs == null || rhs == null) {
return false;
}
if (lhs.getItem() != rhs.getItem()) {
return false;
}
if (lhs.getMetadata() != OreDictionary.WILDCARD_VALUE) {
if (lhs.getMetadata() != rhs.getMetadata()) {
return false;
}
}
if (lhs.getHasSubtypes()) {
String keyLhs = getUniqueIdentifierForStack(lhs, UidMode.NORMAL);
String keyRhs = getUniqueIdentifierForStack(rhs, UidMode.NORMAL);
return Java6Helper.equals(keyLhs, keyRhs);
} else {
return true;
}
}
@Override
public List<ItemStack> getSubtypes(@Nullable ItemStack itemStack) {
if (itemStack == null) {
Log.error("Null itemStack", new NullPointerException());
return Collections.emptyList();
}
Item item = itemStack.getItem();
if (item == null) {
Log.error("Null item in itemStack", new NullPointerException());
return Collections.emptyList();
}
if (itemStack.getItemDamage() != OreDictionary.WILDCARD_VALUE) {
return Collections.singletonList(itemStack);
}
return getSubtypes(item, itemStack.stackSize);
}
public List<ItemStack> getSubtypes(final Item item, final int stackSize) {
List<ItemStack> itemStacks = new ArrayList<ItemStack>();
for (CreativeTabs itemTab : item.getCreativeTabs()) {
List<ItemStack> subItems = new ArrayList<ItemStack>();
try {
item.getSubItems(item, itemTab, subItems);
} catch (RuntimeException e) {
Log.warning("Caught a crash while getting sub-items of {}", item, e);
} catch (LinkageError e) {
Log.warning("Caught a crash while getting sub-items of {}", item, e);
}
for (ItemStack subItem : subItems) {
if (subItem == null) {
Log.warning("Found a null subItem of {}", item);
} else if (subItem.getItem() == null) {
Log.warning("Found a subItem of {} with a null item", item);
} else {
if (subItem.stackSize != stackSize) {
ItemStack subItemCopy = subItem.copy();
subItemCopy.stackSize = stackSize;
itemStacks.add(subItemCopy);
} else {
itemStacks.add(subItem);
}
}
}
}
return itemStacks;
}
@Override
public List<ItemStack> getAllSubtypes(@Nullable Iterable stacks) {
if (stacks == null) {
Log.error("Null stacks", new NullPointerException());
return Collections.emptyList();
}
List<ItemStack> allSubtypes = new ArrayList<ItemStack>();
getAllSubtypes(allSubtypes, stacks);
if (isAllNulls(allSubtypes)) {
return Collections.emptyList();
}
return allSubtypes;
}
private static boolean isAllNulls(Iterable<?> iterable) {
for (Object element : iterable) {
if (element != null) {
return false;
}
}
return true;
}
private void getAllSubtypes(List<ItemStack> subtypesList, Iterable stacks) {
for (Object obj : stacks) {
if (obj instanceof ItemStack) {
ItemStack itemStack = (ItemStack) obj;
List<ItemStack> subtypes = getSubtypes(itemStack);
subtypesList.addAll(subtypes);
} else if (obj instanceof Iterable) {
getAllSubtypes(subtypesList, (Iterable) obj);
} else if (obj != null) {
Log.error("Unknown object found: {}", obj);
} else {
subtypesList.add(null);
}
}
}
@Override
public List<List<ItemStack>> expandRecipeItemStackInputs(@Nullable List inputs) {
if (inputs == null) {
return Collections.emptyList();
}
List<List<ItemStack>> expandedInputs = new ArrayList<List<ItemStack>>();
for (Object input : inputs) {
List<ItemStack> expandedInput = toItemStackList(input);
expandedInputs.add(expandedInput);
}
return expandedInputs;
}
@Override
public List<ItemStack> toItemStackList(@Nullable Object stacks) {
if (stacks == null) {
return Collections.emptyList();
}
UniqueIngredientListBuilder<ItemStack> ingredientListBuilder = new UniqueIngredientListBuilder<ItemStack>(ItemStack.class);
toItemStackList(ingredientListBuilder, stacks);
return ingredientListBuilder.build();
}
private void toItemStackList(UniqueIngredientListBuilder<ItemStack> ingredientListBuilder, @Nullable Object input) {
if (input instanceof ItemStack) {
ItemStack stack = (ItemStack) input;
if (stack.getMetadata() == OreDictionary.WILDCARD_VALUE) {
List<ItemStack> subtypes = getSubtypes(stack);
for (ItemStack subtype : subtypes) {
ingredientListBuilder.add(subtype);
}
} else {
ingredientListBuilder.add(stack);
}
} else if (input instanceof String) {
List<ItemStack> stacks = OreDictionary.getOres((String) input);
for (ItemStack stack : stacks) {
ingredientListBuilder.add(stack);
}
} else if (input instanceof Iterable) {
for (Object obj : (Iterable) input) {
toItemStackList(ingredientListBuilder, obj);
}
} else if (input != null) {
Log.error("Unknown object found: {}", input);
}
}
public String getUniqueIdentifierForStack(ItemStack stack) {
return getUniqueIdentifierForStack(stack, UidMode.NORMAL);
}
public String getUniqueIdentifierForStack(ItemStack stack, UidMode mode) {
if (uidCacheEnabled) {
String result = uidCache.get(mode).get(stack);
if (result != null) {
return result;
}
}
Item item = stack.getItem();
if (item == null) {
throw new NullPointerException(nullItemInStack);
}
ResourceLocation itemName = item.getRegistryName();
if (itemName == null) {
String stackInfo = ErrorUtil.getItemStackInfo(stack);
throw new NullPointerException("Item has no registry name: " + stackInfo);
}
StringBuilder itemKey = new StringBuilder(itemName.toString());
if (mode != UidMode.WILDCARD) {
ISubtypeRegistry subtypeRegistry = Internal.getHelpers().getSubtypeRegistry();
String subtypeInfo = subtypeRegistry.getSubtypeInfo(stack);
if (subtypeInfo != null) {
itemKey.append(':').append(subtypeInfo);
}
}
int metadata = stack.getMetadata();
if (mode == UidMode.WILDCARD || metadata == OreDictionary.WILDCARD_VALUE) {
return itemKey.toString();
}
if (mode == UidMode.FULL) {
itemKey.append(':').append(metadata);
NBTTagCompound serializedNbt = stack.serializeNBT();
NBTTagCompound nbtTagCompound = serializedNbt.getCompoundTag("tag").copy();
if (serializedNbt.hasKey("ForgeCaps")) {
NBTTagCompound forgeCaps = serializedNbt.getCompoundTag("ForgeCaps");
if (!forgeCaps.hasNoTags()) { // ForgeCaps should never be empty
nbtTagCompound.setTag("ForgeCaps", forgeCaps);
}
}
if (!nbtTagCompound.hasNoTags()) {
itemKey.append(':').append(nbtTagCompound);
}
} else if (stack.getHasSubtypes()) {
itemKey.append(':').append(metadata);
}
String result = itemKey.toString();
if (uidCacheEnabled) {
uidCache.get(mode).put(stack, result);
}
return result;
}
public enum UidMode {
NORMAL, WILDCARD, FULL
}
public List<String> getUniqueIdentifiersWithWildcard(ItemStack itemStack) {
String uid = getUniqueIdentifierForStack(itemStack, UidMode.NORMAL);
String uidWild = getUniqueIdentifierForStack(itemStack, UidMode.WILDCARD);
if (uid.equals(uidWild)) {
return Collections.singletonList(uid);
} else {
return Arrays.asList(uid, uidWild);
}
}
public int addStack(Container container, Collection<Integer> slotIndexes, ItemStack stack, boolean doAdd) {
int added = 0;
// Add to existing stacks first
for (final Integer slotIndex : slotIndexes) {
if (slotIndex >= 0 && slotIndex < container.inventorySlots.size()) {
final Slot slot = container.getSlot(slotIndex);
final ItemStack inventoryStack = slot.getStack();
// Check that the slot's contents are stackable with this stack
if (inventoryStack != null &&
inventoryStack.getItem() != null &&
inventoryStack.isStackable() &&
inventoryStack.isItemEqual(stack) &&
ItemStack.areItemStackTagsEqual(inventoryStack, stack)) {
final int remain = stack.stackSize - added;
final int maxStackSize = Math.min(slot.getItemStackLimit(inventoryStack), inventoryStack.getMaxStackSize());
final int space = maxStackSize - inventoryStack.stackSize;
if (space > 0) {
// Enough space
if (space >= remain) {
if (doAdd) {
inventoryStack.stackSize += remain;
}
return stack.stackSize;
}
// Not enough space
if (doAdd) {
inventoryStack.stackSize = inventoryStack.getMaxStackSize();
}
added += space;
}
}
}
}
if (added >= stack.stackSize) {
return added;
}
for (final Integer slotIndex : slotIndexes) {
if (slotIndex >= 0 && slotIndex < container.inventorySlots.size()) {
final Slot slot = container.getSlot(slotIndex);
final ItemStack inventoryStack = slot.getStack();
if (inventoryStack == null) {
if (doAdd) {
ItemStack stackToAdd = stack.copy();
stackToAdd.stackSize = stack.stackSize - added;
slot.putStack(stackToAdd);
}
return stack.stackSize;
}
}
}
return added;
}
public static class MatchingItemsResult {
@Nonnull
public final Map<Integer, Integer> matchingItems = new HashMap<Integer, Integer>();
@Nonnull
public final List<Integer> missingItems = new ArrayList<Integer>();
}
private interface ItemStackMatchable<R> {
@Nullable
ItemStack getStack();
@Nullable
R getResult();
}
private static abstract class DelegateIterator<T, R> implements Iterator<R> {
@Nonnull
protected final Iterator<T> delegate;
public DelegateIterator(Iterator<T> delegate) {
this.delegate = delegate;
}
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public void remove() {
delegate.remove();
}
}
private static class MatchingIterable implements Iterable<ItemStackMatchable<ItemStack>> {
@Nonnull
private final Iterable<ItemStack> list;
public MatchingIterable(@Nullable Iterable<ItemStack> list) {
if (list == null) {
this.list = Collections.emptyList();
} else {
this.list = list;
}
}
@Nonnull
@Override
public Iterator<ItemStackMatchable<ItemStack>> iterator() {
Iterator<ItemStack> stacks = list.iterator();
return new DelegateIterator<ItemStack, ItemStackMatchable<ItemStack>>(stacks) {
@Override
public ItemStackMatchable<ItemStack> next() {
final ItemStack stack = delegate.next();
return new ItemStackMatchable<ItemStack>() {
@Nullable
@Override
public ItemStack getStack() {
return stack;
}
@Nullable
@Override
public ItemStack getResult() {
return stack;
}
};
}
};
}
}
private static class MatchingIndexed implements Iterable<ItemStackMatchable<Integer>> {
@Nonnull
private final Map<Integer, ItemStack> map;
public MatchingIndexed(@Nullable Map<Integer, ItemStack> map) {
if (map == null) {
this.map = Collections.emptyMap();
} else {
this.map = map;
}
}
@Nonnull
@Override
public Iterator<ItemStackMatchable<Integer>> iterator() {
return new DelegateIterator<Map.Entry<Integer, ItemStack>, ItemStackMatchable<Integer>>(map.entrySet().iterator()) {
@Override
public ItemStackMatchable<Integer> next() {
final Map.Entry<Integer, ItemStack> entry = delegate.next();
return new ItemStackMatchable<Integer>() {
@Nonnull
@Override
public ItemStack getStack() {
return entry.getValue();
}
@Nonnull
@Override
public Integer getResult() {
return entry.getKey();
}
};
}
};
}
}
}