PalettedTextureManager .java

net.minecraft.client.resources.palette.PalettedTextureManager (class): members: baseTextureCache, overflowTextures, OverflowTexture, paletteMappings, Slot.

net.minecraft.client.resources.paletteclass258 linesclient10.5 KB

Implements

API Surface (11)

Optional<PalettedTextureManager.BaseTexture> load(final Identifier id)
Identifier textureLocation()
float getU(final float offset)
float getV(final float offset)
PalettedTextureManager.Handle getOrPrepare(final Identifier baseTexture, final Identifier paletteId)
void close()
CompletableFuture<Void> reload(final SharedState currentReload, final Executor taskExecutor, final PreparationBarrier preparationBarrier, final Executor reloadExecutor)
void dumpContents(final Identifier selfId, final Path dir)
void close()
float getU(final float offset)
float getV(final float offset)

Fields & Constants (9)

LOGGER
textureManager
paletteMappings
baseTextureCache
atlasTextures
overflowTextures
handles
missingHandle
preparationBarrier

String literals (5)

"textures/"
".png"
"paletted/atlas_"
"paletted/overflow_"
"Paletted Atlas"

Full Source

PalettedTextureManager.java258 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.client.resources.palette;
2
3
import com.google.common.cache.CacheBuilder;
4
import com.google.common.cache.CacheLoader;
5
import com.google.common.cache.LoadingCache;
6
import com.mojang.blaze3d.platform.NativeImage;
7
import com.mojang.blaze3d.platform.TextureUtil;
8
import com.mojang.blaze3d.systems.RenderSystem;
9
import com.mojang.logging.LogUtils;
10
import com.mojang.renderpearl.api.GpuFormat;
11
import com.mojang.renderpearl.api.device.GpuDevice;
12
import com.mojang.renderpearl.api.textures.FilterMode;
13
import java.io.IOException;
14
import java.io.InputStream;
15
import java.nio.file.Path;
16
import java.time.Duration;
17
import java.util.ArrayList;
18
import java.util.HashMap;
19
import java.util.List;
20
import java.util.Map;
21
import java.util.Optional;
22
import java.util.concurrent.CompletableFuture;
23
import java.util.concurrent.Executor;
24
import java.util.function.BiFunction;
25
import net.fabricmc.api.EnvType;
26
import net.fabricmc.api.Environment;
27
import net.minecraft.client.renderer.texture.AbstractTexture;
28
import net.minecraft.client.renderer.texture.Dumpable;
29
import net.minecraft.client.renderer.texture.DynamicAtlasTree;
30
import net.minecraft.client.renderer.texture.DynamicAtlasTreeSlot;
31
import net.minecraft.client.renderer.texture.DynamicTexture;
32
import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite;
33
import net.minecraft.client.renderer.texture.TextureManager;
34
import net.minecraft.client.renderer.texture.UvMapping;
35
import net.minecraft.client.resources.metadata.texture.PaletteMetadataSection;
36
import net.minecraft.resources.Identifier;
37
import net.minecraft.server.packs.resources.PreparableReloadListener;
38
import net.minecraft.server.packs.resources.Resource;
39
import net.minecraft.server.packs.resources.ResourceManager;
40
import net.minecraft.server.packs.resources.PreparableReloadListener.PreparationBarrier;
41
import net.minecraft.server.packs.resources.PreparableReloadListener.SharedState;
42
import net.minecraft.util.ARGB;
43
import org.jspecify.annotations.Nullable;
44
import org.slf4j.Logger;
45
46
@Environment(EnvType.CLIENT)
47
public class PalettedTextureManager implements PreparableReloadListener, AutoCloseable {
48
	private static final Logger LOGGER = LogUtils.getLogger();
49
	private final TextureManager textureManager;
50
	private BiFunction<Identifier, Identifier, PaletteMapping> paletteMappings = (var0, var1) -> PaletteMapping.NONE;
51
	private final LoadingCache<Identifier, Optional<PalettedTextureManager.BaseTexture>> baseTextureCache;
52
	private final List<PalettedTextureManager.AtlasTexture> atlasTextures = new ArrayList<>();
53
	private final List<PalettedTextureManager.OverflowTexture> overflowTextures = new ArrayList<>();
54
	private final Map<PalettedTextureManager.SlotKey, PalettedTextureManager.Handle> handles = new HashMap<>();
55
	private final PalettedTextureManager.Handle missingHandle;
56
57
	public PalettedTextureManager(final ResourceManager resourceManager, final TextureManager textureManager) {
58
		this.textureManager = textureManager;
59
		this.baseTextureCache = CacheBuilder.newBuilder()
60
			.expireAfterAccess(Duration.ofMinutes(5L))
61
			.maximumSize(64L)
62
			.removalListener(notification -> ((Optional)notification.getValue()).ifPresent(PalettedTextureManager.BaseTexture::close))
63
			.build(new CacheLoader<Identifier, Optional<PalettedTextureManager.BaseTexture>>() {
64
				public Optional<PalettedTextureManager.BaseTexture> load(final Identifier id) {
65
					return Optional.ofNullable(PalettedTextureManager.loadBaseTexture(id, resourceManager));
66
				}
67
			});
68
		this.missingHandle = new PalettedTextureManager.Handle() {
69
			@Override
70
			public Identifier textureLocation() {
71
				return MissingTextureAtlasSprite.getLocation();
72
			}
73
74
			@Override
75
			public float getU(final float offset) {
76
				return offset;
77
			}
78
79
			@Override
80
			public float getV(final float offset) {
81
				return offset;
82
			}
83
		};
84
	}
85
86
	private static PalettedTextureManager.@Nullable BaseTexture loadBaseTexture(final Identifier id, final ResourceManager resourceManager) {
87
		Identifier location = id.withPath(path -> "textures/" + path + ".png");
88
89
		try {
90
			Resource resource = resourceManager.getResourceOrThrow(location);
91
92
			NativeImage image;
93
			try (InputStream input = resource.open()) {
94
				image = NativeImage.read(input);
95
			}
96
97
			return new PalettedTextureManager.BaseTexture(image, resource.metadata().getSection(PaletteMetadataSection.TYPE).orElse(null));
98
		} catch (IOException e) {
99
			LOGGER.error("Failed to load paletted base texture at {}", location, e);
100
			return null;
101
		}
102
	}
103
104
	public PalettedTextureManager.Handle getOrPrepare(final Identifier baseTexture, final Identifier paletteId) {
105
		PalettedTextureManager.SlotKey key = new PalettedTextureManager.SlotKey(baseTexture, paletteId);
106
		PalettedTextureManager.Handle existingHandle = this.handles.get(key);
107
		if (existingHandle != null) {
108
			return existingHandle;
109
		}
110
111
		PalettedTextureManager.Handle handle = this.prepareSlot(baseTexture, paletteId);
112
		this.handles.put(key, handle);
113
		return handle;
114
	}
115
116
	private PalettedTextureManager.Handle prepareSlot(final Identifier baseTextureId, final Identifier paletteId) {
117
		Optional<PalettedTextureManager.BaseTexture> maybeBaseTexture = this.baseTextureCache.getUnchecked(baseTextureId);
118
		if (maybeBaseTexture.isEmpty()) {
119
			return this.missingHandle;
120
		}
121
122
		PalettedTextureManager.BaseTexture baseTexture = maybeBaseTexture.get();
123
		PaletteMetadataSection paletteMetadata = baseTexture.paletteMetadata();
124
		PaletteMapping paletteMapping = paletteMetadata != null ? this.paletteMappings.apply(paletteMetadata.basePalette(), paletteId) : PaletteMapping.NONE;
125
126
		try (NativeImage newTexture = baseTexture.image().mappedCopy(paletteMapping)) {
127
			PalettedTextureManager.Slot slot = this.allocateSlot(newTexture.getWidth(), newTexture.getHeight());
128
			RenderSystem.getDevice().createCommandEncoder().writeToTexture(slot.texture.getTexture(), newTexture, 0, 0, slot.x, slot.y);
129
			return slot;
130
		}
131
	}
132
133
	private PalettedTextureManager.Slot allocateSlot(final int width, final int height) {
134
		if (width <= 512 && height <= 512) {
135
			for (PalettedTextureManager.AtlasTexture atlas : this.atlasTextures) {
136
				DynamicAtlasTreeSlot atlasSlot = atlas.tryAllocateSlot(width, height);
137
				if (atlasSlot != null) {
138
					return new PalettedTextureManager.Slot(atlas, atlas.location, atlasSlot.x(), atlasSlot.y(), atlasSlot.width(), atlasSlot.height());
139
				}
140
			}
141
142
			PalettedTextureManager.AtlasTexture atlas = new PalettedTextureManager.AtlasTexture(
143
				Identifier.withDefaultNamespace("paletted/atlas_" + this.atlasTextures.size())
144
			);
145
			this.textureManager.register(atlas.location, atlas);
146
			this.atlasTextures.add(atlas);
147
			DynamicAtlasTreeSlot atlasSlot = atlas.tryAllocateSlot(width, height);
148
			if (atlasSlot == null) {
149
				throw new IllegalStateException("Could not allocate slot in fresh atlas for sprite with size " + width + "x" + height);
150
			} else {
151
				return new PalettedTextureManager.Slot(atlas, atlas.location, atlasSlot.x(), atlasSlot.y(), atlasSlot.width(), atlasSlot.height());
152
			}
153
		} else {
154
			PalettedTextureManager.OverflowTexture texture = new PalettedTextureManager.OverflowTexture(
155
				Identifier.withDefaultNamespace("paletted/overflow_" + this.overflowTextures.size()), width, height
156
			);
157
			this.textureManager.register(texture.location, texture);
158
			this.overflowTextures.add(texture);
159
			return new PalettedTextureManager.Slot(texture, texture.location, 0, 0, width, height);
160
		}
161
	}
162
163
	@Override
164
	public void close() {
165
		for (PalettedTextureManager.AtlasTexture atlas : this.atlasTextures) {
166
			this.textureManager.release(atlas.location);
167
		}
168
169
		for (PalettedTextureManager.OverflowTexture texture : this.overflowTextures) {
170
			this.textureManager.release(texture.location);
171
		}
172
173
		this.atlasTextures.clear();
174
		this.overflowTextures.clear();
175
		this.handles.clear();
176
		this.paletteMappings = (var0, var1) -> PaletteMapping.NONE;
177
		this.baseTextureCache.invalidateAll();
178
	}
179
180
	@Override
181
	public CompletableFuture<Void> reload(
182
		final SharedState currentReload, final Executor taskExecutor, final PreparationBarrier preparationBarrier, final Executor reloadExecutor
183
	) {
184
		return Palette.listAndLoad(currentReload.resourceManager(), taskExecutor).thenCompose(preparationBarrier::wait).thenAcceptAsync(palettes -> {
185
			this.close();
186
			PaletteMappingCache paletteMappings = new PaletteMappingCache((Map<Identifier, Palette>)palettes);
187
			this.paletteMappings = paletteMappings::get;
188
		}, reloadExecutor);
189
	}
190
191
	@Environment(EnvType.CLIENT)
192
	private static class AtlasTexture extends AbstractTexture implements Dumpable {
193
		private static final int SIZE = 512;
194
		private final Identifier location;
195
		private final DynamicAtlasTree tree = new DynamicAtlasTree(0, 0, 512, 512);
196
197
		private AtlasTexture(final Identifier location) {
198
			GpuDevice device = RenderSystem.getDevice();
199
			this.texture = device.createTexture(() -> "Paletted Atlas", 7, GpuFormat.RGBA8_UNORM, 512, 512, 1, 1);
200
			this.textureView = device.createTextureView(this.texture);
201
			this.location = location;
202
			this.sampler = RenderSystem.getSamplerCache().getRepeat(FilterMode.NEAREST);
203
		}
204
205
		public @Nullable DynamicAtlasTreeSlot tryAllocateSlot(final int width, final int height) {
206
			return this.tree.insert(width, height, 0);
207
		}
208
209
		@Override
210
		public void dumpContents(final Identifier selfId, final Path dir) {
211
			if (this.texture != null) {
212
				String outputId = selfId.toDebugFileName();
213
				TextureUtil.writeAsPNG(dir, outputId, this.texture, 0, argb -> ARGB.alpha(argb) == 0 ? -16777216 : argb);
214
			}
215
		}
216
	}
217
218
	@Environment(EnvType.CLIENT)
219
	private record BaseTexture(NativeImage image, @Nullable PaletteMetadataSection paletteMetadata) implements AutoCloseable {
220
		@Override
221
		public void close() {
222
			this.image.close();
223
		}
224
	}
225
226
	@Environment(EnvType.CLIENT)
227
	public interface Handle extends UvMapping {
228
		Identifier textureLocation();
229
	}
230
231
	@Environment(EnvType.CLIENT)
232
	private static class OverflowTexture extends DynamicTexture {
233
		private final Identifier location;
234
235
		public OverflowTexture(final Identifier location, final int width, final int height) {
236
			super(location::toString, width, height, false);
237
			this.location = location;
238
		}
239
	}
240
241
	@Environment(EnvType.CLIENT)
242
	private record Slot(AbstractTexture texture, Identifier textureLocation, int x, int y, int width, int height) implements PalettedTextureManager.Handle {
243
		@Override
244
		public float getU(final float offset) {
245
			return (this.x + offset * this.width) / this.texture.getTexture().getWidth(0);
246
		}
247
248
		@Override
249
		public float getV(final float offset) {
250
			return (this.y + offset * this.height) / this.texture.getTexture().getHeight(0);
251
		}
252
	}
253
254
	@Environment(EnvType.CLIENT)
255
	private record SlotKey(Identifier baseTexture, Identifier paletteId) {
256
	}
257
}
258

Decompiled Minecraft 26.3 source of PalettedTextureManager (net/minecraft/client/resources/palette/PalettedTextureManager.java) with Mojang official mappings, stored verbatim on the site.