ShaderManager .java

net.minecraft.client.renderer.ShaderManager (class, 376 lines): members: postChainProjectionMatrixBuffer, compiledRequiredPipelines, CompilationException.

net.minecraft.client.rendererclass376 linesclient14.6 KB

Implements

API Surface (12)

CompletableFuture<Void> reload(final SharedState currentReload, final Executor taskExecutor, final PreparationBarrier preparationBarrier, final Executor reloadExecutor)
Map<Identifier, ShaderSource.CachedIncludeSource> listAllIncludes(final ResourceManager resourceManager)
String getName()
boolean isPostEffectValid(final Identifier id, final Set<Identifier> allowedTargets)
void close()
Stream<Identifier> getAvailablePostEffects()
String getShader(final Identifier id, final ShaderType type)
ShaderSource.CachedIncludeSource getInclude(final Identifier id)
void close()
void close()
Stream<Identifier> getKnownPostEffects()
String toString()

Fields & Constants (21)

LOGGER
MAX_LOG_LENGTH
SHADER_PATH
SHADER_INCLUDE_PATH
SHADER_INCLUDE_EXTENSION
SHADER_INCLUDE_CONVERTER
POST_CHAIN_ID_CONVERTER
textureManager
recoveryHandler
postChains
postChainProjection
postChainProjectionMatrixBuffer
preparationBarrier
taskExecutor
type
shaderSources
includeSources
configs
requiredPipelines
optionalPipelines
compiledRequiredPipelines

String literals (7)

"shaders"
"shaders/include/"
".glsl"
"shaders/include"
"post_effect"
"Failed to load required shader programs:\n"
"Shader Loader"

Full Source

ShaderManager.java376 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.client.renderer;
2
3
import com.google.common.collect.ImmutableMap;
4
import com.google.common.collect.Sets;
5
import com.google.common.collect.ImmutableMap.Builder;
6
import com.google.gson.JsonElement;
7
import com.google.gson.JsonParseException;
8
import com.google.gson.JsonSyntaxException;
9
import com.mojang.blaze3d.pipeline.PipelineCache;
10
import com.mojang.blaze3d.systems.RenderSystem;
11
import com.mojang.logging.LogUtils;
12
import com.mojang.renderpearl.api.device.GpuDevice;
13
import com.mojang.renderpearl.api.pipeline.CompiledRenderPipeline;
14
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
15
import com.mojang.renderpearl.api.pipeline.ShaderSource;
16
import com.mojang.renderpearl.api.pipeline.ShaderType;
17
import com.mojang.serialization.JsonOps;
18
import java.io.IOException;
19
import java.io.Reader;
20
import java.util.ArrayList;
21
import java.util.HashMap;
22
import java.util.List;
23
import java.util.Map;
24
import java.util.Optional;
25
import java.util.Set;
26
import java.util.Map.Entry;
27
import java.util.concurrent.CompletableFuture;
28
import java.util.concurrent.Executor;
29
import java.util.function.Consumer;
30
import java.util.stream.Collectors;
31
import java.util.stream.Stream;
32
import net.fabricmc.api.EnvType;
33
import net.fabricmc.api.Environment;
34
import net.minecraft.client.renderer.texture.TextureManager;
35
import net.minecraft.resources.FileToIdConverter;
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.StrictJsonParser;
43
import net.minecraft.util.Util;
44
import org.jspecify.annotations.Nullable;
45
import org.slf4j.Logger;
46
47
@Environment(EnvType.CLIENT)
48
public class ShaderManager implements PreparableReloadListener, AutoCloseable {
49
	private static final Logger LOGGER = LogUtils.getLogger();
50
	public static final int MAX_LOG_LENGTH = 32768;
51
	public static final String SHADER_PATH = "shaders";
52
	public static final String SHADER_INCLUDE_PATH = "shaders/include/";
53
	public static final String SHADER_INCLUDE_EXTENSION = ".glsl";
54
	public static final FileToIdConverter SHADER_INCLUDE_CONVERTER = new FileToIdConverter("shaders/include", ".glsl");
55
	private static final FileToIdConverter POST_CHAIN_ID_CONVERTER = FileToIdConverter.json("post_effect");
56
	private final TextureManager textureManager;
57
	private final Consumer<Exception> recoveryHandler;
58
	private ShaderManager.PostChainCache postChains = new ShaderManager.PostChainCache(ShaderManager.Configs.EMPTY);
59
	private final Projection postChainProjection = new Projection();
60
	private final ProjectionMatrixBuffer postChainProjectionMatrixBuffer = new ProjectionMatrixBuffer("post");
61
62
	public ShaderManager(final TextureManager textureManager, final Consumer<Exception> recoveryHandler) {
63
		this.textureManager = textureManager;
64
		this.recoveryHandler = recoveryHandler;
65
		this.postChainProjection.setupOrtho(0.1F, 1000.0F, 1.0F, 1.0F, false);
66
	}
67
68
	@Override
69
	public final CompletableFuture<Void> reload(
70
		final SharedState currentReload, final Executor taskExecutor, final PreparationBarrier preparationBarrier, final Executor reloadExecutor
71
	) {
72
		ResourceManager manager = currentReload.resourceManager();
73
		GpuDevice device = RenderSystem.getDevice();
74
		return CompletableFuture.<ShaderManager.Configs>supplyAsync(() -> loadConfigs(manager), taskExecutor)
75
			.thenComposeAsync(
76
				configs -> {
77
					List<RenderPipeline> requiredPipelines = RenderPipelines.requiredPipelines();
78
					List<RenderPipeline> optionalPipelines = RenderPipelines.optionalPipelines();
79
					return compilePipelines(device, configs, requiredPipelines, taskExecutor, reloadExecutor)
80
						.thenCombine(
81
							compilePipelines(device, configs, optionalPipelines, taskExecutor, reloadExecutor),
82
							(compiledRequiredPipelines, compiledOptionalPipelines) -> new ShaderManager.PendingResults(
83
								configs,
84
								requiredPipelines,
85
								optionalPipelines,
86
								(List<CompiledRenderPipeline>)compiledRequiredPipelines,
87
								(List<CompiledRenderPipeline>)compiledOptionalPipelines
88
							)
89
						);
90
				},
91
				reloadExecutor
92
			)
93
			.thenCompose(preparationBarrier::wait)
94
			.thenAcceptAsync(compilations -> this.apply(device, compilations), reloadExecutor);
95
	}
96
97
	private static CompletableFuture<List<@Nullable CompiledRenderPipeline>> compilePipelines(
98
		final GpuDevice device, final ShaderSource shaderSource, final List<RenderPipeline> pipelines, final Executor taskExecutor, final Executor reloadExecutor
99
	) {
100
		return Util.sequence(
101
			pipelines.stream()
102
				.map(pipeline -> device.compilePipeline(pipeline, shaderSource, taskExecutor).thenApplyAsync(CompiledRenderPipeline.Pending::finishCompile, reloadExecutor))
103
				.toList()
104
		);
105
	}
106
107
	private static ShaderManager.Configs loadConfigs(final ResourceManager manager) {
108
		Builder<ShaderManager.ShaderSourceKey, String> shaderSources = ImmutableMap.builder();
109
		Builder<Identifier, ShaderSource.CachedIncludeSource> includeSources = ImmutableMap.builder();
110
		Map<Identifier, Resource> files = manager.listResources("shaders", var0 -> true);
111
112
		for (Entry<Identifier, Resource> entry : files.entrySet()) {
113
			Identifier location = entry.getKey();
114
			ShaderType shaderType = ShaderType.byLocation(location);
115
			if (shaderType != null) {
116
				loadShader(location, entry.getValue(), shaderType, shaderSources);
117
			} else if (SHADER_INCLUDE_CONVERTER.matches(location)) {
118
				loadInclude(location, entry.getValue(), includeSources);
119
			}
120
		}
121
122
		Builder<Identifier, PostChainConfig> postChains = ImmutableMap.builder();
123
124
		for (Entry<Identifier, Resource> entry : POST_CHAIN_ID_CONVERTER.listMatchingResources(manager).entrySet()) {
125
			loadPostChain(entry.getKey(), entry.getValue(), postChains);
126
		}
127
128
		return new ShaderManager.Configs(shaderSources.build(), includeSources.build(), postChains.build());
129
	}
130
131
	private static void loadShader(
132
		final Identifier location, final Resource resource, final ShaderType type, final Builder<ShaderManager.ShaderSourceKey, String> output
133
	) {
134
		try {
135
			String contents = resource.readAllAsString();
136
			Identifier id = type.idConverter().fileToId(location);
137
			output.put(new ShaderManager.ShaderSourceKey(id, type), contents);
138
		} catch (IOException e) {
139
			LOGGER.error("Failed to load shader source at {}", location, e);
140
		}
141
	}
142
143
	private static void loadInclude(final Identifier location, final Resource resource, final Builder<Identifier, ShaderSource.CachedIncludeSource> output) {
144
		try {
145
			String contents = resource.readAllAsString();
146
			Identifier id = includeShaderLocationToId(location);
147
			output.put(id, ShaderSource.CachedIncludeSource.create(id, contents));
148
		} catch (IOException e) {
149
			LOGGER.error("Failed to load shader source at {}", location, e);
150
		}
151
	}
152
153
	private static void loadPostChain(final Identifier location, final Resource resource, final Builder<Identifier, PostChainConfig> output) {
154
		Identifier id = POST_CHAIN_ID_CONVERTER.fileToId(location);
155
156
		try (Reader reader = resource.openAsReader()) {
157
			JsonElement json = StrictJsonParser.parse(reader);
158
			output.put(id, PostChainConfig.CODEC.parse(JsonOps.INSTANCE, json).getOrThrow(JsonSyntaxException::new));
159
		} catch (IOException | JsonParseException e) {
160
			LOGGER.error("Failed to parse post chain at {}", location, e);
161
		}
162
	}
163
164
	public static Map<Identifier, ShaderSource.CachedIncludeSource> listAllIncludes(final ResourceManager resourceManager) {
165
		Map<Identifier, ShaderSource.CachedIncludeSource> includes = new HashMap<>();
166
		SHADER_INCLUDE_CONVERTER.listMatchingResources(resourceManager).forEach((location, resource) -> {
167
			try {
168
				String contents = resource.readAllAsString();
169
				Identifier includeId = includeShaderLocationToId(location);
170
				includes.put(includeId, ShaderSource.CachedIncludeSource.create(includeId, contents));
171
			} catch (Exception exception) {
172
				LOGGER.error("Couldn't read shader file {}", location, exception);
173
			}
174
		});
175
		return includes;
176
	}
177
178
	private static Identifier includeShaderLocationToId(final Identifier location) {
179
		return SHADER_INCLUDE_CONVERTER.fileToId(location).withSuffix(".glsl");
180
	}
181
182
	private void apply(final GpuDevice device, final ShaderManager.PendingResults compilations) {
183
		ShaderManager.PostChainCache newPostChains = new ShaderManager.PostChainCache(compilations.configs);
184
		List<Identifier> failedLoads = new ArrayList<>();
185
		PipelineCache pipelineCache = new PipelineCache(device, compilations.configs);
186
		pipelineCache.clear();
187
188
		for (int i = 0; i < compilations.requiredPipelines.size(); i++) {
189
			RenderPipeline pipeline = compilations.requiredPipelines.get(i);
190
			CompiledRenderPipeline compiled = compilations.compiledRequiredPipelines.get(i);
191
			if (compiled != null) {
192
				pipelineCache.insert(pipeline, compiled);
193
			} else {
194
				failedLoads.add(pipeline.getLocation());
195
			}
196
		}
197
198
		if (!failedLoads.isEmpty()) {
199
			for (CompiledRenderPipeline builtPipeline : compilations.compiledOptionalPipelines) {
200
				if (builtPipeline != null) {
201
					builtPipeline.close();
202
				}
203
			}
204
205
			pipelineCache.close();
206
			throw new RuntimeException("Failed to load required shader programs:\n" + failedLoads.stream().map(entry -> " - " + entry).collect(Collectors.joining("\n")));
207
		} else {
208
			for (int i = 0; i < compilations.optionalPipelines.size(); i++) {
209
				RenderPipeline pipeline = compilations.optionalPipelines.get(i);
210
				CompiledRenderPipeline compiled = compilations.compiledOptionalPipelines.get(i);
211
				if (compiled != null) {
212
					pipelineCache.insert(pipeline, compiled);
213
				} else {
214
					failedLoads.add(pipeline.getLocation());
215
				}
216
			}
217
218
			if (!failedLoads.isEmpty()) {
219
				LOGGER.warn("Failed to load optional shader programs:\n{}", failedLoads.stream().map(entry -> " - " + entry).collect(Collectors.joining("\n")));
220
			}
221
222
			this.postChains.close();
223
			this.postChains = newPostChains;
224
			PipelineCache oldPipelineCache = RenderSystem.setCurrentPipelineCache(pipelineCache);
225
			if (oldPipelineCache != null) {
226
				oldPipelineCache.close();
227
			}
228
		}
229
	}
230
231
	@Override
232
	public String getName() {
233
		return "Shader Loader";
234
	}
235
236
	private void tryTriggerRecovery(final Exception exception) {
237
		if (!this.postChains.triggeredRecovery) {
238
			this.recoveryHandler.accept(exception);
239
			this.postChains.triggeredRecovery = true;
240
		}
241
	}
242
243
	public boolean isPostEffectValid(final Identifier id, final Set<Identifier> allowedTargets) {
244
		PostChainConfig postChainConfig = this.postChains.configs.postChains.get(id);
245
		if (postChainConfig == null) {
246
			LOGGER.warn("Requested post effect does not exist: {}", id);
247
			return false;
248
		} else {
249
			Set<Identifier> invalidExternalTargets = Sets.difference(PostChain.getReferencedExternalTargets(postChainConfig), allowedTargets);
250
			if (!invalidExternalTargets.isEmpty()) {
251
				LOGGER.warn("Requested post chain {} can not be used as a post effect because it uses targets inaccessible to post effects: {}", id, invalidExternalTargets);
252
				return false;
253
			} else {
254
				return true;
255
			}
256
		}
257
	}
258
259
	public @Nullable PostChain getPostChain(final Identifier id, final Set<Identifier> allowedTargets) {
260
		try {
261
			return this.postChains.getOrLoadPostChain(id, allowedTargets);
262
		} catch (ShaderManager.CompilationException e) {
263
			LOGGER.error("Failed to load post chain: {}", id, e);
264
			this.postChains.postChains.put(id, Optional.empty());
265
			this.tryTriggerRecovery(e);
266
			return null;
267
		}
268
	}
269
270
	@Override
271
	public void close() {
272
		this.postChains.close();
273
		this.postChainProjectionMatrixBuffer.close();
274
	}
275
276
	public Stream<Identifier> getAvailablePostEffects() {
277
		return this.postChains.getKnownPostEffects();
278
	}
279
280
	@Environment(EnvType.CLIENT)
281
	public static class CompilationException extends Exception {
282
		public CompilationException(final String message) {
283
			super(message);
284
		}
285
	}
286
287
	@Environment(EnvType.CLIENT)
288
	public record Configs(
289
		Map<ShaderManager.ShaderSourceKey, String> shaderSources,
290
		Map<Identifier, ShaderSource.CachedIncludeSource> includeSources,
291
		Map<Identifier, PostChainConfig> postChains
292
	) implements ShaderSource {
293
		public static final ShaderManager.Configs EMPTY = new ShaderManager.Configs(Map.of(), Map.of(), Map.of());
294
295
		@Override
296
		public String getShader(final Identifier id, final ShaderType type) {
297
			return this.shaderSources.get(new ShaderManager.ShaderSourceKey(id, type));
298
		}
299
300
		@Override
301
		public ShaderSource.CachedIncludeSource getInclude(final Identifier id) {
302
			return this.includeSources.get(id);
303
		}
304
305
		@Override
306
		public void close() {
307
			this.includeSources.values().forEach(ShaderSource.CachedIncludeSource::close);
308
		}
309
	}
310
311
	@Environment(EnvType.CLIENT)
312
	private record PendingResults(
313
		ShaderManager.Configs configs,
314
		List<RenderPipeline> requiredPipelines,
315
		List<RenderPipeline> optionalPipelines,
316
		List<@Nullable CompiledRenderPipeline> compiledRequiredPipelines,
317
		List<@Nullable CompiledRenderPipeline> compiledOptionalPipelines
318
	) {
319
	}
320
321
	@Environment(EnvType.CLIENT)
322
	private class PostChainCache implements AutoCloseable {
323
		private final ShaderManager.Configs configs;
324
		private final Map<Identifier, Optional<PostChain>> postChains = new HashMap<>();
325
		private boolean triggeredRecovery;
326
327
		private PostChainCache(final ShaderManager.Configs configs) {
328
			this.configs = configs;
329
		}
330
331
		public @Nullable PostChain getOrLoadPostChain(final Identifier id, final Set<Identifier> allowedTargets) throws ShaderManager.CompilationException {
332
			Optional<PostChain> cached = this.postChains.get(id);
333
			if (cached != null) {
334
				return cached.orElse(null);
335
			}
336
337
			PostChain postChain = this.loadPostChain(id, allowedTargets);
338
			this.postChains.put(id, Optional.ofNullable(postChain));
339
			return postChain;
340
		}
341
342
		private @Nullable PostChain loadPostChain(final Identifier id, final Set<Identifier> allowedTargets) throws ShaderManager.CompilationException {
343
			PostChainConfig config = this.configs.postChains.get(id);
344
			if (config == null) {
345
				if (!id.equals(GameRenderer.END_OF_FRAME_POST_EFFECT)) {
346
					ShaderManager.LOGGER.warn("Attempted to load a non-existent post effect {}", id);
347
				}
348
349
				return null;
350
			} else {
351
				return PostChain.load(
352
					config, ShaderManager.this.textureManager, allowedTargets, id, ShaderManager.this.postChainProjection, ShaderManager.this.postChainProjectionMatrixBuffer
353
				);
354
			}
355
		}
356
357
		@Override
358
		public void close() {
359
			this.postChains.values().forEach(chain -> chain.ifPresent(PostChain::close));
360
			this.postChains.clear();
361
		}
362
363
		public Stream<Identifier> getKnownPostEffects() {
364
			return this.configs.postChains.keySet().stream();
365
		}
366
	}
367
368
	@Environment(EnvType.CLIENT)
369
	private record ShaderSourceKey(Identifier id, ShaderType type) {
370
		@Override
371
		public String toString() {
372
			return this.id + " (" + this.type + ")";
373
		}
374
	}
375
}
376

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