RenderSystem .java

com.mojang.blaze3d.systems.RenderSystem (class, 495 lines): members: getScissorStateForRenderTypeDraws, disableScissorForRenderTypeDraws, DEVICE, BACKEND.

com.mojang.blaze3d.systemsclass495 linesclient15.6 KB

API Surface (43)

SamplerCache getSamplerCache()
void setFallbackPipelineCache(final PipelineCache pipelineCache)
CompiledRenderPipeline getCompiledPipeline(final RenderPipeline pipeline)
void initRenderThread()
boolean isOnRenderThread()
void assertOnRenderThread()
void pollEvents(final SDLEventHandler eventHandler)
boolean isFrozenAtPollEvents()
void pumpEvents(final SDLEventHandler eventHandler)
void setShaderFog(final GpuBufferSlice fog)
void setShaderLights(final GpuBufferSlice buffer)
void enableScissorForRenderTypeDraws(final int x, final int y, final int width, final int height)
void disableScissorForRenderTypeDraws()
ScissorState getScissorStateForRenderTypeDraws()
String getBackendDescription()
NanoTimeSource initBackendSystem()
void initRenderer(final GpuDevice device)
void shutdownRenderer()
void trackBackendLibraryForShutdown(final GpuBackend backend)
void unloadTrackedBackendLibrary()
void setupDefaultState()
void setProjectionMatrix(final GpuBufferSlice projectionMatrixBuffer, final ProjectionType type)
void backupProjectionMatrix()
void restoreProjectionMatrix()
Matrix4f getModelViewMatrixCopy()
Matrix4fStack getModelViewStack()
RenderSystem.AutoStorageIndexBuffer getSequentialBuffer(final PrimitiveTopology primitiveTopology)
void setGlobalSettingsUniform(final GpuBuffer buffer)
ProjectionType getProjectionType()
void queueFencedTask(final Runnable task)
void executePendingTasks()
GpuDevice getDevice()
boolean isWireframeAvailable()
DynamicGpuData getDynamicUniforms()
void bindDefaultUniforms(final RenderPass renderPass)
void resizeAllAutoStorageIndexBuffers()
void close()
boolean hasStorage(final int indexCount)
void requestIndexCount(final int indexCount)
void resizeToRequestedIndexCount()
GpuBuffer getBuffer(final int indexCount)
GpuBuffer getBuffer()
IndexType type()

Fields & Constants (27)

LOGGER
DEFAULT_DEPTH_CLEAR_VALUE
MINIMUM_ATLAS_TEXTURE_SIZE
PROJECTION_MATRIX_UBO_SIZE
sharedSequential
sharedSequentialQuad
sharedSequentialLines
modelViewStack
pollEventsWaitStart
pollingEvents
PENDING_FENCES
scissorStateForRenderTypeDraws
samplerCache
renderThread
DEVICE
BACKEND
projectionType
savedProjectionType
shaderFog
shaderLightDirections
projectionMatrixBuffer
savedProjectionMatrixBuffer
isRenderingLevel
globalSettingsUniform
dynamicGpuData
fallbackPipelineCache
currentPipelineCache

String literals (32)

"Fallback pipeline cache already set"
"Fallback pipeline cache not yet set"
"Failed to find or load pipeline "
"Could not initialize render thread"
"Rendersystem called from wrong thread"
"SDL.app.metadata.name"
"Minecraft"
"SDL.app.metadata.version"
"SDL.app.metadata.identifier"
"com.mojang.minecraft"
"SDL.app.metadata.creator"
"Mojang Studios"
"SDL.app.metadata.copyright"
"Copyright Mojang AB."
"SDL.app.metadata.url"
"https://www.minecraft.net"
"SDL.app.metadata.type"
"game"
"SDL_NO_SIGNAL_HANDLERS"
"SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS"
"SDL_QUIT_ON_LAST_WINDOW_CLOSE"
"SDL_MOUSE_FOCUS_CLICKTHROUGH"
"SDL_ENABLE_SCREEN_KEYBOARD"
"SDL_IME_IMPLEMENTED_UI"

Full Source

RenderSystem.java495 lines · Minecraft 26.3 · verbatim
1
package com.mojang.blaze3d.systems;
2
3
import com.mojang.blaze3d.ProjectionType;
4
import com.mojang.blaze3d.buffers.Std140SizeCalculator;
5
import com.mojang.blaze3d.pipeline.PipelineCache;
6
import com.mojang.blaze3d.platform.SDLEventHandler;
7
import com.mojang.blaze3d.platform.SdlDebug;
8
import com.mojang.blaze3d.systems.RenderSystem.AutoStorageIndexBuffer.IndexGenerator;
9
import com.mojang.logging.LogUtils;
10
import com.mojang.renderpearl.api.buffers.GpuBuffer;
11
import com.mojang.renderpearl.api.buffers.GpuBufferSlice;
12
import com.mojang.renderpearl.api.commands.GpuFence;
13
import com.mojang.renderpearl.api.commands.RenderPass;
14
import com.mojang.renderpearl.api.device.GpuBackend;
15
import com.mojang.renderpearl.api.device.GpuDevice;
16
import com.mojang.renderpearl.api.pipeline.CompiledRenderPipeline;
17
import com.mojang.renderpearl.api.pipeline.IndexType;
18
import com.mojang.renderpearl.api.pipeline.PrimitiveTopology;
19
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
20
import java.nio.ByteBuffer;
21
import java.util.Locale;
22
import java.util.concurrent.atomic.AtomicBoolean;
23
import java.util.concurrent.atomic.AtomicLong;
24
import java.util.function.IntConsumer;
25
import net.fabricmc.api.EnvType;
26
import net.fabricmc.api.Environment;
27
import net.minecraft.SharedConstants;
28
import net.minecraft.client.renderer.DynamicGpuData;
29
import net.minecraft.util.ArrayListDeque;
30
import net.minecraft.util.Mth;
31
import net.minecraft.util.Util;
32
import net.minecraft.util.TimeSource.NanoTimeSource;
33
import org.joml.Matrix4f;
34
import org.joml.Matrix4fStack;
35
import org.jspecify.annotations.Nullable;
36
import org.lwjgl.Version;
37
import org.lwjgl.sdl.SDLError;
38
import org.lwjgl.sdl.SDLHints;
39
import org.lwjgl.sdl.SDLInit;
40
import org.lwjgl.sdl.SDLTimer;
41
import org.lwjgl.system.MemoryUtil;
42
import org.slf4j.Logger;
43
44
@Environment(EnvType.CLIENT)
45
public class RenderSystem {
46
	private static final Logger LOGGER = LogUtils.getLogger();
47
	public static final double DEFAULT_DEPTH_CLEAR_VALUE = 0.0;
48
	public static final int MINIMUM_ATLAS_TEXTURE_SIZE = 1024;
49
	public static final int PROJECTION_MATRIX_UBO_SIZE = new Std140SizeCalculator().putMat4f().get();
50
	private static @Nullable Thread renderThread;
51
	private static @Nullable GpuDevice DEVICE;
52
	private static @Nullable GpuBackend BACKEND;
53
	private static final RenderSystem.AutoStorageIndexBuffer sharedSequential = new RenderSystem.AutoStorageIndexBuffer(1, 1, IntConsumer::accept);
54
	private static final RenderSystem.AutoStorageIndexBuffer sharedSequentialQuad = new RenderSystem.AutoStorageIndexBuffer(4, 6, (c, i) -> {
55
		c.accept(i);
56
		c.accept(i + 1);
57
		c.accept(i + 2);
58
		c.accept(i + 2);
59
		c.accept(i + 3);
60
		c.accept(i);
61
	});
62
	private static final RenderSystem.AutoStorageIndexBuffer sharedSequentialLines = new RenderSystem.AutoStorageIndexBuffer(4, 6, (c, i) -> {
63
		c.accept(i);
64
		c.accept(i + 1);
65
		c.accept(i + 2);
66
		c.accept(i + 3);
67
		c.accept(i + 2);
68
		c.accept(i + 1);
69
	});
70
	private static ProjectionType projectionType = ProjectionType.PERSPECTIVE;
71
	private static ProjectionType savedProjectionType = ProjectionType.PERSPECTIVE;
72
	private static final Matrix4fStack modelViewStack = new Matrix4fStack(16);
73
	private static @Nullable GpuBufferSlice shaderFog = null;
74
	private static @Nullable GpuBufferSlice shaderLightDirections;
75
	private static @Nullable GpuBufferSlice projectionMatrixBuffer;
76
	private static @Nullable GpuBufferSlice savedProjectionMatrixBuffer;
77
	private static final AtomicLong pollEventsWaitStart = new AtomicLong();
78
	private static final AtomicBoolean pollingEvents = new AtomicBoolean(false);
79
	private static final ArrayListDeque<RenderSystem.GpuAsyncTask> PENDING_FENCES = new ArrayListDeque<>();
80
	public static boolean isRenderingLevel = false;
81
	private static @Nullable GpuBuffer globalSettingsUniform;
82
	private static @Nullable DynamicGpuData dynamicGpuData;
83
	private static final ScissorState scissorStateForRenderTypeDraws = new ScissorState();
84
	private static final SamplerCache samplerCache = new SamplerCache();
85
	private static @Nullable PipelineCache fallbackPipelineCache;
86
	private static @Nullable PipelineCache currentPipelineCache;
87
88
	public static SamplerCache getSamplerCache() {
89
		return samplerCache;
90
	}
91
92
	public static void setFallbackPipelineCache(final PipelineCache pipelineCache) {
93
		if (fallbackPipelineCache != null) {
94
			throw new IllegalStateException("Fallback pipeline cache already set");
95
		}
96
97
		fallbackPipelineCache = pipelineCache;
98
	}
99
100
	public static @Nullable PipelineCache setCurrentPipelineCache(final PipelineCache pipelineCache) {
101
		PipelineCache oldCache = currentPipelineCache;
102
		currentPipelineCache = pipelineCache;
103
		return oldCache;
104
	}
105
106
	public static @Nullable CompiledRenderPipeline getCompiledPipelineNullable(final RenderPipeline pipeline) {
107
		if (currentPipelineCache != null) {
108
			CompiledRenderPipeline cachedPipeline = currentPipelineCache.get(pipeline);
109
			if (cachedPipeline != null) {
110
				return cachedPipeline;
111
			}
112
		}
113
114
		if (fallbackPipelineCache == null) {
115
			throw new IllegalStateException("Fallback pipeline cache not yet set");
116
		} else {
117
			return fallbackPipelineCache.get(pipeline);
118
		}
119
	}
120
121
	public static CompiledRenderPipeline getCompiledPipeline(final RenderPipeline pipeline) {
122
		CompiledRenderPipeline compiledPipeline = getCompiledPipelineNullable(pipeline);
123
		if (compiledPipeline != null) {
124
			return compiledPipeline;
125
		} else {
126
			throw new IllegalStateException("Failed to find or load pipeline " + pipeline.getLocation());
127
		}
128
	}
129
130
	public static void initRenderThread() {
131
		if (renderThread != null) {
132
			throw new IllegalStateException("Could not initialize render thread");
133
		}
134
135
		renderThread = Thread.currentThread();
136
	}
137
138
	public static boolean isOnRenderThread() {
139
		return Thread.currentThread() == renderThread;
140
	}
141
142
	public static void assertOnRenderThread() {
143
		if (!isOnRenderThread()) {
144
			throw constructThreadException();
145
		}
146
	}
147
148
	private static IllegalStateException constructThreadException() {
149
		return new IllegalStateException("Rendersystem called from wrong thread");
150
	}
151
152
	public static void pollEvents(final SDLEventHandler eventHandler) {
153
		pollEventsWaitStart.set(Util.getMillis());
154
		pollingEvents.set(true);
155
		eventHandler.pollEvents();
156
		pollingEvents.set(false);
157
	}
158
159
	public static boolean isFrozenAtPollEvents() {
160
		return pollingEvents.get() && Util.getMillis() - pollEventsWaitStart.get() > 200L;
161
	}
162
163
	public static void pumpEvents(final SDLEventHandler eventHandler) {
164
		pollEventsWaitStart.set(Util.getMillis());
165
		pollingEvents.set(true);
166
		eventHandler.pumpEvents();
167
		pollingEvents.set(false);
168
	}
169
170
	public static void setShaderFog(final GpuBufferSlice fog) {
171
		shaderFog = fog;
172
	}
173
174
	public static @Nullable GpuBufferSlice getShaderFog() {
175
		return shaderFog;
176
	}
177
178
	public static void setShaderLights(final GpuBufferSlice buffer) {
179
		shaderLightDirections = buffer;
180
	}
181
182
	public static @Nullable GpuBufferSlice getShaderLights() {
183
		return shaderLightDirections;
184
	}
185
186
	public static void enableScissorForRenderTypeDraws(final int x, final int y, final int width, final int height) {
187
		scissorStateForRenderTypeDraws.enable(x, y, width, height);
188
	}
189
190
	public static void disableScissorForRenderTypeDraws() {
191
		scissorStateForRenderTypeDraws.disable();
192
	}
193
194
	public static ScissorState getScissorStateForRenderTypeDraws() {
195
		return scissorStateForRenderTypeDraws;
196
	}
197
198
	public static String getBackendDescription() {
199
		return String.format(Locale.ROOT, "LWJGL version %s", Version.getVersion());
200
	}
201
202
	public static NanoTimeSource initBackendSystem() {
203
		SdlDebug.init();
204
		SDLInit.SDL_SetAppMetadataProperty("SDL.app.metadata.name", "Minecraft");
205
		SDLInit.SDL_SetAppMetadataProperty("SDL.app.metadata.version", SharedConstants.getCurrentVersion().name());
206
		SDLInit.SDL_SetAppMetadataProperty("SDL.app.metadata.identifier", "com.mojang.minecraft");
207
		SDLInit.SDL_SetAppMetadataProperty("SDL.app.metadata.creator", "Mojang Studios");
208
		SDLInit.SDL_SetAppMetadataProperty("SDL.app.metadata.copyright", "Copyright Mojang AB.");
209
		SDLInit.SDL_SetAppMetadataProperty("SDL.app.metadata.url", "https://www.minecraft.net");
210
		SDLInit.SDL_SetAppMetadataProperty("SDL.app.metadata.type", "game");
211
		SDLHints.SDL_SetHint("SDL_NO_SIGNAL_HANDLERS", "1");
212
		SDLHints.SDL_SetHint("SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS", "0");
213
		SDLHints.SDL_SetHint("SDL_QUIT_ON_LAST_WINDOW_CLOSE", "0");
214
		SDLHints.SDL_SetHint("SDL_MOUSE_FOCUS_CLICKTHROUGH", "1");
215
		SDLHints.SDL_SetHint("SDL_ENABLE_SCREEN_KEYBOARD", "0");
216
		SDLHints.SDL_SetHint("SDL_IME_IMPLEMENTED_UI", "composition");
217
		if (!SDLInit.SDL_Init(32)) {
218
			throw new IllegalStateException("Unable to initialize SDL: " + SDLError.SDL_GetError());
219
		} else {
220
			return SDLTimer::SDL_GetTicksNS;
221
		}
222
	}
223
224
	public static void initRenderer(final GpuDevice device) {
225
		if (DEVICE != null) {
226
			throw new IllegalStateException("RenderSystem.DEVICE already initialized");
227
		}
228
229
		DEVICE = device;
230
		dynamicGpuData = new DynamicGpuData();
231
		samplerCache.initialize();
232
	}
233
234
	public static void shutdownRenderer() {
235
		if (currentPipelineCache != null) {
236
			currentPipelineCache.close();
237
		}
238
239
		if (fallbackPipelineCache != null) {
240
			fallbackPipelineCache.close();
241
		}
242
243
		sharedSequential.close();
244
		sharedSequentialQuad.close();
245
		sharedSequentialLines.close();
246
		samplerCache.close();
247
		if (dynamicGpuData != null) {
248
			dynamicGpuData.close();
249
		}
250
251
		if (DEVICE != null) {
252
			DEVICE.close();
253
		}
254
	}
255
256
	public static void trackBackendLibraryForShutdown(final GpuBackend backend) {
257
		BACKEND = backend;
258
	}
259
260
	public static void unloadTrackedBackendLibrary() {
261
		if (BACKEND != null) {
262
			BACKEND.unloadLibrary();
263
			BACKEND = null;
264
		}
265
	}
266
267
	public static void setupDefaultState() {
268
		modelViewStack.clear();
269
	}
270
271
	public static void setProjectionMatrix(final GpuBufferSlice projectionMatrixBuffer, final ProjectionType type) {
272
		assertOnRenderThread();
273
		RenderSystem.projectionMatrixBuffer = projectionMatrixBuffer;
274
		projectionType = type;
275
	}
276
277
	public static void backupProjectionMatrix() {
278
		assertOnRenderThread();
279
		savedProjectionMatrixBuffer = projectionMatrixBuffer;
280
		savedProjectionType = projectionType;
281
	}
282
283
	public static void restoreProjectionMatrix() {
284
		assertOnRenderThread();
285
		projectionMatrixBuffer = savedProjectionMatrixBuffer;
286
		projectionType = savedProjectionType;
287
	}
288
289
	public static @Nullable GpuBufferSlice getProjectionMatrixBuffer() {
290
		assertOnRenderThread();
291
		return projectionMatrixBuffer;
292
	}
293
294
	public static Matrix4f getModelViewMatrixCopy() {
295
		assertOnRenderThread();
296
		return new Matrix4f(modelViewStack);
297
	}
298
299
	public static Matrix4fStack getModelViewStack() {
300
		assertOnRenderThread();
301
		return modelViewStack;
302
	}
303
304
	public static RenderSystem.AutoStorageIndexBuffer getSequentialBuffer(final PrimitiveTopology primitiveTopology) {
305
		assertOnRenderThread();
306
307
		return switch (primitiveTopology) {
308
			case QUADS -> sharedSequentialQuad;
309
			case LINES -> sharedSequentialLines;
310
			default -> sharedSequential;
311
		};
312
	}
313
314
	public static void setGlobalSettingsUniform(final GpuBuffer buffer) {
315
		globalSettingsUniform = buffer;
316
	}
317
318
	public static @Nullable GpuBuffer getGlobalSettingsUniform() {
319
		return globalSettingsUniform;
320
	}
321
322
	public static ProjectionType getProjectionType() {
323
		assertOnRenderThread();
324
		return projectionType;
325
	}
326
327
	public static void queueFencedTask(final Runnable task) {
328
		PENDING_FENCES.addLast(new RenderSystem.GpuAsyncTask(task, getDevice().createCommandEncoder().createFence()));
329
	}
330
331
	public static void executePendingTasks() {
332
		for (RenderSystem.GpuAsyncTask task = PENDING_FENCES.peekFirst(); task != null; task = PENDING_FENCES.peekFirst()) {
333
			if (!task.fence.awaitCompletion(0L)) {
334
				return;
335
			}
336
337
			try {
338
				task.callback.run();
339
			} finally {
340
				task.fence.close();
341
			}
342
343
			PENDING_FENCES.removeFirst();
344
		}
345
	}
346
347
	public static GpuDevice getDevice() {
348
		if (DEVICE == null) {
349
			throw new IllegalStateException("Can't getDevice() before it was initialized");
350
		} else {
351
			return DEVICE;
352
		}
353
	}
354
355
	public static @Nullable GpuDevice tryGetDevice() {
356
		return DEVICE;
357
	}
358
359
	public static boolean isWireframeAvailable() {
360
		return getDevice().getDeviceInfo().features().wireframeFillMode();
361
	}
362
363
	public static DynamicGpuData getDynamicUniforms() {
364
		if (dynamicGpuData == null) {
365
			throw new IllegalStateException("Can't getDynamicUniforms() before device was initialized");
366
		} else {
367
			return dynamicGpuData;
368
		}
369
	}
370
371
	public static void bindDefaultUniforms(final RenderPass renderPass) {
372
		GpuBufferSlice projectionMatrix = getProjectionMatrixBuffer();
373
		if (projectionMatrix != null) {
374
			renderPass.setUniform("Projection", projectionMatrix);
375
		}
376
377
		GpuBufferSlice fog = getShaderFog();
378
		if (fog != null) {
379
			renderPass.setUniform("Fog", fog);
380
		}
381
382
		GpuBuffer globalUniform = getGlobalSettingsUniform();
383
		if (globalUniform != null) {
384
			renderPass.setUniform("Globals", globalUniform);
385
		}
386
387
		GpuBufferSlice shaderLights = getShaderLights();
388
		if (shaderLights != null) {
389
			renderPass.setUniform("Lighting", shaderLights);
390
		}
391
	}
392
393
	public static void resizeAllAutoStorageIndexBuffers() {
394
		sharedSequential.resizeToRequestedIndexCount();
395
		sharedSequentialQuad.resizeToRequestedIndexCount();
396
		sharedSequentialLines.resizeToRequestedIndexCount();
397
	}
398
399
	@Environment(EnvType.CLIENT)
400
	public static final class AutoStorageIndexBuffer implements AutoCloseable {
401
		private final int vertexStride;
402
		private final int indexStride;
403
		private final IndexGenerator generator;
404
		private @Nullable GpuBuffer buffer;
405
		private IndexType type = IndexType.SHORT;
406
		private int indexCount;
407
		private int maxRequestedIndexCount;
408
409
		private AutoStorageIndexBuffer(final int vertexStride, final int indexStride, final IndexGenerator generator) {
410
			this.vertexStride = vertexStride;
411
			this.indexStride = indexStride;
412
			this.generator = generator;
413
		}
414
415
		@Override
416
		public void close() {
417
			if (this.buffer != null) {
418
				this.buffer.close();
419
			}
420
		}
421
422
		public boolean hasStorage(final int indexCount) {
423
			return indexCount <= this.indexCount;
424
		}
425
426
		public void requestIndexCount(final int indexCount) {
427
			this.maxRequestedIndexCount = Math.max(this.maxRequestedIndexCount, indexCount);
428
		}
429
430
		public void resizeToRequestedIndexCount() {
431
			this.ensureStorage(this.maxRequestedIndexCount);
432
		}
433
434
		public GpuBuffer getBuffer(final int indexCount) {
435
			this.requestIndexCount(indexCount);
436
			this.ensureStorage(indexCount);
437
			return this.buffer;
438
		}
439
440
		public GpuBuffer getBuffer() {
441
			return this.buffer;
442
		}
443
444
		private void ensureStorage(int indexCount) {
445
			if (!this.hasStorage(indexCount)) {
446
				indexCount = Mth.roundToward(indexCount * 2, this.indexStride);
447
				RenderSystem.LOGGER.debug("Growing IndexBuffer: Old limit {}, new limit {}.", this.indexCount, indexCount);
448
				int primitiveCount = indexCount / this.indexStride;
449
				int vertexCount = primitiveCount * this.vertexStride;
450
				IndexType type = IndexType.least(vertexCount);
451
				int bufferSize = Mth.roundToward(indexCount * type.bytes, 4);
452
				ByteBuffer data = MemoryUtil.memAlloc(bufferSize);
453
454
				try {
455
					this.type = type;
456
					it.unimi.dsi.fastutil.ints.IntConsumer intConsumer = this.intConsumer(data);
457
458
					for (int ii = 0; ii < indexCount; ii += this.indexStride) {
459
						this.generator.accept(intConsumer, ii * this.vertexStride / this.indexStride);
460
					}
461
462
					data.flip();
463
					if (this.buffer != null) {
464
						this.buffer.close();
465
					}
466
467
					this.buffer = RenderSystem.getDevice().createBuffer(() -> "Auto Storage index buffer", 64, data);
468
				} finally {
469
					MemoryUtil.memFree(data);
470
				}
471
472
				this.indexCount = indexCount;
473
			}
474
		}
475
476
		private it.unimi.dsi.fastutil.ints.IntConsumer intConsumer(final ByteBuffer buffer) {
477
			switch (this.type) {
478
				case SHORT:
479
					return value -> buffer.putShort((short)value);
480
				case INT:
481
				default:
482
					return buffer::putInt;
483
			}
484
		}
485
486
		public IndexType type() {
487
			return this.type;
488
		}
489
	}
490
491
	@Environment(EnvType.CLIENT)
492
	private record GpuAsyncTask(Runnable callback, GpuFence fence) {
493
	}
494
}
495

Decompiled Minecraft 26.3 source of RenderSystem (com/mojang/blaze3d/systems/RenderSystem.java) with Mojang official mappings, stored verbatim on the site.