SpriteContents .java

net.minecraft.client.renderer.texture.SpriteContents (class, 410 lines): members: getAdditionalMetadata, additionalMetadata, increaseMipLevel, byMipLevel.

net.minecraft.client.renderer.textureclass410 linesclient15.0 KB

Implements

API Surface (20)

void increaseMipLevel(final int mipLevel)
boolean isAnimated()
Transparency transparency()
int width()
int height()
Identifier name()
IntList getUniqueFrames()
<T> Optional<T> getAdditionalMetadata(final MetadataSectionType<T> type)
void close()
String toString()
boolean isTransparent(final int frame, final int x, final int y)
Transparency computeTransparency(final float u0, final float v0, final float u1, final float v1)
void uploadFirstFrame(final GpuTexture destination, final int level)
SpriteContents.AnimationState createAnimationState(final GpuBufferSlice uboSlice, final int spriteUboSize)
IntList getUniqueFrames()
void tick()
GpuBufferSlice getDrawUbo(final int level)
boolean needsToDraw()
void drawToAtlas(final RenderPass renderPass, final GpuBufferSlice ubo)
void close()

Fields & Constants (16)

LOGGER
UBO_SIZE
name
width
height
originalImage
byMipLevel
animatedTexture
additionalMetadata
mipmapStrategy
alphaCutoffBias
transparency
frameSize
image
animationInfo
fullHeight

String literals (17)

"Generating mipmaps for frame"
"Frame being iterated"
"Sprite name"
"Sprite size"
"Sprite frames"
" frames"
"Mipmap levels"
"Original image size"
"SpriteContents{name="
", frameCount="
", height="
", width="
" animation frame "
"CurrentSprite"
"NextSprite"
"Sprite"
"SpriteAnimationInfo"

Full Source

SpriteContents.java410 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.client.renderer.texture;
2
3
import com.mojang.blaze3d.buffers.Std140SizeCalculator;
4
import com.mojang.blaze3d.platform.NativeImage;
5
import com.mojang.blaze3d.platform.Transparency;
6
import com.mojang.blaze3d.systems.RenderSystem;
7
import com.mojang.logging.LogUtils;
8
import com.mojang.renderpearl.api.GpuFormat;
9
import com.mojang.renderpearl.api.buffers.GpuBufferSlice;
10
import com.mojang.renderpearl.api.commands.CommandEncoder;
11
import com.mojang.renderpearl.api.commands.RenderPass;
12
import com.mojang.renderpearl.api.device.GpuDevice;
13
import com.mojang.renderpearl.api.textures.FilterMode;
14
import com.mojang.renderpearl.api.textures.GpuSampler;
15
import com.mojang.renderpearl.api.textures.GpuTexture;
16
import com.mojang.renderpearl.api.textures.GpuTextureView;
17
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
18
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
19
import it.unimi.dsi.fastutil.ints.IntArrayList;
20
import it.unimi.dsi.fastutil.ints.IntList;
21
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
22
import it.unimi.dsi.fastutil.ints.IntSet;
23
import java.util.ArrayList;
24
import java.util.Arrays;
25
import java.util.Iterator;
26
import java.util.List;
27
import java.util.Optional;
28
import java.util.stream.IntStream;
29
import net.fabricmc.api.EnvType;
30
import net.fabricmc.api.Environment;
31
import net.minecraft.CrashReport;
32
import net.minecraft.CrashReportCategory;
33
import net.minecraft.ReportedException;
34
import net.minecraft.client.renderer.RenderPipelines;
35
import net.minecraft.client.resources.metadata.animation.AnimationFrame;
36
import net.minecraft.client.resources.metadata.animation.AnimationMetadataSection;
37
import net.minecraft.client.resources.metadata.animation.FrameSize;
38
import net.minecraft.client.resources.metadata.texture.TextureMetadataSection;
39
import net.minecraft.resources.Identifier;
40
import net.minecraft.server.packs.metadata.MetadataSectionType;
41
import net.minecraft.server.packs.metadata.MetadataSectionType.WithValue;
42
import net.minecraft.util.ARGB;
43
import net.minecraft.util.Mth;
44
import org.jspecify.annotations.Nullable;
45
import org.slf4j.Logger;
46
47
@Environment(EnvType.CLIENT)
48
public class SpriteContents implements AutoCloseable, Stitcher.Entry {
49
	private static final Logger LOGGER = LogUtils.getLogger();
50
	public static final int UBO_SIZE = new Std140SizeCalculator().putMat4f().putMat4f().putFloat().putFloat().putInt().get();
51
	private final Identifier name;
52
	private final int width;
53
	private final int height;
54
	private final NativeImage originalImage;
55
	private NativeImage[] byMipLevel;
56
	private final SpriteContents.@Nullable AnimatedTexture animatedTexture;
57
	private final List<WithValue<?>> additionalMetadata;
58
	private final MipmapStrategy mipmapStrategy;
59
	private final float alphaCutoffBias;
60
	private final Transparency transparency;
61
62
	public SpriteContents(final Identifier name, final FrameSize frameSize, final NativeImage image) {
63
		this(name, frameSize, image, Optional.empty(), List.of(), Optional.empty());
64
	}
65
66
	public SpriteContents(
67
		final Identifier name,
68
		final FrameSize frameSize,
69
		final NativeImage image,
70
		final Optional<AnimationMetadataSection> animationInfo,
71
		final List<WithValue<?>> additionalMetadata,
72
		final Optional<TextureMetadataSection> textureInfo
73
	) {
74
		this.name = name;
75
		this.width = frameSize.width();
76
		this.height = frameSize.height();
77
		this.additionalMetadata = additionalMetadata;
78
		this.animatedTexture = animationInfo.<SpriteContents.AnimatedTexture>map(
79
				animation -> this.createAnimatedTexture(frameSize, image.getWidth(), image.getHeight(), animation)
80
			)
81
			.orElse(null);
82
		this.originalImage = image;
83
		this.byMipLevel = new NativeImage[]{this.originalImage};
84
		this.mipmapStrategy = textureInfo.map(TextureMetadataSection::mipmapStrategy).orElse(MipmapStrategy.AUTO);
85
		this.alphaCutoffBias = textureInfo.map(TextureMetadataSection::alphaCutoffBias).orElse(0.0F);
86
		this.transparency = image.computeTransparency();
87
	}
88
89
	public void increaseMipLevel(final int mipLevel) {
90
		try {
91
			this.byMipLevel = MipmapGenerator.generateMipLevels(this.name, this.byMipLevel, mipLevel, this.mipmapStrategy, this.alphaCutoffBias, this.transparency);
92
		} catch (Throwable t) {
93
			CrashReport report = CrashReport.forThrowable(t, "Generating mipmaps for frame");
94
			CrashReportCategory frameCategory = report.addCategory("Frame being iterated");
95
			frameCategory.setDetail("Sprite name", this.name);
96
			frameCategory.setDetail("Sprite size", () -> this.width + " x " + this.height);
97
			frameCategory.setDetail("Sprite frames", () -> this.getFrameCount() + " frames");
98
			frameCategory.setDetail("Mipmap levels", mipLevel);
99
			frameCategory.setDetail("Original image size", () -> this.originalImage.getWidth() + "x" + this.originalImage.getHeight());
100
			throw new ReportedException(report);
101
		}
102
	}
103
104
	private int getFrameCount() {
105
		return this.animatedTexture != null ? this.animatedTexture.frames.size() : 1;
106
	}
107
108
	public boolean isAnimated() {
109
		return this.getFrameCount() > 1;
110
	}
111
112
	public Transparency transparency() {
113
		return this.transparency;
114
	}
115
116
	private SpriteContents.@Nullable AnimatedTexture createAnimatedTexture(
117
		final FrameSize frameSize, final int fullWidth, final int fullHeight, final AnimationMetadataSection metadata
118
	) {
119
		int frameRowSize = fullWidth / frameSize.width();
120
		int frameColumnSize = fullHeight / frameSize.height();
121
		int totalFrameCount = frameRowSize * frameColumnSize;
122
		int defaultFrameTime = metadata.defaultFrameTime();
123
		List<SpriteContents.FrameInfo> frames;
124
		if (metadata.frames().isEmpty()) {
125
			frames = new ArrayList<>(totalFrameCount);
126
127
			for (int i = 0; i < totalFrameCount; i++) {
128
				frames.add(new SpriteContents.FrameInfo(i, defaultFrameTime));
129
			}
130
		} else {
131
			List<AnimationFrame> metadataFrames = metadata.frames().get();
132
			frames = new ArrayList<>(metadataFrames.size());
133
134
			for (AnimationFrame frame : metadataFrames) {
135
				frames.add(new SpriteContents.FrameInfo(frame.index(), frame.timeOr(defaultFrameTime)));
136
			}
137
138
			int index = 0;
139
			IntSet usedFrameIndices = new IntOpenHashSet();
140
141
			for (Iterator<SpriteContents.FrameInfo> iterator = frames.iterator(); iterator.hasNext(); index++) {
142
				SpriteContents.FrameInfo frame = iterator.next();
143
				boolean isValid = true;
144
				if (frame.time <= 0) {
145
					LOGGER.warn("Invalid frame duration on sprite {} frame {}: {}", this.name, index, frame.time);
146
					isValid = false;
147
				}
148
149
				if (frame.index < 0 || frame.index >= totalFrameCount) {
150
					LOGGER.warn("Invalid frame index on sprite {} frame {}: {}", this.name, index, frame.index);
151
					isValid = false;
152
				}
153
154
				if (isValid) {
155
					usedFrameIndices.add(frame.index);
156
				} else {
157
					iterator.remove();
158
				}
159
			}
160
161
			int[] unusedFrameIndices = IntStream.range(0, totalFrameCount).filter(i -> !usedFrameIndices.contains(i)).toArray();
162
			if (unusedFrameIndices.length > 0) {
163
				LOGGER.warn("Unused frames in sprite {}: {}", this.name, Arrays.toString(unusedFrameIndices));
164
			}
165
		}
166
167
		return frames.size() <= 1 ? null : new SpriteContents.AnimatedTexture(List.copyOf(frames), frameRowSize, metadata.interpolatedFrames());
168
	}
169
170
	@Override
171
	public int width() {
172
		return this.width;
173
	}
174
175
	@Override
176
	public int height() {
177
		return this.height;
178
	}
179
180
	@Override
181
	public Identifier name() {
182
		return this.name;
183
	}
184
185
	public IntList getUniqueFrames() {
186
		return this.animatedTexture != null ? this.animatedTexture.getUniqueFrames() : IntList.of(1);
187
	}
188
189
	public SpriteContents.@Nullable AnimationState createAnimationState(final GpuBufferSlice uboSlice, final int spriteUboSize) {
190
		return this.animatedTexture != null ? this.animatedTexture.createAnimationState(uboSlice, spriteUboSize) : null;
191
	}
192
193
	public <T> Optional<T> getAdditionalMetadata(final MetadataSectionType<T> type) {
194
		for (WithValue<?> metadata : this.additionalMetadata) {
195
			Optional<T> result = metadata.unwrapToType(type);
196
			if (result.isPresent()) {
197
				return result;
198
			}
199
		}
200
201
		return Optional.empty();
202
	}
203
204
	@Override
205
	public void close() {
206
		for (NativeImage image : this.byMipLevel) {
207
			image.close();
208
		}
209
	}
210
211
	@Override
212
	public String toString() {
213
		return "SpriteContents{name=" + this.name + ", frameCount=" + this.getFrameCount() + ", height=" + this.height + ", width=" + this.width + "}";
214
	}
215
216
	public boolean isTransparent(final int frame, final int x, final int y) {
217
		int actualX = x;
218
		int actualY = y;
219
		if (this.animatedTexture != null) {
220
			actualX += this.animatedTexture.getFrameX(frame) * this.width;
221
			actualY += this.animatedTexture.getFrameY(frame) * this.height;
222
		}
223
224
		return ARGB.alpha(this.originalImage.getPixel(actualX, actualY)) == 0;
225
	}
226
227
	public Transparency computeTransparency(final float u0, final float v0, final float u1, final float v1) {
228
		if (this.transparency.isOpaque()) {
229
			return this.transparency;
230
		}
231
232
		if (u0 == 0.0F && v0 == 0.0F && u1 == 1.0F && v1 == 1.0F) {
233
			return this.transparency;
234
		}
235
236
		int x0 = Mth.floor(u0 * this.width);
237
		int y0 = Mth.floor(v0 * this.height);
238
		int x1 = Mth.ceil(u1 * this.width);
239
		int y1 = Mth.ceil(v1 * this.height);
240
		if (this.animatedTexture == null) {
241
			return this.originalImage.computeTransparency(x0, y0, x1, y1);
242
		}
243
244
		IntList uniqueFrames = this.animatedTexture.uniqueFrames;
245
		Transparency transparency = Transparency.NONE;
246
247
		for (int i = 0; i < uniqueFrames.size(); i++) {
248
			int frame = uniqueFrames.getInt(i);
249
			int frameX = this.animatedTexture.getFrameX(frame) * this.width;
250
			int frameY = this.animatedTexture.getFrameY(frame) * this.height;
251
			transparency = transparency.or(this.originalImage.computeTransparency(frameX + x0, frameY + y0, frameX + x1, frameY + y1));
252
		}
253
254
		return transparency;
255
	}
256
257
	public void uploadFirstFrame(final GpuTexture destination, final int level) {
258
		RenderSystem.getDevice().createCommandEncoder().writeToTexture(destination, this.byMipLevel[level], level, 0, 0, 0);
259
	}
260
261
	@Environment(EnvType.CLIENT)
262
	private class AnimatedTexture {
263
		private final List<SpriteContents.FrameInfo> frames;
264
		private final IntList uniqueFrames;
265
		private final int frameRowSize;
266
		private final boolean interpolateFrames;
267
268
		private AnimatedTexture(final List<SpriteContents.FrameInfo> frames, final int frameRowSize, final boolean interpolateFrames) {
269
			this.frames = frames;
270
			this.frameRowSize = frameRowSize;
271
			this.interpolateFrames = interpolateFrames;
272
			this.uniqueFrames = IntArrayList.toList(frames.stream().mapToInt(SpriteContents.FrameInfo::index).distinct());
273
		}
274
275
		private int getFrameX(final int index) {
276
			return index % this.frameRowSize;
277
		}
278
279
		private int getFrameY(final int index) {
280
			return index / this.frameRowSize;
281
		}
282
283
		public SpriteContents.AnimationState createAnimationState(final GpuBufferSlice uboSlice, final int spriteUboSize) {
284
			GpuDevice device = RenderSystem.getDevice();
285
			Int2ObjectMap<GpuTextureView> frameTexturesByIndex = new Int2ObjectOpenHashMap<>();
286
			GpuBufferSlice[] spriteUbosByMip = new GpuBufferSlice[SpriteContents.this.byMipLevel.length];
287
			CommandEncoder encoder = device.createCommandEncoder();
288
			List<GpuBufferSlice> stagingBuffers = encoder.transientMemory()
289
				.multiUploadStaging(Arrays.stream(SpriteContents.this.byMipLevel).map(NativeImage::getPixelBytes).toList(), 1L, 16);
290
291
			for (int i = 0; i < this.uniqueFrames.size(); i++) {
292
				int frame = this.uniqueFrames.getInt(i);
293
				GpuTexture texture = device.createTexture(
294
					() -> SpriteContents.this.name + " animation frame " + frame,
295
					5,
296
					GpuFormat.RGBA8_UNORM,
297
					SpriteContents.this.width,
298
					SpriteContents.this.height,
299
					1,
300
					SpriteContents.this.byMipLevel.length
301
				);
302
				int offsetX = this.getFrameX(frame) * SpriteContents.this.width;
303
				int offsetY = this.getFrameY(frame) * SpriteContents.this.height;
304
305
				for (int level = 0; level < SpriteContents.this.byMipLevel.length; level++) {
306
					encoder.copyBufferToTexture(
307
						stagingBuffers.get(level),
308
						offsetX >> level,
309
						offsetY >> level,
310
						SpriteContents.this.byMipLevel[level].getWidth(),
311
						SpriteContents.this.byMipLevel[level].getHeight(),
312
						texture,
313
						0,
314
						0,
315
						SpriteContents.this.width >> level,
316
						SpriteContents.this.height >> level,
317
						level,
318
						0
319
					);
320
				}
321
322
				frameTexturesByIndex.put(frame, RenderSystem.getDevice().createTextureView(texture));
323
			}
324
325
			for (int level = 0; level < SpriteContents.this.byMipLevel.length; level++) {
326
				spriteUbosByMip[level] = uboSlice.slice(level * spriteUboSize, spriteUboSize);
327
			}
328
329
			return SpriteContents.this.new AnimationState(this, frameTexturesByIndex, spriteUbosByMip);
330
		}
331
332
		public IntList getUniqueFrames() {
333
			return this.uniqueFrames;
334
		}
335
	}
336
337
	@Environment(EnvType.CLIENT)
338
	public class AnimationState implements AutoCloseable {
339
		private int frame;
340
		private int subFrame;
341
		private final SpriteContents.AnimatedTexture animationInfo;
342
		private final Int2ObjectMap<GpuTextureView> frameTexturesByIndex;
343
		private final GpuBufferSlice[] spriteUbosByMip;
344
		private boolean isDirty = true;
345
346
		private AnimationState(
347
			final SpriteContents.AnimatedTexture animationInfo, final Int2ObjectMap<GpuTextureView> frameTexturesByIndex, final GpuBufferSlice[] spriteUbosByMip
348
		) {
349
			this.animationInfo = animationInfo;
350
			this.frameTexturesByIndex = frameTexturesByIndex;
351
			this.spriteUbosByMip = spriteUbosByMip;
352
		}
353
354
		public void tick() {
355
			this.subFrame++;
356
			this.isDirty = false;
357
			SpriteContents.FrameInfo currentFrame = this.animationInfo.frames.get(this.frame);
358
			if (this.subFrame >= currentFrame.time) {
359
				int oldFrame = currentFrame.index;
360
				this.frame = (this.frame + 1) % this.animationInfo.frames.size();
361
				this.subFrame = 0;
362
				int newFrame = this.animationInfo.frames.get(this.frame).index;
363
				if (oldFrame != newFrame) {
364
					this.isDirty = true;
365
				}
366
			}
367
		}
368
369
		public GpuBufferSlice getDrawUbo(final int level) {
370
			return this.spriteUbosByMip[level];
371
		}
372
373
		public boolean needsToDraw() {
374
			return this.animationInfo.interpolateFrames || this.isDirty;
375
		}
376
377
		public void drawToAtlas(final RenderPass renderPass, final GpuBufferSlice ubo) {
378
			GpuSampler sampler = RenderSystem.getSamplerCache().getClampToEdge(FilterMode.NEAREST, true);
379
			List<SpriteContents.FrameInfo> frames = this.animationInfo.frames;
380
			int oldFrame = frames.get(this.frame).index;
381
			float frameProgress = (float)this.subFrame / this.animationInfo.frames.get(this.frame).time;
382
			int frameProgressAsInt = (int)(frameProgress * 1000.0F);
383
			if (this.animationInfo.interpolateFrames) {
384
				int newFrame = frames.get((this.frame + 1) % frames.size()).index;
385
				renderPass.setPipeline(RenderSystem.getCompiledPipeline(RenderPipelines.ANIMATE_SPRITE_INTERPOLATE));
386
				renderPass.setUniform("CurrentSprite", this.frameTexturesByIndex.get(oldFrame), sampler);
387
				renderPass.setUniform("NextSprite", this.frameTexturesByIndex.get(newFrame), sampler);
388
			} else if (this.isDirty) {
389
				renderPass.setPipeline(RenderSystem.getCompiledPipeline(RenderPipelines.ANIMATE_SPRITE_BLIT));
390
				renderPass.setUniform("Sprite", this.frameTexturesByIndex.get(oldFrame), sampler);
391
			}
392
393
			renderPass.setUniform("SpriteAnimationInfo", ubo);
394
			renderPass.draw(6, 1, frameProgressAsInt << 3, 0);
395
		}
396
397
		@Override
398
		public void close() {
399
			for (GpuTextureView view : this.frameTexturesByIndex.values()) {
400
				view.texture().close();
401
				view.close();
402
			}
403
		}
404
	}
405
406
	@Environment(EnvType.CLIENT)
407
	private record FrameInfo(int index, int time) {
408
	}
409
}
410

Decompiled Minecraft 26.3 source of SpriteContents (net/minecraft/client/renderer/texture/SpriteContents.java) with Mojang official mappings, stored verbatim on the site.