-
Notifications
You must be signed in to change notification settings - Fork 18
/
AnvilRecipe.java
384 lines (347 loc) · 11.4 KB
/
AnvilRecipe.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
package knightminer.inspirations.library.recipe.anvil;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.mojang.datafixers.util.Pair;
import knightminer.inspirations.Inspirations;
import knightminer.inspirations.library.InspirationsRegistry;
import knightminer.inspirations.library.recipe.BlockIngredient;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.IRecipeSerializer;
import net.minecraft.item.crafting.IRecipeType;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.network.PacketBuffer;
import net.minecraft.state.IProperty;
import net.minecraft.state.StateContainer;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.common.crafting.CompoundIngredient;
import net.minecraftforge.registries.ForgeRegistries;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class AnvilRecipe implements IRecipe<AnvilInventory> {
public static final String FROM_INPUT = "<input>";
private final ResourceLocation id;
private final NonNullList<Ingredient> ingredients;
private final String group;
// If null, keep the existing block.
@Nullable
private final Block result;
// Properties to assign to the result, unparsed.
// If value == "<input>", copy over.
private final List<Pair<String, String>> properties;
// When matching, holds the number of times each item was used.
@Nullable
private int[] used=null;
private AnvilRecipe(
ResourceLocation id,
String group,
NonNullList<Ingredient> ingredients,
@Nullable Block result,
List<Pair<String, String>> properties
) {
this.id = id;
this.group = group;
this.ingredients = ingredients;
this.result = result;
this.properties = properties;
}
/**
* Test if the given recipe matches the input.
* When successful, inv.used is modified to reflect the used items.
*/
@Override
public boolean matches(@Nonnull AnvilInventory inv, @Nonnull World worldIn) {
// Used is set to true if that item was used in this recipe. First reset it.
used = new int[inv.getItems().size()];
Arrays.fill(used, 0);
boolean result = ingredients.stream().allMatch(ing -> checkIngredient(inv, ing));
if (!result) {
// Clear this, since it's not useful.
used = null;
}
return result;
}
private boolean checkIngredient(AnvilInventory inv, Ingredient ing) {
assert this.used != null;
int[] used = this.used.clone();
if (ing instanceof BlockIngredient) {
// It's a block, just test the state.
return ((BlockIngredient) ing).testBlock(inv.getState());
} else if (ing instanceof CompoundIngredient) {
for(Ingredient subIng: ((CompoundIngredient) ing).getChildren()) {
if (checkIngredient(inv, subIng)) {
// Keep the state for this one.
return true;
}
// Restore the state, since the compound didn't match.
this.used = used.clone();
}
return false;
} else {
// It's an item. We want to see if any item matches,
// but not reuse items twice - since they're consumed.
boolean found = false;
for(int i = 0; i < this.used.length; i++) {
ItemStack item = inv.getItems().get(i);
if (this.used[i] < item.getCount() && ing.test(item)) {
this.used[i]++;
found = true;
break;
}
}
if (!found) {
// Restore the state, since the ingredient didn't match.
this.used = used.clone();
}
return found;
}
}
/**
* Equivalent to getCraftingResult, but for blocks.
* @param inv The inventory that was matched.
* @return The block which should replace the existing one.
*/
@Nonnull
public BlockState getBlockResult(@Nonnull AnvilInventory inv) {
BlockState state = result == null ? inv.getState() : result.getDefaultState();
StateContainer<Block, BlockState> cont = state.getBlock().getStateContainer();
StateContainer<Block, BlockState> inpContainer = inv.getState().getBlock().getStateContainer();
for(Pair<String, String> prop: properties) {
String key = prop.getFirst();
String value = prop.getSecond();
if (value.equals(FROM_INPUT)) {
IProperty<?> inpProp = inpContainer.getProperty(key);
if (inpProp == null) {
InspirationsRegistry.log.warn(
"No property \"{}\" to copy from block {} in Anvil recipe {}!",
key, inv.getState().getBlock().getRegistryName(), id
);
continue;
}
// Convert to a string, so differing types and identical but distinct IProperty objects
// still work.
value = getProperty(state, inpProp);
}
IProperty<?> targProp = cont.getProperty(key);
if(targProp == null) {
InspirationsRegistry.log.warn(
"Property \"{}\" is not valid for block {} in Anvil recipe {}!",
key, state.getBlock().getRegistryName(), id
);
continue;
}
state = setProperty(state, targProp, value);
}
return state;
}
/**
* Consume the items used by the recipe, killing empty items.
* @param items Item entities involved.
*/
public void consumeItemEnts(List<ItemEntity> items) {
if (used == null || items.size() != used.length) {
return;
}
for(int i = 0; i < items.size(); i++) {
if(used[i] > 0) {
ItemEntity item = items.get(i);
ItemStack newStack = item.getItem().copy();
newStack.shrink(used[i]);
if(newStack.isEmpty()) {
item.remove();
} else {
item.setItem(newStack);
}
}
}
}
/**
* Consume the items used by the recipe.
* @param items ItemStacks in the same order as passed to match().
*/
public void consumeItemStacks(List<ItemStack> items) {
if (used == null || items.size() != used.length) {
return;
}
for(int i = 0; i < items.size(); i++) {
items.get(i).shrink(used[i]);
}
}
/**
* Setting the property needs a generic arg, so the parsed value can have the same type as the property.
*/
private <T extends Comparable<T>> BlockState setProperty(BlockState state, IProperty<T>prop, String value) {
Optional<T> parsedValue = prop.parseValue(value);
if (parsedValue.isPresent()) {
return state.with(prop, parsedValue.get());
} else {
InspirationsRegistry.log.warn(
"Invalid value \"{}\" for block property {} of {} in anvil recipe {}!",
value, prop.getName(), state.getBlock().getRegistryName(), id);
return state;
}
}
/**
* Getting the property needs a generic arg, so the parsed value can have the same type as the property.
*/
private <T extends Comparable<T>> String getProperty(BlockState state, IProperty<T> prop) {
return state.get(prop).toString();
}
/**
* Not used, call getBlockResult.
* @param inv The inventory that was matched.
* @deprecated Use getBlockResult
*/
@Nonnull
@Override
public ItemStack getCraftingResult(@Nonnull AnvilInventory inv) {
return ItemStack.EMPTY;
}
@Override
public boolean canFit(int width, int height) {
return true;
}
@Nonnull
@Override
public ItemStack getRecipeOutput() {
return ItemStack.EMPTY;
}
@Nonnull
@Override
public NonNullList<ItemStack> getRemainingItems(@Nonnull AnvilInventory inv) {
return NonNullList.create();
}
@Nonnull
@Override
public NonNullList<Ingredient> getIngredients() {
return ingredients;
}
@Override
public boolean isDynamic() {
return false;
}
@Nonnull
@Override
public String getGroup() {
return group;
}
@Nonnull
@Override
public ItemStack getIcon() {
return new ItemStack(Items.ANVIL);
}
@Nonnull
@Override
public ResourceLocation getId() {
return id;
}
@Nonnull
@Override
public IRecipeSerializer<?> getSerializer() {
return SERIALIZER;
}
@Nonnull
@Override
public IRecipeType<?> getType() {
return InspirationsRegistry.ANVIL_RECIPE_TYPE;
}
public static final IRecipeSerializer<?> SERIALIZER = new AnvilRecipeSerializer()
.setRegistryName(new ResourceLocation(Inspirations.modID, "anvil_smashing"));
private static class AnvilRecipeSerializer
extends net.minecraftforge.registries.ForgeRegistryEntry<IRecipeSerializer<?>>
implements IRecipeSerializer<AnvilRecipe>
{
@Nonnull
@Override
public AnvilRecipe read(@Nonnull ResourceLocation recipeId, @Nonnull JsonObject json) {
String group = JSONUtils.getString(json, "group", "");
NonNullList<Ingredient> inputs = NonNullList.create();
JsonArray inputJSON = JSONUtils.getJsonArray(json, "ingredients");
for(int i = 0; i < inputJSON.size(); i++) {
Ingredient ingredient = Ingredient.deserialize(inputJSON.get(i));
if (!ingredient.hasNoMatchingItems()) {
inputs.add(ingredient);
}
}
// Generate the output blockstate.
JsonObject result = JSONUtils.getJsonObject(json, "result");
String blockName = JSONUtils.getString(result, "block", FROM_INPUT);
Block block;
if (blockName.equals(FROM_INPUT)) {
// We keep the block, maybe tranferring properties.
block = null;
} else {
block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(blockName));
if (block == null) {
throw new JsonParseException("Unknown block \"" + blockName + "\"");
}
}
JsonObject props = JSONUtils.getJsonObject(result, "properties", new JsonObject());
List<Pair<String, String>> propsMap = new ArrayList<>();
for(Map.Entry<String, JsonElement> entry: props.entrySet()) {
if (!entry.getValue().isJsonPrimitive()) {
throw new JsonParseException("Expected simple value for property \"" + entry.getKey() + "\", but got a " + entry.getValue().getClass().getSimpleName());
}
propsMap.add(Pair.of(entry.getKey(), entry.getValue().getAsString()));
}
return new AnvilRecipe(recipeId, group, inputs, block, propsMap);
}
@Nullable
@Override
public AnvilRecipe read(@Nonnull ResourceLocation recipeId, @Nonnull PacketBuffer buffer) {
String group = buffer.readString();
String resultName = buffer.readString();
Block result;
if(resultName.isEmpty()) {
result = null;
} else {
// Should never be missing, since we've already validated it.
result = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(resultName));
}
int ingredientCount = buffer.readVarInt();
int propsCount = buffer.readVarInt();
NonNullList<Ingredient> inputs = NonNullList.withSize(ingredientCount, Ingredient.EMPTY);
for(int i = 0; i < ingredientCount; i++) {
inputs.set(i, Ingredient.read(buffer));
}
List<Pair<String, String>> props = new ArrayList<>(propsCount);
for(int i = 0; i < propsCount; i++) {
props.add(Pair.of(buffer.readString(), buffer.readString()));
}
return new AnvilRecipe(recipeId, group, inputs, result, props);
}
@Override
public void write(PacketBuffer buffer, AnvilRecipe recipe) {
buffer.writeString(recipe.group);
if (recipe.result == null) { // Copy result
buffer.writeString("");
} else {
buffer.writeString(recipe.result.getRegistryName().toString());
}
buffer.writeVarInt(recipe.ingredients.size());
buffer.writeVarInt(recipe.properties.size());
for(Ingredient ingredient: recipe.ingredients) {
ingredient.write(buffer);
}
for(Pair<String, String> prop: recipe.properties) {
buffer.writeString(prop.getFirst());
buffer.writeString(prop.getSecond());
}
}
}
}