FallbackResourceManager .java

net.minecraft.server.packs.resources.FallbackResourceManager (class, 364 lines): members: LeakedResourceWarningInputStream, ResourceWithSource, EntryStack.

net.minecraft.server.packs.resourcesclass364 linesserver12.5 KB

Implements

API Surface (13)

void push(final PackResources pack)
void push(final PackResources pack, final PackResources.Filter filter)
void pushFilterOnly(final String name, final PackResources.Filter filter)
Set<String> getNamespaces()
Optional<Resource> getResource(final Identifier location)
List<Resource> getResourceStack(final Identifier location)
Map<Identifier, Resource> listResources(final String directory, final ResourceManager.Selector selector)
Map<Identifier, List<Resource>> listResourceStacks(final String directory, final ResourceManager.Selector selector)
Stream<PackResources> listPacks()
void close()
void finalize()
void filterAll(final Collection<Identifier> collection)
boolean isFiltered(final Identifier location)

Fields & Constants (11)

LOGGER
fallbacks
type
namespace
resource
entry
directory
selector
fileLocation
metadataLocation
fileSources

String literals (4)

".mcmeta"
"Stacktrace"
"Leaked resource: '"
"' loaded from pack: '"

Full Source

FallbackResourceManager.java364 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.server.packs.resources;
2
3
import com.google.common.collect.ImmutableSet;
4
import com.google.common.collect.Lists;
5
import com.mojang.logging.LogUtils;
6
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
7
import java.io.FilterInputStream;
8
import java.io.IOException;
9
import java.io.InputStream;
10
import java.io.PrintWriter;
11
import java.io.StringWriter;
12
import java.util.ArrayList;
13
import java.util.Collection;
14
import java.util.HashMap;
15
import java.util.List;
16
import java.util.Map;
17
import java.util.Objects;
18
import java.util.Optional;
19
import java.util.Set;
20
import java.util.SortedMap;
21
import java.util.TreeMap;
22
import java.util.function.Supplier;
23
import java.util.stream.Stream;
24
import net.minecraft.resources.Identifier;
25
import net.minecraft.server.packs.PackResources;
26
import net.minecraft.server.packs.PackType;
27
import org.jspecify.annotations.Nullable;
28
import org.slf4j.Logger;
29
30
public class FallbackResourceManager implements ResourceManager {
31
	private static final Logger LOGGER = LogUtils.getLogger();
32
	private final List<FallbackResourceManager.PackEntry> fallbacks = new ArrayList<>();
33
	private final PackType type;
34
	private final String namespace;
35
36
	public FallbackResourceManager(final PackType type, final String namespace) {
37
		this.type = type;
38
		this.namespace = namespace;
39
	}
40
41
	public void push(final PackResources pack) {
42
		this.pushInternal(pack.packId(), pack, null);
43
	}
44
45
	public void push(final PackResources pack, final PackResources.Filter filter) {
46
		this.pushInternal(pack.packId(), pack, filter);
47
	}
48
49
	public void pushFilterOnly(final String name, final PackResources.Filter filter) {
50
		this.pushInternal(name, null, filter);
51
	}
52
53
	private void pushInternal(final String name, final @Nullable PackResources pack, final PackResources.@Nullable Filter contentFilter) {
54
		this.fallbacks.add(new FallbackResourceManager.PackEntry(name, pack, contentFilter));
55
	}
56
57
	@Override
58
	public Set<String> getNamespaces() {
59
		return ImmutableSet.of(this.namespace);
60
	}
61
62
	@Override
63
	public Optional<Resource> getResource(final Identifier location) {
64
		for (int i = this.fallbacks.size() - 1; i >= 0; i--) {
65
			FallbackResourceManager.PackEntry entry = this.fallbacks.get(i);
66
			PackResources fallback = entry.resources;
67
			if (fallback != null) {
68
				IoSupplier<InputStream> resource = fallback.getResource(this.type, location);
69
				if (resource != null) {
70
					IoSupplier<ResourceMetadata> metadataGetter = this.createStackMetadataFinder(location, i);
71
					return Optional.of(createResource(fallback, location, resource, metadataGetter));
72
				}
73
			}
74
75
			if (entry.isFiltered(location)) {
76
				LOGGER.warn("Resource {} not found, but was filtered by pack {}", location, entry.name);
77
				return Optional.empty();
78
			}
79
		}
80
81
		return Optional.empty();
82
	}
83
84
	private static Resource createResource(
85
		final PackResources source, final Identifier location, final IoSupplier<InputStream> resource, final IoSupplier<ResourceMetadata> metadata
86
	) {
87
		return new Resource(source, wrapForDebug(location, source, resource), metadata);
88
	}
89
90
	private static IoSupplier<InputStream> wrapForDebug(final Identifier location, final PackResources source, final IoSupplier<InputStream> resource) {
91
		return LOGGER.isDebugEnabled() ? () -> new FallbackResourceManager.LeakedResourceWarningInputStream(resource.get(), location, source.packId()) : resource;
92
	}
93
94
	@Override
95
	public List<Resource> getResourceStack(final Identifier location) {
96
		Identifier metadataLocation = getMetadataLocation(location);
97
		List<Resource> result = new ArrayList<>();
98
		boolean filterMeta = false;
99
		String lastFilterName = null;
100
101
		for (int i = this.fallbacks.size() - 1; i >= 0; i--) {
102
			FallbackResourceManager.PackEntry entry = this.fallbacks.get(i);
103
			PackResources fileSource = entry.resources;
104
			if (fileSource != null) {
105
				IoSupplier<InputStream> resource = fileSource.getResource(this.type, location);
106
				if (resource != null) {
107
					IoSupplier<ResourceMetadata> metadataGetter;
108
					if (filterMeta) {
109
						metadataGetter = ResourceMetadata.EMPTY_SUPPLIER;
110
					} else {
111
						metadataGetter = () -> {
112
							IoSupplier<InputStream> metaResource = fileSource.getResource(this.type, metadataLocation);
113
							return metaResource != null ? parseMetadata(metaResource) : ResourceMetadata.EMPTY;
114
						};
115
					}
116
117
					result.add(new Resource(fileSource, resource, metadataGetter));
118
				}
119
			}
120
121
			if (entry.isFiltered(location)) {
122
				lastFilterName = entry.name;
123
				break;
124
			}
125
126
			if (entry.isFiltered(metadataLocation)) {
127
				filterMeta = true;
128
			}
129
		}
130
131
		if (result.isEmpty() && lastFilterName != null) {
132
			LOGGER.warn("Resource {} not found, but was filtered by pack {}", location, lastFilterName);
133
		}
134
135
		return Lists.reverse(result);
136
	}
137
138
	private static boolean isMetadata(final Identifier location) {
139
		return location.getPath().endsWith(".mcmeta");
140
	}
141
142
	private static Identifier getIdentifierFromMetadata(final Identifier identifier) {
143
		String newPath = identifier.getPath().substring(0, identifier.getPath().length() - ".mcmeta".length());
144
		return identifier.withPath(newPath);
145
	}
146
147
	private static Identifier getMetadataLocation(final Identifier identifier) {
148
		return identifier.withPath(identifier.getPath() + ".mcmeta");
149
	}
150
151
	@Override
152
	public Map<Identifier, Resource> listResources(final String directory, final ResourceManager.Selector selector) {
153
		record ResourceWithSourceAndIndex(PackResources packResources, IoSupplier<InputStream> resource, int packIndex) {
154
		}
155
156
		Map<Identifier, ResourceWithSourceAndIndex> topResourceForFileLocation = new HashMap<>();
157
		Map<Identifier, ResourceWithSourceAndIndex> topResourceForMetaLocation = new HashMap<>();
158
		int packCount = this.fallbacks.size();
159
160
		for (int i = 0; i < packCount; i++) {
161
			FallbackResourceManager.PackEntry entry = this.fallbacks.get(i);
162
			entry.filterAll(topResourceForFileLocation.keySet());
163
			entry.filterAll(topResourceForMetaLocation.keySet());
164
			PackResources packResources = entry.resources;
165
			if (packResources != null) {
166
				int packIndex = i;
167
				packResources.listResources(this.type, this.namespace, directory, (resource, streamSupplier) -> {
168
					if (isMetadata(resource)) {
169
						if (selector.isIncluded(getIdentifierFromMetadata(resource))) {
170
							topResourceForMetaLocation.put(resource, new ResourceWithSourceAndIndex(packResources, streamSupplier, packIndex));
171
						}
172
					} else if (selector.isIncluded(resource)) {
173
						topResourceForFileLocation.put(resource, new ResourceWithSourceAndIndex(packResources, streamSupplier, packIndex));
174
					}
175
				});
176
			}
177
		}
178
179
		Map<Identifier, Resource> result = new TreeMap<>();
180
		topResourceForFileLocation.forEach((location, resource) -> {
181
			Identifier metadataLocation = getMetadataLocation(location);
182
			ResourceWithSourceAndIndex metaResource = topResourceForMetaLocation.get(metadataLocation);
183
			IoSupplier<ResourceMetadata> metaGetter;
184
			if (metaResource != null && metaResource.packIndex >= resource.packIndex) {
185
				metaGetter = convertToMetadata(metaResource.resource);
186
			} else {
187
				metaGetter = ResourceMetadata.EMPTY_SUPPLIER;
188
			}
189
190
			result.put(location, createResource(resource.packResources, location, resource.resource, metaGetter));
191
		});
192
		return result;
193
	}
194
195
	private IoSupplier<ResourceMetadata> createStackMetadataFinder(final Identifier location, final int finalPackIndex) {
196
		return () -> {
197
			Identifier metadataLocation = getMetadataLocation(location);
198
199
			for (int i = this.fallbacks.size() - 1; i >= finalPackIndex; i--) {
200
				FallbackResourceManager.PackEntry entry = this.fallbacks.get(i);
201
				PackResources metadataPackCandidate = entry.resources;
202
				if (metadataPackCandidate != null) {
203
					IoSupplier<InputStream> resource = metadataPackCandidate.getResource(this.type, metadataLocation);
204
					if (resource != null) {
205
						return parseMetadata(resource);
206
					}
207
				}
208
209
				if (entry.isFiltered(metadataLocation)) {
210
					break;
211
				}
212
			}
213
214
			return ResourceMetadata.EMPTY;
215
		};
216
	}
217
218
	private static IoSupplier<ResourceMetadata> convertToMetadata(final IoSupplier<InputStream> input) {
219
		return () -> parseMetadata(input);
220
	}
221
222
	private static ResourceMetadata parseMetadata(final IoSupplier<InputStream> input) throws IOException {
223
		try (InputStream metadata = input.get()) {
224
			return ResourceMetadata.fromJsonStream(metadata);
225
		}
226
	}
227
228
	private static void applyPackFiltersToExistingResources(
229
		final FallbackResourceManager.PackEntry entry, final Map<Identifier, FallbackResourceManager.EntryStack> foundResources
230
	) {
231
		for (FallbackResourceManager.EntryStack e : foundResources.values()) {
232
			if (entry.isFiltered(e.fileLocation)) {
233
				e.fileSources.clear();
234
			} else if (entry.isFiltered(e.metadataLocation())) {
235
				e.metaSources.clear();
236
			}
237
		}
238
	}
239
240
	private void listPackResources(
241
		final FallbackResourceManager.PackEntry entry,
242
		final String directory,
243
		final ResourceManager.Selector selector,
244
		final Map<Identifier, FallbackResourceManager.EntryStack> foundResources
245
	) {
246
		PackResources pack = entry.resources;
247
		if (pack != null) {
248
			pack.listResources(
249
				this.type,
250
				this.namespace,
251
				directory,
252
				(id, resource) -> {
253
					if (isMetadata(id)) {
254
						Identifier actualId = getIdentifierFromMetadata(id);
255
						if (!selector.isIncluded(actualId)) {
256
							return;
257
						}
258
259
						foundResources.computeIfAbsent(actualId, FallbackResourceManager.EntryStack::new).metaSources.put(pack, resource);
260
					} else {
261
						if (!selector.isIncluded(id)) {
262
							return;
263
						}
264
265
						foundResources.computeIfAbsent(id, FallbackResourceManager.EntryStack::new)
266
							.fileSources
267
							.add(new FallbackResourceManager.ResourceWithSource(pack, resource));
268
					}
269
				}
270
			);
271
		}
272
	}
273
274
	@Override
275
	public Map<Identifier, List<Resource>> listResourceStacks(final String directory, final ResourceManager.Selector selector) {
276
		Map<Identifier, FallbackResourceManager.EntryStack> foundResources = new HashMap<>();
277
278
		for (FallbackResourceManager.PackEntry entry : this.fallbacks) {
279
			applyPackFiltersToExistingResources(entry, foundResources);
280
			this.listPackResources(entry, directory, selector, foundResources);
281
		}
282
283
		SortedMap<Identifier, List<Resource>> result = new TreeMap<>();
284
285
		for (FallbackResourceManager.EntryStack entry : foundResources.values()) {
286
			if (!entry.fileSources.isEmpty()) {
287
				List<Resource> resources = new ArrayList<>();
288
289
				for (FallbackResourceManager.ResourceWithSource stackEntry : entry.fileSources) {
290
					PackResources source = stackEntry.source;
291
					IoSupplier<InputStream> metaSource = entry.metaSources.get(source);
292
					IoSupplier<ResourceMetadata> metaGetter = metaSource != null ? convertToMetadata(metaSource) : ResourceMetadata.EMPTY_SUPPLIER;
293
					resources.add(createResource(source, entry.fileLocation, stackEntry.resource, metaGetter));
294
				}
295
296
				result.put(entry.fileLocation, resources);
297
			}
298
		}
299
300
		return result;
301
	}
302
303
	@Override
304
	public Stream<PackResources> listPacks() {
305
		return this.fallbacks.stream().map(p -> p.resources).filter(Objects::nonNull);
306
	}
307
308
	private record EntryStack(
309
		Identifier fileLocation,
310
		Identifier metadataLocation,
311
		List<FallbackResourceManager.ResourceWithSource> fileSources,
312
		Map<PackResources, IoSupplier<InputStream>> metaSources
313
	) {
314
		public EntryStack(final Identifier fileLocation) {
315
			this(fileLocation, FallbackResourceManager.getMetadataLocation(fileLocation), new ArrayList<>(), new Object2ObjectArrayMap<>());
316
		}
317
	}
318
319
	private static class LeakedResourceWarningInputStream extends FilterInputStream {
320
		private final Supplier<String> message;
321
		private boolean closed;
322
323
		public LeakedResourceWarningInputStream(final InputStream wrapped, final Identifier location, final String name) {
324
			super(wrapped);
325
			Exception exception = new Exception("Stacktrace");
326
			this.message = () -> {
327
				StringWriter data = new StringWriter();
328
				exception.printStackTrace(new PrintWriter(data));
329
				return "Leaked resource: '" + location + "' loaded from pack: '" + name + "'\n" + data;
330
			};
331
		}
332
333
		@Override
334
		public void close() throws IOException {
335
			super.close();
336
			this.closed = true;
337
		}
338
339
		@Override
340
		protected void finalize() throws Throwable {
341
			if (!this.closed) {
342
				FallbackResourceManager.LOGGER.warn("{}", this.message.get());
343
			}
344
345
			super.finalize();
346
		}
347
	}
348
349
	private record PackEntry(String name, @Nullable PackResources resources, PackResources.@Nullable Filter filter) {
350
		public void filterAll(final Collection<Identifier> collection) {
351
			if (this.filter != null) {
352
				collection.removeIf(this.filter::isFiltered);
353
			}
354
		}
355
356
		public boolean isFiltered(final Identifier location) {
357
			return this.filter != null && this.filter.isFiltered(location);
358
		}
359
	}
360
361
	private record ResourceWithSource(PackResources source, IoSupplier<InputStream> resource) {
362
	}
363
}
364

Decompiled Minecraft 26.3 source of FallbackResourceManager (net/minecraft/server/packs/resources/FallbackResourceManager.java) with Mojang official mappings, stored verbatim on the site.