PipelineBuilder .java

com.mojang.renderpearl.frontend.shaders.PipelineBuilder (class): members: InterfaceVariableInfo, shaderCreateInfos, backendDevice, stageName, compiler.

com.mojang.renderpearl.frontend.shadersclass477 linesclient19.5 KB

Implements

API Surface (2)

void close()
CompletableFuture<CompiledRenderPipeline.Pending> compilePipeline(final RenderPipeline pipeline, final ShaderSource shaderSource, final Executor executor)

Fields & Constants (7)

LOGGER
backendDevice
compiler
pipeline
shaderSource
shaderCreateInfos
stageName

String literals (17)

"main"
"Unexpected value: "
"vertex"
"fragment"
"Unable to find shader defined uniform ("
"Uniform type for "
" does not match across all stages"
"Uniform dimensions for "
"1D textures not supported ("
"3D textures not supported ("
"Unexpected SpvDim ("
") for uniform ("
"Unexpected dimensions for uniform ("
"), does not match RenderPipeline definition"
"Frontend Compile and reflection"
"Backend Compile"
"Complete Compile"

Full Source

PipelineBuilder.java477 lines · Minecraft 26.3 · verbatim
1
package com.mojang.renderpearl.frontend.shaders;
2
3
import com.mojang.jtracy.TracyClient;
4
import com.mojang.jtracy.Zone;
5
import com.mojang.logging.LogUtils;
6
import com.mojang.renderpearl.api.GpuFormat;
7
import com.mojang.renderpearl.api.device.DeviceInfo;
8
import com.mojang.renderpearl.api.pipeline.BindGroupLayout;
9
import com.mojang.renderpearl.api.pipeline.CompiledRenderPipeline;
10
import com.mojang.renderpearl.api.pipeline.PolygonMode;
11
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
12
import com.mojang.renderpearl.api.pipeline.ShaderSource;
13
import com.mojang.renderpearl.api.pipeline.ShaderType;
14
import com.mojang.renderpearl.api.pipeline.UniformType;
15
import com.mojang.renderpearl.api.vertex.VertexFormat;
16
import com.mojang.renderpearl.api.vertex.VertexFormatElement;
17
import com.mojang.renderpearl.backend.api.BackendRenderPipeline;
18
import com.mojang.renderpearl.backend.api.GpuDeviceBackend;
19
import com.mojang.renderpearl.backend.api.SpvModule;
20
import com.mojang.renderpearl.backend.api.BackendRenderPipeline.CreateInfo.AttribBinding;
21
import com.mojang.renderpearl.backend.api.BackendRenderPipeline.CreateInfo.Shader;
22
import com.mojang.renderpearl.backend.api.BackendRenderPipeline.CreateInfo.VertexBuffer;
23
import com.mojang.renderpearl.backend.api.SpvModule.Reflection.Descriptor;
24
import com.mojang.renderpearl.backend.api.SpvModule.Reflection.InterfaceVariable;
25
import com.mojang.renderpearl.backend.api.SpvModule.Reflection.PushConstant;
26
import com.mojang.renderpearl.backend.api.SpvModule.Reflection.Type;
27
import com.mojang.renderpearl.frontend.FrontendRenderPipeline;
28
import com.mojang.renderpearl.util.ShaderCompileException;
29
import com.mojang.renderpearl.util.UncheckedAutoCloseable;
30
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
31
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
32
import it.unimi.dsi.fastutil.ints.Int2ObjectMaps;
33
import it.unimi.dsi.fastutil.ints.IntArrayList;
34
import it.unimi.dsi.fastutil.ints.IntList;
35
import it.unimi.dsi.fastutil.objects.Object2IntMaps;
36
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
37
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
38
import it.unimi.dsi.fastutil.objects.ReferenceArrayList;
39
import it.unimi.dsi.fastutil.objects.ReferenceList;
40
import it.unimi.dsi.fastutil.objects.ReferenceLists;
41
import java.util.EnumMap;
42
import java.util.List;
43
import java.util.Locale;
44
import java.util.Map;
45
import java.util.Map.Entry;
46
import java.util.concurrent.CompletableFuture;
47
import java.util.concurrent.Executor;
48
import java.util.function.Function;
49
import java.util.stream.Collectors;
50
import net.fabricmc.api.EnvType;
51
import net.fabricmc.api.Environment;
52
import net.minecraft.resources.Identifier;
53
import org.jspecify.annotations.Nullable;
54
import org.slf4j.Logger;
55
56
@Environment(EnvType.CLIENT)
57
public class PipelineBuilder implements UncheckedAutoCloseable {
58
	private static final Logger LOGGER = LogUtils.getLogger();
59
	private final GpuDeviceBackend backendDevice;
60
	private final GlslCompiler compiler;
61
62
	public PipelineBuilder(final GpuDeviceBackend backendDevice) {
63
		this.backendDevice = backendDevice;
64
		DeviceInfo deviceInfo = backendDevice.getDeviceInfo();
65
		this.compiler = new GlslCompiler(deviceInfo.isZZeroToOne(), deviceInfo.features().shaderDrawParameters());
66
	}
67
68
	@Override
69
	public void close() {
70
		this.compiler.close();
71
	}
72
73
	private BackendRenderPipeline.CreateInfo generateBackendCreateInfo(
74
		final RenderPipeline pipeline,
75
		final ShaderSource shaderSource,
76
		final ReferenceArrayList<Shader> shaderCreateInfos,
77
		final Object2IntOpenHashMap<String> uniformBindings
78
	) {
79
		try {
80
			EnumMap<ShaderType, SpvModule> shaderSources = new EnumMap<>(ShaderType.class);
81
82
			for (Entry<ShaderType, Identifier> shader : pipeline.getShaders().entrySet()) {
83
				String source = loadShaderSource(shader.getValue(), shader.getKey(), shaderSource);
84
				if (source == null) {
85
					LOGGER.error("Couldn't find source for {} shader ({})", shader.getKey(), shader.getValue());
86
					return null;
87
				}
88
89
				SpvModule spvModule = this.compiler.compileToSpv(shader.getValue().toString(), source, shader.getKey(), pipeline.getShaderDefines(), shaderSource);
90
				shaderSources.put(shader.getKey(), spvModule);
91
				shaderCreateInfos.add(new Shader(shader.getValue().toString(), "main", spvModule));
92
			}
93
94
			List<VertexBuffer> vertexBuffers = new ReferenceArrayList<>();
95
			List<AttribBinding> attribBindings = new ReferenceArrayList<>();
96
			if (shaderSources.containsKey(ShaderType.VERTEX)) {
97
				Int2ObjectMap<GpuFormat> attribFormats = new Int2ObjectArrayMap<>();
98
				SpvModule vertexShader = shaderSources.get(ShaderType.VERTEX);
99
				List<InterfaceVariable> vertexShaderInputs = vertexShader.reflect().inputs();
100
				String vertexStageName = pipeline.getShaders().get(ShaderType.VERTEX).toString();
101
				Map<String, InterfaceVariable> vertexShaderInputsByName = vertexShaderInputs.stream()
102
					.collect(Collectors.toUnmodifiableMap(InterfaceVariable::name, Function.identity()));
103
				List<VertexFormat> vertexBindings = pipeline.getVertexFormatBindings();
104
				String previousElementName = null;
105
				int previousElementLocation = 0;
106
107
				for (int i = 0; i < vertexBindings.size(); i++) {
108
					VertexFormat vertexBinding = vertexBindings.get(i);
109
					if (vertexBinding != null) {
110
						vertexBuffers.add(new VertexBuffer(i, vertexBinding.getVertexSize(), vertexBinding.getStepRate()));
111
112
						for (VertexFormatElement element : vertexBinding.getElements()) {
113
							InterfaceVariable input = vertexShaderInputsByName.get(element.name());
114
							if (input != null) {
115
								int attribLocation;
116
								if (element.name().equals(previousElementName)) {
117
									attribLocation = previousElementLocation + 1;
118
								} else {
119
									attribLocation = input.location();
120
								}
121
122
								attribBindings.add(new AttribBinding(i, attribLocation, element.offset(), element.format()));
123
								attribFormats.put(attribLocation, element.format());
124
								previousElementName = element.name();
125
								previousElementLocation = attribLocation;
126
							}
127
						}
128
					}
129
				}
130
131
				for (InterfaceVariable vertexShaderInput : vertexShaderInputs) {
132
					if (vertexShaderInput.decoration(31) != 0) {
133
						throw new ShaderCompileException(
134
							String.format(Locale.ROOT, "vertex shader (%s) attrib (%s) has component decoration, this is not permitted", vertexStageName, vertexShaderInput.name())
135
						);
136
					}
137
138
					GpuFormat format = attribFormats.get(vertexShaderInput.location());
139
					if (format == null) {
140
						throw new ShaderCompileException(
141
							String.format(Locale.ROOT, "vertex shader (%s) attrib (%s) does not have a matching vertex buffer element", vertexStageName, vertexShaderInput.name())
142
						);
143
					}
144
					int expectedBaseType = switch (format.componentType()) {
145
						case UNORM_8, SNORM_8, UNORM_16, SNORM_16, FLOAT_16, FLOAT_32 -> 13;
146
						case UINT_8, UINT_16, UINT_32 -> 8;
147
						case SINT_8, SINT_16, SINT_32 -> 7;
148
						default -> throw new ShaderCompileException("Unexpected value: " + format.componentType());
149
					};
150
					if (expectedBaseType != vertexShaderInput.type().baseType()) {
151
						throw new ShaderCompileException(
152
							String.format(
153
								Locale.ROOT,
154
								"Unexpected base type for input attribute %s in vertex shader %s, expected %s got %s",
155
								vertexShaderInput.name(),
156
								vertexStageName,
157
								SpvUtil.baseTypeString(expectedBaseType),
158
								SpvUtil.baseTypeString(vertexShaderInput.type().baseType())
159
							)
160
						);
161
					}
162
163
					if (vertexShaderInput.type().vectorSize() > format.componentCount()) {
164
						throw new ShaderCompileException(
165
							String.format(
166
								Locale.ROOT,
167
								"Not enough components for input attribute %s in vertex shader %s, expected at least %s got %s",
168
								vertexShaderInput.name(),
169
								vertexStageName,
170
								vertexShaderInput.type().vectorSize(),
171
								format.componentCount()
172
							)
173
						);
174
					}
175
				}
176
			}
177
178
			String vertexStageName;
179
			Int2ObjectMap<PipelineBuilder.InterfaceVariableInfo> outputSlotMap;
180
			if (shaderSources.containsKey(ShaderType.VERTEX)) {
181
				vertexStageName = pipeline.getShaders().get(ShaderType.VERTEX).toString();
182
				outputSlotMap = generateSlotMap(shaderSources.get(ShaderType.VERTEX).reflect().outputs(), vertexStageName, ShaderType.VERTEX);
183
			} else {
184
				vertexStageName = "";
185
				outputSlotMap = Int2ObjectMaps.emptyMap();
186
			}
187
188
			String fragmentStageName = pipeline.getShaders().get(ShaderType.FRAGMENT).toString();
189
			Int2ObjectMap<PipelineBuilder.InterfaceVariableInfo> inputSlotMap = generateSlotMap(
190
				shaderSources.get(ShaderType.FRAGMENT).reflect().inputs(), vertexStageName, ShaderType.FRAGMENT
191
			);
192
193
			for (it.unimi.dsi.fastutil.ints.Int2ObjectMap.Entry<PipelineBuilder.InterfaceVariableInfo> entry : inputSlotMap.int2ObjectEntrySet()) {
194
				int location = entry.getIntKey();
195
				PipelineBuilder.InterfaceVariableInfo input = entry.getValue();
196
				assert input != null;
197
				PipelineBuilder.InterfaceVariableInfo output = outputSlotMap.get(location);
198
				if (output == null) {
199
					throw new ShaderCompileException(
200
						String.format(
201
							Locale.ROOT, "Vertex shader (%s) missing output at location %d consumed by Fragment shader (%s)", vertexStageName, location, fragmentStageName
202
						)
203
					);
204
				}
205
206
				if (!output.equals(input)) {
207
					if (output.baseType() != input.baseType()) {
208
						throw new ShaderCompileException(
209
							String.format(
210
								Locale.ROOT,
211
								"Vertex shader (%s) and Fragment shader (%s) have base type mismatch at location %d of %s and %s.",
212
								vertexStageName,
213
								fragmentStageName,
214
								location,
215
								SpvUtil.baseTypeString(output.baseType()),
216
								SpvUtil.baseTypeString(input.baseType())
217
							)
218
						);
219
					}
220
221
					if (output.vectorLength() != input.vectorLength()) {
222
						throw new ShaderCompileException(
223
							String.format(
224
								Locale.ROOT,
225
								"Vertex shader (%s) and Fragment shader (%s) have vector length mismatch at location %d of %d and %d.",
226
								vertexStageName,
227
								fragmentStageName,
228
								location,
229
								output.vectorLength(),
230
								input.vectorLength()
231
							)
232
						);
233
					}
234
235
					if (output.flatInterpolated() != input.flatInterpolated()) {
236
						throw new ShaderCompileException(
237
							String.format(
238
								Locale.ROOT,
239
								"Vertex shader (%s) and Fragment shader (%s) have mismatched interpolation at location %d, flat in %s",
240
								vertexStageName,
241
								fragmentStageName,
242
								location,
243
								output.flatInterpolated() ? "vertex" : "fragment"
244
							)
245
						);
246
					}
247
				}
248
			}
249
250
			List<BindGroupLayout.UniformDescription> pipelineUniforms = BindGroupLayout.flattenUniforms(pipeline.getBindGroupLayouts());
251
			Map<String, BindGroupLayout.UniformDescription> pipelineUniformsByName = new Object2ObjectOpenHashMap<>();
252
253
			for (BindGroupLayout.UniformDescription pipelineUniform : pipelineUniforms) {
254
				pipelineUniformsByName.put(pipelineUniform.name(), pipelineUniform);
255
			}
256
257
			IntList uniformResourceTypes = new IntArrayList();
258
			IntList uniformDimensions = new IntArrayList();
259
			ReferenceList<BindGroupLayout.UniformDescription> uniforms = new ReferenceArrayList<>();
260
261
			for (Shader shader : shaderCreateInfos) {
262
				SpvModule.Reflection reflectionInfo = shader.module().reflect();
263
264
				for (Descriptor descriptor : reflectionInfo.descriptors()) {
265
					String uniformName = descriptor.name();
266
					Type type = descriptor.type();
267
					BindGroupLayout.UniformDescription pipelineUniform = pipelineUniformsByName.get(uniformName);
268
					if (pipelineUniform == null) {
269
						throw new ShaderCompileException("Unable to find shader defined uniform (" + uniformName + ")");
270
					}
271
272
					int newBinding = uniformBindings.computeIfAbsent(descriptor.name(), var1 -> uniformBindings.size());
273
					if (newBinding >= uniformResourceTypes.size()) {
274
						uniformResourceTypes.add(descriptor.resourceType());
275
						uniformDimensions.add(type.dimensions());
276
						uniforms.add(new BindGroupLayout.UniformDescription(pipelineUniform.name(), pipelineUniform.type(), pipelineUniform.gpuFormat()));
277
					} else {
278
						if (descriptor.resourceType() != uniformResourceTypes.getInt(newBinding)) {
279
							throw new ShaderCompileException("Uniform type for " + descriptor.name() + " does not match across all stages");
280
						}
281
282
						if (type.dimensions() != uniformDimensions.getInt(newBinding)) {
283
							throw new ShaderCompileException("Uniform dimensions for " + descriptor.name() + " does not match across all stages");
284
						}
285
					}
286
287
					descriptor.binding(newBinding);
288
					descriptor.descriptorSetIndex(0);
289
				}
290
			}
291
292
			for (String uniformName : uniformBindings.keySet()) {
293
				BindGroupLayout.UniformDescription pipelineUniform = pipelineUniformsByName.get(uniformName);
294
				assert pipelineUniform != null;
295
				int uniformBinding = uniformBindings.getInt(uniformName);
296
				int definedResourceType = uniformResourceTypes.getInt(uniformBinding);
297
				int expectedResourceType = SpvUtil.resourceType(pipelineUniform.type());
298
				int definedDimensions = uniformDimensions.getInt(uniformBinding);
299
				if (expectedResourceType != definedResourceType) {
300
					throw new ShaderCompileException("Uniform type in shader does not match expected type from RenderPipeline for (" + uniformName + ")");
301
				}
302
303
				if (definedDimensions != Integer.MAX_VALUE) {
304
					UniformType expectedUniformType = switch (definedDimensions) {
305
						case 0 -> throw new ShaderCompileException("1D textures not supported (" + uniformName + ")");
306
						case 1 -> UniformType.COMBINED_IMAGE_SAMPLER;
307
						case 2 -> throw new ShaderCompileException("3D textures not supported (" + uniformName + ")");
308
						case 3 -> UniformType.COMBINED_IMAGE_SAMPLER;
309
						case 4 -> UniformType.COMBINED_IMAGE_SAMPLER;
310
						case 5 -> UniformType.TEXEL_BUFFER;
311
						default -> throw new ShaderCompileException("Unexpected SpvDim (" + definedDimensions + ") for uniform (" + uniformName + ")");
312
					};
313
					if (pipelineUniform.type() != expectedUniformType) {
314
						throw new ShaderCompileException("Unexpected dimensions for uniform (" + uniformName + "), does not match RenderPipeline definition");
315
					}
316
				}
317
			}
318
319
			for (Shader shader : shaderCreateInfos) {
320
				List<PushConstant> pushConstants = shader.module().reflect().pushConstants();
321
				if (!pushConstants.isEmpty()) {
322
					if (pushConstants.size() > 1) {
323
						throw new ShaderCompileException("Shader may define at most one push_constant block");
324
					}
325
326
					PushConstant pushConstant = pushConstants.getFirst();
327
					if (pushConstant.size() > pipeline.pushConstantSize()) {
328
						throw new ShaderCompileException("Shader push constant size exceeds pipeline declared size");
329
					}
330
				}
331
			}
332
333
			return new BackendRenderPipeline.CreateInfo(
334
				pipeline.getLocation().toString(),
335
				List.copyOf(shaderCreateInfos),
336
				List.copyOf(vertexBuffers),
337
				List.copyOf(attribBindings),
338
				List.copyOf(uniforms),
339
				pipeline.pushConstantSize(),
340
				pipeline.getDepthStencilState(),
341
				pipeline.getPolygonMode(),
342
				pipeline.isCull(),
343
				pipeline.getColorTargetStates(),
344
				pipeline.getPrimitiveTopology()
345
			);
346
		} catch (ShaderCompileException e) {
347
			LOGGER.error("Couldn't compile pipeline ({}): ", pipeline.getLocation(), e);
348
			shaderCreateInfos.forEach(shader -> shader.module().close());
349
			return null;
350
		}
351
	}
352
353
	public CompletableFuture<CompiledRenderPipeline.Pending> compilePipeline(
354
		final RenderPipeline pipeline, final ShaderSource shaderSource, final Executor executor
355
	) {
356
		if (pipeline.getPolygonMode() == PolygonMode.WIREFRAME && !this.backendDevice.getDeviceInfo().features().wireframeFillMode()) {
357
			LOGGER.error("Pipeline {} uses {} fill mode, not supported by device", pipeline.getLocation(), PolygonMode.WIREFRAME);
358
			return CompletableFuture.completedFuture(CompiledRenderPipeline.Pending.NULL);
359
		} else {
360
			return CompletableFuture.supplyAsync(
361
				() -> {
362
					ReferenceArrayList<Shader> shaderCreateInfos = new ReferenceArrayList<>();
363
					Object2IntOpenHashMap<String> uniformBindings = new Object2IntOpenHashMap<>();
364
365
					BackendRenderPipeline.CreateInfo createInfo;
366
					try (Zone tracyZone = TracyClient.beginZone("Frontend Compile and reflection", false)) {
367
						tracyZone.addText(pipeline.getLocation().toString());
368
						createInfo = this.generateBackendCreateInfo(pipeline, shaderSource, shaderCreateInfos, uniformBindings);
369
					}
370
371
					if (createInfo == null) {
372
						return CompiledRenderPipeline.Pending.NULL;
373
					}
374
375
					BackendRenderPipeline.Pending backendPendingPipeline;
376
					try (Zone tracyZone = TracyClient.beginZone("Backend Compile", false)) {
377
						tracyZone.addText(pipeline.getLocation().toString());
378
						backendPendingPipeline = this.backendDevice.compilePipeline(createInfo);
379
					}
380
381
					return () -> {
382
						BackendRenderPipeline backendPipeline;
383
						try (Zone tracyZonex = TracyClient.beginZone("Complete Compile", false)) {
384
							tracyZonex.addText(pipeline.getLocation().toString());
385
							backendPipeline = backendPendingPipeline.finishCompile();
386
						}
387
388
						executor.execute(() -> shaderCreateInfos.forEach(shader -> shader.module().close()));
389
						return backendPipeline == null
390
							? null
391
							: new FrontendRenderPipeline(
392
								pipeline.getLocation().toString(),
393
								backendPipeline,
394
								ReferenceLists.unmodifiable(new ReferenceArrayList<>(pipeline.getVertexFormatBindings())),
395
								Object2IntMaps.unmodifiable(uniformBindings),
396
								BindGroupLayout.flattenUniforms(pipeline.getBindGroupLayouts()),
397
								ReferenceLists.unmodifiable(new ReferenceArrayList<>(pipeline.getColorTargetStates())),
398
								pipeline.wantsDepthTexture(),
399
								pipeline.pushConstantSize()
400
							);
401
					};
402
				},
403
				executor
404
			);
405
		}
406
	}
407
408
	private static @Nullable String loadShaderSource(final Identifier id, final ShaderType type, final ShaderSource shaderSource) {
409
		String source = shaderSource.getShader(id, type);
410
		if (source == null) {
411
			LOGGER.error("Couldn't find source for {} shader ({})", type, id);
412
			return null;
413
		} else {
414
			return source;
415
		}
416
	}
417
418
	private static Int2ObjectMap<PipelineBuilder.InterfaceVariableInfo> generateSlotMap(
419
		final List<InterfaceVariable> interfaceVariables, final String stageName, final ShaderType shaderType
420
	) throws ShaderCompileException {
421
		Int2ObjectMap<PipelineBuilder.InterfaceVariableInfo> slotMap = new Int2ObjectArrayMap<>();
422
423
		for (InterfaceVariable interfaceVariable : interfaceVariables) {
424
			Type interfaceVariableType = interfaceVariable.type();
425
			int baseLocation = interfaceVariable.location();
426
			if (interfaceVariable.decoration(31) != 0) {
427
				throw new ShaderCompileException(
428
					String.format(
429
						Locale.ROOT, "%s shader (%s) interface (%s) has component decoration, this is not permitted", shaderType.getName(), stageName, interfaceVariable.name()
430
					)
431
				);
432
			}
433
434
			switch (interfaceVariableType.baseType()) {
435
				case 9:
436
				case 10:
437
				case 14:
438
				case 15:
439
					throw new ShaderCompileException(
440
						String.format(
441
							Locale.ROOT,
442
							"Unsupported interface variable type %s in %s shader (%s) location %d",
443
							SpvUtil.baseTypeString(interfaceVariableType.baseType()),
444
							shaderType.getName(),
445
							stageName,
446
							baseLocation
447
						)
448
					);
449
				case 11:
450
				case 12:
451
				case 13:
452
			}
453
454
			PipelineBuilder.InterfaceVariableInfo info = new PipelineBuilder.InterfaceVariableInfo(
455
				interfaceVariableType.baseType(), interfaceVariableType.vectorSize(), interfaceVariable.hasDecoration(14)
456
			);
457
			int totalArraySize = 1;
458
			int arrayDimensions = interfaceVariableType.arrayDimensions();
459
			if (arrayDimensions > 0) {
460
				for (int i = 0; i < arrayDimensions; i++) {
461
					totalArraySize *= interfaceVariableType.arrayLength(i);
462
				}
463
			}
464
465
			for (int i = 0; i < totalArraySize; i++) {
466
				slotMap.put(baseLocation + i, info);
467
			}
468
		}
469
470
		return slotMap;
471
	}
472
473
	@Environment(EnvType.CLIENT)
474
	private record InterfaceVariableInfo(int baseType, int vectorLength, boolean flatInterpolated) {
475
	}
476
}
477

Decompiled Minecraft 26.3 source of PipelineBuilder (com/mojang/renderpearl/frontend/shaders/PipelineBuilder.java) with Mojang official mappings, stored verbatim on the site.