/
StackHelper.java
483 lines (413 loc) · 13.9 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
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.List;
import java.util.Map;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
import mezz.jei.Internal;
import mezz.jei.api.ISubtypeRegistry;
import mezz.jei.api.recipe.IStackHelper;
import mezz.jei.api.gui.IGuiIngredient;
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.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(@Nonnull 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.
*/
@Nonnull
public MatchingItemsResult getMatchingItems(@Nonnull List<ItemStack> availableItemStacks, @Nonnull Map<Integer, ? extends IGuiIngredient<ItemStack>> ingredientsMap) {
MatchingItemsResult matchingItemResult = new MatchingItemsResult();
int recipeSlotNumber = -1;
SortedSet<Integer> keys = new TreeSet<>(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;
}
ItemStack matching = containsStack(availableItemStacks, requiredStacks);
if (matching == null) {
matchingItemResult.missingItems.add(key);
} else {
ItemStack matchingSplit = matching.splitStack(1);
if (matching.stackSize == 0) {
availableItemStacks.remove(matching);
}
matchingItemResult.matchingItems.put(recipeSlotNumber, matchingSplit);
}
}
return matchingItemResult;
}
@Nullable
public Slot getSlotWithStack(@Nonnull Container container, @Nonnull Iterable<Integer> slotNumbers, @Nonnull ItemStack stack) {
for (Integer slotNumber : slotNumbers) {
Slot slot = container.getSlot(slotNumber);
if (slot != null) {
ItemStack slotStack = slot.getStack();
if (isEquivalent(stack, slotStack)) {
return slot;
}
}
}
return null;
}
/** Returns true if all stacks from "contains" are found in "stacks" and the opposite is true as well. */
public boolean containsSameStacks(@Nonnull Iterable<ItemStack> stacks, @Nonnull Iterable<ItemStack> contains) {
for (ItemStack stack : contains) {
if (containsStack(stacks, stack) == null) {
return false;
}
}
for (ItemStack stack : stacks) {
if (containsStack(contains, stack) == null) {
return false;
}
}
return true;
}
/* Returns an ItemStack from "stacks" if it isEquivalent to an ItemStack from "contains" */
@Nullable
public ItemStack containsStack(@Nullable Iterable<ItemStack> stacks, @Nullable Iterable<ItemStack> contains) {
if (stacks == null || contains == null) {
return null;
}
for (ItemStack containStack : contains) {
ItemStack matchingStack = containsStack(stacks, containStack);
if (matchingStack != null) {
return matchingStack;
}
}
return null;
}
/* Returns an ItemStack from "stacks" if it isEquivalent to "contains" */
@Nullable
public ItemStack containsStack(@Nullable Iterable<ItemStack> stacks, @Nullable ItemStack contains) {
if (stacks == null || contains == null) {
return null;
}
for (ItemStack stack : stacks) {
if (isEquivalent(contains, stack)) {
return stack;
}
}
return null;
}
/**
* Similar to ItemStack.areItemStacksEqual but ignores NBT on items without subtypes, and uses the INbtIgnoreList
*/
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 Objects.equals(keyLhs, keyRhs);
} else {
return true;
}
}
@Override
@Nonnull
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);
}
@Nonnull
public List<ItemStack> getSubtypes(@Nonnull final Item item, final int stackSize) {
List<ItemStack> itemStacks = new ArrayList<>();
for (CreativeTabs itemTab : item.getCreativeTabs()) {
List<ItemStack> subItems = new ArrayList<>();
try {
item.getSubItems(item, itemTab, subItems);
} catch (RuntimeException | 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
@Nonnull
public List<ItemStack> getAllSubtypes(@Nullable Iterable stacks) {
if (stacks == null) {
Log.error("Null stacks", new NullPointerException());
return Collections.emptyList();
}
List<ItemStack> allSubtypes = new ArrayList<>();
getAllSubtypes(allSubtypes, stacks);
return allSubtypes;
}
private void getAllSubtypes(@Nonnull List<ItemStack> subtypesList, @Nonnull 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);
}
}
}
@Override
@Nonnull
public List<ItemStack> toItemStackList(@Nullable Object stacks) {
if (stacks == null) {
return Collections.emptyList();
}
UniqueItemStackListBuilder itemStackListBuilder = new UniqueItemStackListBuilder();
toItemStackList(itemStackListBuilder, stacks);
return itemStackListBuilder.build();
}
private void toItemStackList(@Nonnull UniqueItemStackListBuilder itemStackListBuilder, @Nullable Object input) {
if (input instanceof ItemStack) {
ItemStack stack = (ItemStack) input;
itemStackListBuilder.add(stack);
} else if (input instanceof String) {
List<ItemStack> stacks = OreDictionary.getOres((String) input);
for (ItemStack stack : stacks) {
itemStackListBuilder.add(stack);
}
} else if (input instanceof Iterable) {
for (Object obj : (Iterable) input) {
toItemStackList(itemStackListBuilder, obj);
}
} else if (input != null) {
Log.error("Unknown object found: {}", input);
}
}
@Nonnull
public String getModId(@Nonnull ItemStack stack) {
Item item = stack.getItem();
if (item == null) {
throw new NullPointerException(nullItemInStack);
}
ResourceLocation itemName = Item.REGISTRY.getNameForObject(item);
if (itemName == null) {
String stackInfo = ErrorUtil.getItemStackInfo(stack);
throw new NullPointerException("Item.itemRegistry.getNameForObject returned null for: " + stackInfo);
}
return itemName.getResourceDomain();
}
@Nonnull
public String getUniqueIdentifierForStack(@Nonnull ItemStack stack) {
return getUniqueIdentifierForStack(stack, UidMode.NORMAL);
}
@Nonnull
public String getUniqueIdentifierForStack(@Nonnull ItemStack stack, @Nonnull 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());
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");
if (serializedNbt.hasKey("ForgeCaps")) {
if (nbtTagCompound == null) {
nbtTagCompound = new NBTTagCompound();
}
nbtTagCompound.setTag("ForgeCaps", serializedNbt.getCompoundTag("ForgeCaps"));
}
if (nbtTagCompound != null && !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
}
@Nonnull
public List<String> getUniqueIdentifiersWithWildcard(@Nonnull 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(@Nonnull Container container, @Nonnull Collection<Integer> slotIndexes, @Nonnull ItemStack stack, boolean doAdd) {
int added = 0;
// Add to existing stacks first
for (Integer slotIndex : slotIndexes) {
Slot slot = container.getSlot(slotIndex);
if (slot == null) {
continue;
}
ItemStack inventoryStack = slot.getStack();
if (inventoryStack == null || inventoryStack.getItem() == null) {
continue;
}
// Already occupied by different item, skip this slot.
if (!inventoryStack.isStackable() || !inventoryStack.isItemEqual(stack) || !ItemStack.areItemStackTagsEqual(inventoryStack, stack)) {
continue;
}
int remain = stack.stackSize - added;
int maxStackSize = Math.min(slot.getItemStackLimit(inventoryStack), inventoryStack.getMaxStackSize());
int space = maxStackSize - inventoryStack.stackSize;
if (space <= 0) {
continue;
}
// 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 (Integer slotIndex : slotIndexes) {
Slot slot = container.getSlot(slotIndex);
if (slot == null) {
continue;
}
ItemStack inventoryStack = slot.getStack();
if (inventoryStack != null) {
continue;
}
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, ItemStack> matchingItems = new HashMap<>();
@Nonnull
public final List<Integer> missingItems = new ArrayList<>();
}
}