| 1 | package net.minecraft.client.renderer;
|
| 2 |
|
| 3 | import com.mojang.blaze3d.buffers.Std140Builder;
|
| 4 | import com.mojang.blaze3d.systems.RenderSystem;
|
| 5 | import com.mojang.renderpearl.api.buffers.GpuBuffer;
|
| 6 | import com.mojang.renderpearl.api.buffers.GpuBufferSlice;
|
| 7 | import com.mojang.renderpearl.api.device.GpuDevice;
|
| 8 | import java.nio.ByteBuffer;
|
| 9 | import net.fabricmc.api.EnvType;
|
| 10 | import net.fabricmc.api.Environment;
|
| 11 | import org.joml.Matrix4f;
|
| 12 | import org.jspecify.annotations.Nullable;
|
| 13 | import org.lwjgl.system.MemoryStack;
|
| 14 |
|
| 15 | @Environment(EnvType.CLIENT)
|
| 16 | public class ProjectionMatrixBuffer implements AutoCloseable {
|
| 17 | private final GpuBuffer buffer;
|
| 18 | private final GpuBufferSlice bufferSlice;
|
| 19 | private @Nullable Projection lastUploadedProjection;
|
| 20 | private long projectionMatrixVersion;
|
| 21 | private final Matrix4f tempMatrix = new Matrix4f();
|
| 22 |
|
| 23 | public ProjectionMatrixBuffer(final String name) {
|
| 24 | this.lastUploadedProjection = null;
|
| 25 | this.projectionMatrixVersion = -1L;
|
| 26 | GpuDevice device = RenderSystem.getDevice();
|
| 27 | this.buffer = device.createBuffer(() -> "Camera projection matrix UBO " + name, 136, RenderSystem.PROJECTION_MATRIX_UBO_SIZE);
|
| 28 | this.bufferSlice = this.buffer.slice(0L, RenderSystem.PROJECTION_MATRIX_UBO_SIZE);
|
| 29 | }
|
| 30 |
|
| 31 | public GpuBufferSlice getBuffer(final Projection projection) {
|
| 32 | assert projection.getMatrixVersion() != -1L;
|
| 33 | if (this.lastUploadedProjection == projection && projection.getMatrixVersion() == this.projectionMatrixVersion) {
|
| 34 | return this.bufferSlice;
|
| 35 | }
|
| 36 |
|
| 37 | this.lastUploadedProjection = projection;
|
| 38 | this.projectionMatrixVersion = projection.getMatrixVersion();
|
| 39 | return this.writeBuffer(projection.getMatrix(this.tempMatrix));
|
| 40 | }
|
| 41 |
|
| 42 | public GpuBufferSlice getBuffer(final Matrix4f projectionMatrix) {
|
| 43 | this.lastUploadedProjection = null;
|
| 44 | this.projectionMatrixVersion = -1L;
|
| 45 | return this.writeBuffer(projectionMatrix);
|
| 46 | }
|
| 47 |
|
| 48 | private GpuBufferSlice writeBuffer(final Matrix4f projectionMatrix) {
|
| 49 | try (MemoryStack stack = MemoryStack.stackPush()) {
|
| 50 | ByteBuffer byteBuffer = Std140Builder.onStack(stack, RenderSystem.PROJECTION_MATRIX_UBO_SIZE).putMat4f(projectionMatrix).get();
|
| 51 | RenderSystem.getDevice().createCommandEncoder().writeToBuffer(this.buffer.slice(), byteBuffer);
|
| 52 | }
|
| 53 |
|
| 54 | return this.bufferSlice;
|
| 55 | }
|
| 56 |
|
| 57 | @Override
|
| 58 | public void close() {
|
| 59 | this.buffer.close();
|
| 60 | }
|
| 61 | }
|
| 62 |
|