ShapedRecipePattern .java

net.minecraft.world.item.crafting.ShapedRecipePattern (class): members: symmetrical, ingredientCount, EMPTY_SLOT, MAX_SIZE, ingredients, Data, data, width.

net.minecraft.world.item.craftingclass245 linescommon7.5 KB

API Surface (7)

ShapedRecipePattern of(final Map<Character, Ingredient> key, final String... pattern)
ShapedRecipePattern of(final Map<Character, Ingredient> key, final List<String> pattern)
boolean matches(final CraftingInput input)
int width()
int height()
List<Optional<Ingredient>> ingredients()
record Data(Map<Character, Ingredient> key, List<String> pattern)

Fields & Constants (10)

MAX_SIZE
EMPTY_SLOT
MAP_CODEC
STREAM_CODEC
width
height
ingredients
data
ingredientCount
symmetrical

String literals (10)

"Cannot encode unpacked recipe"
"Pattern references symbol '"
"' but it's not defined in the key"
"Invalid pattern: too many rows, 3 is maximum"
"Invalid pattern: empty pattern not allowed"
"Invalid pattern: too many columns, 3 is maximum"
"Invalid pattern: each row must be the same width"
"Invalid key entry: '"
"Invalid key entry: ' ' is a reserved symbol."
"pattern"

Full Source

ShapedRecipePattern.java245 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.item.crafting;
2
3
import com.google.common.annotations.VisibleForTesting;
4
import com.mojang.serialization.Codec;
5
import com.mojang.serialization.DataResult;
6
import com.mojang.serialization.MapCodec;
7
import com.mojang.serialization.codecs.RecordCodecBuilder;
8
import it.unimi.dsi.fastutil.chars.CharArraySet;
9
import it.unimi.dsi.fastutil.chars.CharSet;
10
import java.util.ArrayList;
11
import java.util.List;
12
import java.util.Map;
13
import java.util.Optional;
14
import java.util.function.Function;
15
import net.minecraft.network.RegistryFriendlyByteBuf;
16
import net.minecraft.network.codec.ByteBufCodecs;
17
import net.minecraft.network.codec.StreamCodec;
18
import net.minecraft.util.ExtraCodecs;
19
import net.minecraft.util.Util;
20
import net.minecraft.world.item.ItemStack;
21
22
public final class ShapedRecipePattern {
23
	private static final int MAX_SIZE = 3;
24
	public static final char EMPTY_SLOT = ' ';
25
	public static final MapCodec<ShapedRecipePattern> MAP_CODEC = ShapedRecipePattern.Data.MAP_CODEC
26
		.flatXmap(
27
			ShapedRecipePattern::unpack, pattern -> pattern.data.map(DataResult::success).orElseGet(() -> DataResult.error(() -> "Cannot encode unpacked recipe"))
28
		);
29
	public static final StreamCodec<RegistryFriendlyByteBuf, ShapedRecipePattern> STREAM_CODEC = StreamCodec.composite(
30
		ByteBufCodecs.VAR_INT,
31
		e -> e.width,
32
		ByteBufCodecs.VAR_INT,
33
		e -> e.height,
34
		Ingredient.OPTIONAL_CONTENTS_STREAM_CODEC.apply(ByteBufCodecs.list()),
35
		e -> e.ingredients,
36
		ShapedRecipePattern::createFromNetwork
37
	);
38
	private final int width;
39
	private final int height;
40
	private final List<Optional<Ingredient>> ingredients;
41
	private final Optional<ShapedRecipePattern.Data> data;
42
	private final int ingredientCount;
43
	private final boolean symmetrical;
44
45
	public ShapedRecipePattern(final int width, final int height, final List<Optional<Ingredient>> ingredients, final Optional<ShapedRecipePattern.Data> data) {
46
		this.width = width;
47
		this.height = height;
48
		this.ingredients = ingredients;
49
		this.data = data;
50
		this.ingredientCount = (int)ingredients.stream().flatMap(Optional::stream).count();
51
		this.symmetrical = Util.isSymmetrical(width, height, ingredients);
52
	}
53
54
	private static ShapedRecipePattern createFromNetwork(final Integer width, final Integer height, final List<Optional<Ingredient>> ingredients) {
55
		return new ShapedRecipePattern(width, height, ingredients, Optional.empty());
56
	}
57
58
	public static ShapedRecipePattern of(final Map<Character, Ingredient> key, final String... pattern) {
59
		return of(key, List.of(pattern));
60
	}
61
62
	public static ShapedRecipePattern of(final Map<Character, Ingredient> key, final List<String> pattern) {
63
		ShapedRecipePattern.Data data = new ShapedRecipePattern.Data(key, pattern);
64
		return unpack(data).getOrThrow();
65
	}
66
67
	private static DataResult<ShapedRecipePattern> unpack(final ShapedRecipePattern.Data data) {
68
		String[] shrunkPattern = shrink(data.pattern);
69
		int width = shrunkPattern[0].length();
70
		int height = shrunkPattern.length;
71
		List<Optional<Ingredient>> ingredients = new ArrayList<>(width * height);
72
		CharSet unusedSymbols = new CharArraySet(data.key.keySet());
73
74
		for (String line : shrunkPattern) {
75
			for (int x = 0; x < line.length(); x++) {
76
				char symbol = line.charAt(x);
77
				Optional<Ingredient> ingredient;
78
				if (symbol == ' ') {
79
					ingredient = Optional.empty();
80
				} else {
81
					Ingredient ingredientForSymbol = data.key.get(symbol);
82
					if (ingredientForSymbol == null) {
83
						return DataResult.error(() -> "Pattern references symbol '" + symbol + "' but it's not defined in the key");
84
					}
85
86
					ingredient = Optional.of(ingredientForSymbol);
87
				}
88
89
				unusedSymbols.remove(symbol);
90
				ingredients.add(ingredient);
91
			}
92
		}
93
94
		return !unusedSymbols.isEmpty()
95
			? DataResult.error(() -> "Key defines symbols that aren't used in pattern: " + unusedSymbols)
96
			: DataResult.success(new ShapedRecipePattern(width, height, ingredients, Optional.of(data)));
97
	}
98
99
	@VisibleForTesting
100
	static String[] shrink(final List<String> pattern) {
101
		int left = Integer.MAX_VALUE;
102
		int right = 0;
103
		int top = 0;
104
		int bottom = 0;
105
106
		for (int i = 0; i < pattern.size(); i++) {
107
			String line = pattern.get(i);
108
			left = Math.min(left, firstNonEmpty(line));
109
			int lastNonSpace = lastNonEmpty(line);
110
			right = Math.max(right, lastNonSpace);
111
			if (lastNonSpace < 0) {
112
				if (top == i) {
113
					top++;
114
				}
115
116
				bottom++;
117
			} else {
118
				bottom = 0;
119
			}
120
		}
121
122
		if (pattern.size() == bottom) {
123
			return new String[0];
124
		}
125
126
		String[] result = new String[pattern.size() - bottom - top];
127
128
		for (int line = 0; line < result.length; line++) {
129
			result[line] = pattern.get(line + top).substring(left, right + 1);
130
		}
131
132
		return result;
133
	}
134
135
	private static int firstNonEmpty(final String line) {
136
		int index = 0;
137
138
		while (index < line.length() && line.charAt(index) == ' ') {
139
			index++;
140
		}
141
142
		return index;
143
	}
144
145
	private static int lastNonEmpty(final String line) {
146
		int index = line.length() - 1;
147
148
		while (index >= 0 && line.charAt(index) == ' ') {
149
			index--;
150
		}
151
152
		return index;
153
	}
154
155
	public boolean matches(final CraftingInput input) {
156
		if (input.ingredientCount() != this.ingredientCount) {
157
			return false;
158
		}
159
160
		if (input.width() == this.width && input.height() == this.height) {
161
			if (!this.symmetrical && this.matches(input, true)) {
162
				return true;
163
			}
164
165
			if (this.matches(input, false)) {
166
				return true;
167
			}
168
		}
169
170
		return false;
171
	}
172
173
	private boolean matches(final CraftingInput input, final boolean xFlip) {
174
		for (int y = 0; y < this.height; y++) {
175
			for (int x = 0; x < this.width; x++) {
176
				Optional<Ingredient> expected;
177
				if (xFlip) {
178
					expected = this.ingredients.get(this.width - x - 1 + y * this.width);
179
				} else {
180
					expected = this.ingredients.get(x + y * this.width);
181
				}
182
183
				ItemStack actual = input.getItem(x, y);
184
				if (!Ingredient.testOptionalIngredient(expected, actual)) {
185
					return false;
186
				}
187
			}
188
		}
189
190
		return true;
191
	}
192
193
	public int width() {
194
		return this.width;
195
	}
196
197
	public int height() {
198
		return this.height;
199
	}
200
201
	public List<Optional<Ingredient>> ingredients() {
202
		return this.ingredients;
203
	}
204
205
	public record Data(Map<Character, Ingredient> key, List<String> pattern) {
206
		private static final Codec<List<String>> PATTERN_CODEC = Codec.STRING.listOf().comapFlatMap(strings -> {
207
			if (strings.size() > 3) {
208
				return DataResult.error(() -> "Invalid pattern: too many rows, 3 is maximum");
209
			}
210
211
			if (strings.isEmpty()) {
212
				return DataResult.error(() -> "Invalid pattern: empty pattern not allowed");
213
			}
214
215
			int firstLength = strings.getFirst().length();
216
217
			for (String line : strings) {
218
				if (line.length() > 3) {
219
					return DataResult.error(() -> "Invalid pattern: too many columns, 3 is maximum");
220
				}
221
222
				if (firstLength != line.length()) {
223
					return DataResult.error(() -> "Invalid pattern: each row must be the same width");
224
				}
225
			}
226
227
			return DataResult.success(strings);
228
		}, Function.identity());
229
		private static final Codec<Character> SYMBOL_CODEC = Codec.STRING.comapFlatMap(symbol -> {
230
			if (symbol.length() != 1) {
231
				return DataResult.error(() -> "Invalid key entry: '" + symbol + "' is an invalid symbol (must be 1 character only).");
232
			} else {
233
				return " ".equals(symbol) ? DataResult.error(() -> "Invalid key entry: ' ' is a reserved symbol.") : DataResult.success(symbol.charAt(0));
234
			}
235
		}, String::valueOf);
236
		public static final MapCodec<ShapedRecipePattern.Data> MAP_CODEC = RecordCodecBuilder.mapCodec(
237
			i -> i.group(
238
					ExtraCodecs.strictUnboundedMap(SYMBOL_CODEC, Ingredient.CODEC).fieldOf("key").forGetter(d -> d.key),
239
					PATTERN_CODEC.fieldOf("pattern").forGetter(d -> d.pattern)
240
				)
241
				.apply(i, ShapedRecipePattern.Data::new)
242
		);
243
	}
244
}
245

Decompiled Minecraft 26.3 source of ShapedRecipePattern (net/minecraft/world/item/crafting/ShapedRecipePattern.java) with Mojang official mappings, stored verbatim on the site.