Vertex pulling #48
No files matched your search
+16
-2
@@ -6,6 +6,7 @@ import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
|||||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
|
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.parameters.AlphaCutoffParameter;
|
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.parameters.AlphaCutoffParameter;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkMeshFormats;
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkMeshFormats;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -27,11 +28,24 @@ public final class BenchRenderPasses {
|
|||||||
private BenchRenderPasses() {
|
private BenchRenderPasses() {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Selected with {@code -Dceleritas.bench.vertexType=COMPACT|VANILLA_LIKE}, since passes are built once per JVM.
|
||||||
|
*/
|
||||||
|
private static ChunkVertexType vertexType() {
|
||||||
|
String name = System.getProperty("celeritas.bench.vertexType", "COMPACT");
|
||||||
|
|
||||||
|
return switch (name) {
|
||||||
|
case "COMPACT" -> ChunkMeshFormats.COMPACT;
|
||||||
|
case "VANILLA_LIKE" -> ChunkMeshFormats.VANILLA_LIKE;
|
||||||
|
default -> throw new IllegalArgumentException("Unknown bench vertex type " + name);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
private static TerrainRenderPass.TerrainRenderPassBuilder builder() {
|
private static TerrainRenderPass.TerrainRenderPassBuilder builder() {
|
||||||
// No GL state: the benchmark never draws.
|
// No GL state: draw benchmarks set up the pipeline themselves.
|
||||||
return TerrainRenderPass.builder()
|
return TerrainRenderPass.builder()
|
||||||
.pipelineState(TerrainRenderPass.PipelineState.DEFAULT)
|
.pipelineState(TerrainRenderPass.PipelineState.DEFAULT)
|
||||||
.vertexType(ChunkMeshFormats.COMPACT)
|
.vertexType(vertexType())
|
||||||
.primitiveType(QuadPrimitiveType.TRIANGULATED);
|
.primitiveType(QuadPrimitiveType.TRIANGULATED);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+358
@@ -0,0 +1,358 @@
|
|||||||
|
package org.embeddedt.embeddium.impl.render.chunk.draw.bench;
|
||||||
|
|
||||||
|
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.ChunkRenderMatrices;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.DefaultChunkRenderer;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.bench.voxel.BenchRenderPasses;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.fog.FogService;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.multidraw.bench.MultiDrawBench;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.occlusion.bench.Cameras;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.occlusion.bench.HeadlessGl;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.occlusion.bench.WorldType;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkFogMode;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderComponent;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderTextureSlot;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
||||||
|
import org.joml.Matrix4f;
|
||||||
|
import org.lwjgl.opengl.GL11C;
|
||||||
|
import org.lwjgl.opengl.GL12C;
|
||||||
|
import org.lwjgl.opengl.GL13C;
|
||||||
|
import org.lwjgl.opengl.GL14C;
|
||||||
|
import org.lwjgl.opengl.GL15C;
|
||||||
|
import org.lwjgl.opengl.GL30C;
|
||||||
|
import org.lwjgl.opengl.GL33C;
|
||||||
|
import org.lwjgl.system.MemoryUtil;
|
||||||
|
import org.openjdk.jmh.annotations.Benchmark;
|
||||||
|
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||||
|
import org.openjdk.jmh.annotations.Level;
|
||||||
|
import org.openjdk.jmh.annotations.Fork;
|
||||||
|
import org.openjdk.jmh.annotations.Measurement;
|
||||||
|
import org.openjdk.jmh.annotations.Mode;
|
||||||
|
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||||
|
import org.openjdk.jmh.annotations.Param;
|
||||||
|
import org.openjdk.jmh.annotations.Scope;
|
||||||
|
import org.openjdk.jmh.annotations.Setup;
|
||||||
|
import org.openjdk.jmh.annotations.State;
|
||||||
|
import org.openjdk.jmh.annotations.TearDown;
|
||||||
|
import org.openjdk.jmh.annotations.Warmup;
|
||||||
|
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.util.Random;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.zip.CRC32;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GPU cost of drawing terrain: whole frames of the real terrain passes into an offscreen framebuffer, timed to
|
||||||
|
* completion with {@code glFinish}. The fetch path and vertex format are fixed per JVM, so compare runs with
|
||||||
|
* {@code -Dceleritas.preferVertexPulling=true} and {@code -Dceleritas.bench.vertexType=VANILLA_LIKE} appended.
|
||||||
|
* <p>
|
||||||
|
* Setup prints a checksum of the first frame, which should not depend on the fetch path.
|
||||||
|
*/
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||||
|
@Fork(1)
|
||||||
|
@Warmup(iterations = 3, time = 2, timeUnit = TimeUnit.SECONDS)
|
||||||
|
@Measurement(iterations = 5, time = 2, timeUnit = TimeUnit.SECONDS)
|
||||||
|
public class TerrainDrawBench {
|
||||||
|
private static final FogService NO_FOG = new FogService() {
|
||||||
|
@Override
|
||||||
|
public float getFogEnd() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public float getFogStart() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public float getFogDensity() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getFogShapeIndex() {
|
||||||
|
return FOG_SHAPE_SPHERICAL;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public float getFogCutoff() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public float[] getFogColor() {
|
||||||
|
return new float[4];
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ChunkShaderComponent.Factory<?> getFogMode() {
|
||||||
|
return ChunkFogMode.NONE;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
@State(Scope.Benchmark)
|
||||||
|
public static class DrawState {
|
||||||
|
@Param({ "32" })
|
||||||
|
public int renderDistance;
|
||||||
|
|
||||||
|
/** Framebuffer width; the height follows the bench cameras' 16:9 aspect. Low widths are vertex-bound. */
|
||||||
|
@Param({ "640", "2560" })
|
||||||
|
public int width;
|
||||||
|
|
||||||
|
private int height;
|
||||||
|
|
||||||
|
private MultiDrawBench.FrameState frames;
|
||||||
|
private ChunkRenderMatrices[] matrices;
|
||||||
|
private DefaultChunkRenderer renderer;
|
||||||
|
|
||||||
|
private int framebuffer;
|
||||||
|
private int colorTexture;
|
||||||
|
private int depthRenderbuffer;
|
||||||
|
private int blockTexture;
|
||||||
|
private int lightTexture;
|
||||||
|
|
||||||
|
private int frameIndex;
|
||||||
|
|
||||||
|
private int timerQuery;
|
||||||
|
private long gpuNanos;
|
||||||
|
private long submitNanos;
|
||||||
|
private int timedFrames;
|
||||||
|
|
||||||
|
@Setup
|
||||||
|
public void setup() {
|
||||||
|
this.frames = new MultiDrawBench.FrameState();
|
||||||
|
this.frames.world = WorldType.SURFACE;
|
||||||
|
this.frames.renderDistance = this.renderDistance;
|
||||||
|
this.frames.caveWidth = 0.03;
|
||||||
|
this.frames.useBlockFaceCulling = true;
|
||||||
|
this.frames.setup();
|
||||||
|
|
||||||
|
this.height = this.width * 9 / 16;
|
||||||
|
this.matrices = createMatrices(this.renderDistance);
|
||||||
|
|
||||||
|
this.renderer = new DefaultChunkRenderer(RenderDevice.INSTANCE, BenchRenderPasses.configuration(), NO_FOG) {
|
||||||
|
@Override
|
||||||
|
protected void configureShaderInterface(ChunkShaderInterface shader) {
|
||||||
|
shader.setTextureSlot(ChunkShaderTextureSlot.BLOCK, 0);
|
||||||
|
shader.setTextureSlot(ChunkShaderTextureSlot.LIGHT, 2);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
this.createFramebuffer();
|
||||||
|
this.blockTexture = createBlockTexture();
|
||||||
|
this.lightTexture = createLightTexture();
|
||||||
|
|
||||||
|
this.timerQuery = GL15C.glGenQueries();
|
||||||
|
|
||||||
|
this.drawFrame(0);
|
||||||
|
|
||||||
|
System.out.printf("%n[TerrainDrawBench] %s | pass fetch=%s format=%s | %dx%d | first frame crc=%08x covered=%d%n",
|
||||||
|
HeadlessGl.describe(), BenchRenderPasses.SOLID.vertexFetchMode(),
|
||||||
|
BenchRenderPasses.SOLID.vertexType().getClass().getSimpleName(),
|
||||||
|
this.width, this.height, this.checksum(), this.coveredPixels());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ChunkRenderMatrices[] createMatrices(int renderDistance) {
|
||||||
|
var matrices = new ChunkRenderMatrices[MultiDrawBench.ROTATION_STEPS];
|
||||||
|
var projection = new Matrix4f().perspective((float) Math.toRadians(Cameras.FOV_DEGREES), Cameras.ASPECT,
|
||||||
|
Cameras.NEAR_PLANE, Cameras.farPlane(renderDistance));
|
||||||
|
|
||||||
|
// Must match Cameras.yawRing, which built the frames' visibility lists
|
||||||
|
for (int i = 0; i < matrices.length; i++) {
|
||||||
|
float yaw = (360.0f / matrices.length) * i;
|
||||||
|
var modelView = new Matrix4f()
|
||||||
|
.rotateX((float) Math.toRadians(Cameras.DEFAULT_PITCH))
|
||||||
|
.rotateY((float) Math.toRadians(yaw + 180.0f));
|
||||||
|
|
||||||
|
matrices[i] = new ChunkRenderMatrices(projection, modelView);
|
||||||
|
}
|
||||||
|
|
||||||
|
return matrices;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createFramebuffer() {
|
||||||
|
this.colorTexture = GL11C.glGenTextures();
|
||||||
|
GL11C.glBindTexture(GL11C.GL_TEXTURE_2D, this.colorTexture);
|
||||||
|
GL11C.glTexImage2D(GL11C.GL_TEXTURE_2D, 0, GL11C.GL_RGBA8, this.width, this.height, 0,
|
||||||
|
GL11C.GL_RGBA, GL11C.GL_UNSIGNED_BYTE, (ByteBuffer) null);
|
||||||
|
|
||||||
|
this.depthRenderbuffer = GL30C.glGenRenderbuffers();
|
||||||
|
GL30C.glBindRenderbuffer(GL30C.GL_RENDERBUFFER, this.depthRenderbuffer);
|
||||||
|
GL30C.glRenderbufferStorage(GL30C.GL_RENDERBUFFER, GL14C.GL_DEPTH_COMPONENT24, this.width, this.height);
|
||||||
|
|
||||||
|
this.framebuffer = GL30C.glGenFramebuffers();
|
||||||
|
GL30C.glBindFramebuffer(GL30C.GL_FRAMEBUFFER, this.framebuffer);
|
||||||
|
GL30C.glFramebufferTexture2D(GL30C.GL_FRAMEBUFFER, GL30C.GL_COLOR_ATTACHMENT0, GL11C.GL_TEXTURE_2D, this.colorTexture, 0);
|
||||||
|
GL30C.glFramebufferRenderbuffer(GL30C.GL_FRAMEBUFFER, GL30C.GL_DEPTH_ATTACHMENT, GL30C.GL_RENDERBUFFER, this.depthRenderbuffer);
|
||||||
|
|
||||||
|
int status = GL30C.glCheckFramebufferStatus(GL30C.GL_FRAMEBUFFER);
|
||||||
|
|
||||||
|
if (status != GL30C.GL_FRAMEBUFFER_COMPLETE) {
|
||||||
|
throw new IllegalStateException("Framebuffer incomplete: 0x" + Integer.toHexString(status));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A 16x16 noise sprite with mipmaps, standing in for one atlas sprite per block face. */
|
||||||
|
private static int createBlockTexture() {
|
||||||
|
var random = new Random(42);
|
||||||
|
ByteBuffer pixels = MemoryUtil.memAlloc(16 * 16 * 4);
|
||||||
|
|
||||||
|
for (int i = 0; i < 16 * 16; i++) {
|
||||||
|
pixels.put((byte) (64 + random.nextInt(192)))
|
||||||
|
.put((byte) (64 + random.nextInt(192)))
|
||||||
|
.put((byte) (64 + random.nextInt(192)))
|
||||||
|
.put((byte) 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
pixels.flip();
|
||||||
|
|
||||||
|
int texture = GL11C.glGenTextures();
|
||||||
|
GL11C.glBindTexture(GL11C.GL_TEXTURE_2D, texture);
|
||||||
|
GL11C.glTexImage2D(GL11C.GL_TEXTURE_2D, 0, GL11C.GL_RGBA8, 16, 16, 0, GL11C.GL_RGBA, GL11C.GL_UNSIGNED_BYTE, pixels);
|
||||||
|
GL30C.glGenerateMipmap(GL11C.GL_TEXTURE_2D);
|
||||||
|
GL11C.glTexParameteri(GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_MIN_FILTER, GL11C.GL_NEAREST_MIPMAP_LINEAR);
|
||||||
|
GL11C.glTexParameteri(GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_MAG_FILTER, GL11C.GL_NEAREST);
|
||||||
|
|
||||||
|
MemoryUtil.memFree(pixels);
|
||||||
|
|
||||||
|
return texture;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int createLightTexture() {
|
||||||
|
ByteBuffer pixels = MemoryUtil.memAlloc(16 * 16 * 4);
|
||||||
|
|
||||||
|
for (int sky = 0; sky < 16; sky++) {
|
||||||
|
for (int block = 0; block < 16; block++) {
|
||||||
|
int level = Math.max(sky, block) * 17;
|
||||||
|
pixels.put((byte) level).put((byte) level).put((byte) level).put((byte) 255);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pixels.flip();
|
||||||
|
|
||||||
|
int texture = GL11C.glGenTextures();
|
||||||
|
GL11C.glBindTexture(GL11C.GL_TEXTURE_2D, texture);
|
||||||
|
GL11C.glTexImage2D(GL11C.GL_TEXTURE_2D, 0, GL11C.GL_RGBA8, 16, 16, 0, GL11C.GL_RGBA, GL11C.GL_UNSIGNED_BYTE, pixels);
|
||||||
|
GL11C.glTexParameteri(GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_MIN_FILTER, GL11C.GL_LINEAR);
|
||||||
|
GL11C.glTexParameteri(GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_MAG_FILTER, GL11C.GL_LINEAR);
|
||||||
|
GL11C.glTexParameteri(GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_WRAP_S, GL12C.GL_CLAMP_TO_EDGE);
|
||||||
|
GL11C.glTexParameteri(GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_WRAP_T, GL12C.GL_CLAMP_TO_EDGE);
|
||||||
|
|
||||||
|
MemoryUtil.memFree(pixels);
|
||||||
|
|
||||||
|
return texture;
|
||||||
|
}
|
||||||
|
|
||||||
|
void drawFrame(int rotation) {
|
||||||
|
GL30C.glBindFramebuffer(GL30C.GL_FRAMEBUFFER, this.framebuffer);
|
||||||
|
GL11C.glViewport(0, 0, this.width, this.height);
|
||||||
|
GL11C.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
|
||||||
|
GL11C.glClear(GL11C.GL_COLOR_BUFFER_BIT | GL11C.GL_DEPTH_BUFFER_BIT);
|
||||||
|
|
||||||
|
GL11C.glEnable(GL11C.GL_DEPTH_TEST);
|
||||||
|
GL11C.glDepthFunc(GL11C.GL_LEQUAL);
|
||||||
|
GL11C.glEnable(GL11C.GL_CULL_FACE);
|
||||||
|
|
||||||
|
GL13C.glActiveTexture(GL13C.GL_TEXTURE2);
|
||||||
|
GL11C.glBindTexture(GL11C.GL_TEXTURE_2D, this.lightTexture);
|
||||||
|
GL13C.glActiveTexture(GL13C.GL_TEXTURE0);
|
||||||
|
GL11C.glBindTexture(GL11C.GL_TEXTURE_2D, this.blockTexture);
|
||||||
|
|
||||||
|
var lists = this.frames.frames[rotation];
|
||||||
|
var camera = this.frames.camera;
|
||||||
|
|
||||||
|
long submitStart = System.nanoTime();
|
||||||
|
GL15C.glBeginQuery(GL33C.GL_TIME_ELAPSED, this.timerQuery);
|
||||||
|
|
||||||
|
try (var commandList = RenderDevice.INSTANCE.createCommandList()) {
|
||||||
|
for (TerrainRenderPass pass : new TerrainRenderPass[] { BenchRenderPasses.SOLID, BenchRenderPasses.CUTOUT_MIPPED }) {
|
||||||
|
this.renderer.render(this.matrices[rotation], commandList, lists, pass, camera, camera);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
GL15C.glEndQuery(GL33C.GL_TIME_ELAPSED);
|
||||||
|
this.submitNanos += System.nanoTime() - submitStart;
|
||||||
|
|
||||||
|
GL11C.glFinish();
|
||||||
|
|
||||||
|
this.gpuNanos += GL33C.glGetQueryObjecti64(this.timerQuery, GL15C.GL_QUERY_RESULT);
|
||||||
|
this.timedFrames++;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Setup(Level.Iteration)
|
||||||
|
public void resetTimers() {
|
||||||
|
this.gpuNanos = 0;
|
||||||
|
this.submitNanos = 0;
|
||||||
|
this.timedFrames = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Splits each iteration's frame time into GPU execution and CPU submission. */
|
||||||
|
@TearDown(Level.Iteration)
|
||||||
|
public void reportTimers() {
|
||||||
|
if (this.timedFrames > 0) {
|
||||||
|
System.out.printf("%n[TerrainDrawBench] gpu=%.1f us submit=%.1f us over %d frames%n",
|
||||||
|
this.gpuNanos / 1000.0 / this.timedFrames, this.submitNanos / 1000.0 / this.timedFrames, this.timedFrames);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private long checksum() {
|
||||||
|
ByteBuffer pixels = this.readPixels();
|
||||||
|
var crc = new CRC32();
|
||||||
|
crc.update(pixels);
|
||||||
|
MemoryUtil.memFree(pixels);
|
||||||
|
|
||||||
|
return crc.getValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
private int coveredPixels() {
|
||||||
|
ByteBuffer pixels = this.readPixels();
|
||||||
|
int covered = 0;
|
||||||
|
|
||||||
|
for (int i = 3; i < pixels.capacity(); i += 4) {
|
||||||
|
if (pixels.get(i) != 0) {
|
||||||
|
covered++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MemoryUtil.memFree(pixels);
|
||||||
|
|
||||||
|
return covered;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ByteBuffer readPixels() {
|
||||||
|
ByteBuffer pixels = MemoryUtil.memAlloc(this.width * this.height * 4);
|
||||||
|
GL30C.glBindFramebuffer(GL30C.GL_FRAMEBUFFER, this.framebuffer);
|
||||||
|
GL11C.glReadPixels(0, 0, this.width, this.height, GL11C.GL_RGBA, GL11C.GL_UNSIGNED_BYTE, pixels);
|
||||||
|
|
||||||
|
return pixels;
|
||||||
|
}
|
||||||
|
|
||||||
|
int nextRotation() {
|
||||||
|
int rotation = this.frameIndex;
|
||||||
|
this.frameIndex = (rotation + 1) % this.matrices.length;
|
||||||
|
return rotation;
|
||||||
|
}
|
||||||
|
|
||||||
|
@TearDown
|
||||||
|
public void tearDown() {
|
||||||
|
try (var commandList = RenderDevice.INSTANCE.createCommandList()) {
|
||||||
|
this.renderer.delete(commandList);
|
||||||
|
}
|
||||||
|
|
||||||
|
GL15C.glDeleteQueries(this.timerQuery);
|
||||||
|
GL30C.glDeleteFramebuffers(this.framebuffer);
|
||||||
|
GL30C.glDeleteRenderbuffers(this.depthRenderbuffer);
|
||||||
|
GL11C.glDeleteTextures(new int[] { this.colorTexture, this.blockTexture, this.lightTexture });
|
||||||
|
|
||||||
|
this.frames.tearDown();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Solid and cutout passes for one frame, rotating through the camera ring. */
|
||||||
|
@Benchmark
|
||||||
|
public void drawOpaque(DrawState state) {
|
||||||
|
state.drawFrame(state.nextRotation());
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -51,7 +51,7 @@ import java.util.concurrent.TimeUnit;
|
|||||||
@Warmup(iterations = 2, time = 1, timeUnit = TimeUnit.SECONDS)
|
@Warmup(iterations = 2, time = 1, timeUnit = TimeUnit.SECONDS)
|
||||||
@Measurement(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS)
|
@Measurement(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS)
|
||||||
public class MultiDrawBench {
|
public class MultiDrawBench {
|
||||||
private static final int ROTATION_STEPS = 8;
|
public static final int ROTATION_STEPS = 8;
|
||||||
private static final int TARGET_QUEUE_SIZE = 32 * 10;
|
private static final int TARGET_QUEUE_SIZE = 32 * 10;
|
||||||
private static final int UPLOAD_BATCH = 256;
|
private static final int UPLOAD_BATCH = 256;
|
||||||
|
|
||||||
|
|||||||
@@ -13,10 +13,12 @@ import org.apache.logging.log4j.Logger;
|
|||||||
import org.lwjgl.opengl.APPLEVertexArrayObject;
|
import org.lwjgl.opengl.APPLEVertexArrayObject;
|
||||||
import org.lwjgl.opengl.ARBBufferStorage;
|
import org.lwjgl.opengl.ARBBufferStorage;
|
||||||
import org.lwjgl.opengl.ARBInstancedArrays;
|
import org.lwjgl.opengl.ARBInstancedArrays;
|
||||||
|
import org.lwjgl.opengl.ARBTextureBufferObject;
|
||||||
import org.lwjgl.opengl.ARBTimerQuery;
|
import org.lwjgl.opengl.ARBTimerQuery;
|
||||||
import org.lwjgl.opengl.ARBVertexArrayObject;
|
import org.lwjgl.opengl.ARBVertexArrayObject;
|
||||||
import org.lwjgl.opengl.ContextCapabilities;
|
import org.lwjgl.opengl.ContextCapabilities;
|
||||||
import org.lwjgl.opengl.EXTGpuShader4;
|
import org.lwjgl.opengl.EXTGpuShader4;
|
||||||
|
import org.lwjgl.opengl.EXTTextureBufferObject;
|
||||||
import org.lwjgl.opengl.EXTTimerQuery;
|
import org.lwjgl.opengl.EXTTimerQuery;
|
||||||
import org.lwjgl.opengl.GL11;
|
import org.lwjgl.opengl.GL11;
|
||||||
import org.lwjgl.opengl.GL13;
|
import org.lwjgl.opengl.GL13;
|
||||||
@@ -255,6 +257,9 @@ public record LWJGL2Service(
|
|||||||
case ARB_texture_storage -> caps.GL_ARB_texture_storage;
|
case ARB_texture_storage -> caps.GL_ARB_texture_storage;
|
||||||
case ARB_base_instance -> caps.GL_ARB_base_instance;
|
case ARB_base_instance -> caps.GL_ARB_base_instance;
|
||||||
case ARB_compatibility -> caps.GL_ARB_compatibility;
|
case ARB_compatibility -> caps.GL_ARB_compatibility;
|
||||||
|
case ARB_texture_buffer_object -> caps.GL_ARB_texture_buffer_object;
|
||||||
|
case EXT_texture_buffer_object -> caps.GL_EXT_texture_buffer_object;
|
||||||
|
case EXT_gpu_shader4 -> caps.GL_EXT_gpu_shader4;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -753,6 +758,21 @@ public record LWJGL2Service(
|
|||||||
GL11.glTexParameteri(target, pname, param);
|
GL11.glTexParameteri(target, pname, param);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void glTexBuffer(int target, int internalFormat, int buffer) {
|
||||||
|
GL31.glTexBuffer(target, internalFormat, buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void glTexBufferARB(int target, int internalFormat, int buffer) {
|
||||||
|
ARBTextureBufferObject.glTexBufferARB(target, internalFormat, buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void glTexBufferEXT(int target, int internalFormat, int buffer) {
|
||||||
|
EXTTextureBufferObject.glTexBufferEXT(target, internalFormat, buffer);
|
||||||
|
}
|
||||||
|
|
||||||
// ===================== FRAMEBUFFER OPERATIONS =====================
|
// ===================== FRAMEBUFFER OPERATIONS =====================
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -79,6 +79,9 @@ public record LWJGL3Service(
|
|||||||
case ARB_texture_storage -> caps.GL_ARB_texture_storage;
|
case ARB_texture_storage -> caps.GL_ARB_texture_storage;
|
||||||
case ARB_base_instance -> caps.GL_ARB_base_instance;
|
case ARB_base_instance -> caps.GL_ARB_base_instance;
|
||||||
case ARB_compatibility -> caps.GL_ARB_compatibility;
|
case ARB_compatibility -> caps.GL_ARB_compatibility;
|
||||||
|
case ARB_texture_buffer_object -> caps.GL_ARB_texture_buffer_object;
|
||||||
|
case EXT_texture_buffer_object -> caps.GL_EXT_texture_buffer_object;
|
||||||
|
case EXT_gpu_shader4 -> caps.GL_EXT_gpu_shader4;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -650,6 +653,21 @@ public record LWJGL3Service(
|
|||||||
GL11C.glTexParameteri(target, pname, param);
|
GL11C.glTexParameteri(target, pname, param);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void glTexBuffer(int target, int internalFormat, int buffer) {
|
||||||
|
GL31C.glTexBuffer(target, internalFormat, buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void glTexBufferARB(int target, int internalFormat, int buffer) {
|
||||||
|
ARBTextureBufferObject.glTexBufferARB(target, internalFormat, buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void glTexBufferEXT(int target, int internalFormat, int buffer) {
|
||||||
|
EXTTextureBufferObject.glTexBufferEXT(target, internalFormat, buffer);
|
||||||
|
}
|
||||||
|
|
||||||
// ===================== FRAMEBUFFER OPERATIONS =====================
|
// ===================== FRAMEBUFFER OPERATIONS =====================
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -20,5 +20,8 @@ public enum GLExtension {
|
|||||||
ARB_copy_buffer,
|
ARB_copy_buffer,
|
||||||
ARB_texture_storage,
|
ARB_texture_storage,
|
||||||
ARB_base_instance,
|
ARB_base_instance,
|
||||||
ARB_compatibility
|
ARB_compatibility,
|
||||||
|
ARB_texture_buffer_object,
|
||||||
|
EXT_texture_buffer_object,
|
||||||
|
EXT_gpu_shader4
|
||||||
}
|
}
|
||||||
@@ -138,6 +138,9 @@ public interface LWJGLService {
|
|||||||
void glPixelStorei(int pname, int param);
|
void glPixelStorei(int pname, int param);
|
||||||
void glTexImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, ByteBuffer pixels);
|
void glTexImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, ByteBuffer pixels);
|
||||||
void glTexParameteri(int target, int pname, int param);
|
void glTexParameteri(int target, int pname, int param);
|
||||||
|
void glTexBuffer(int target, int internalFormat, int buffer);
|
||||||
|
void glTexBufferARB(int target, int internalFormat, int buffer);
|
||||||
|
void glTexBufferEXT(int target, int internalFormat, int buffer);
|
||||||
|
|
||||||
// ===================== FRAMEBUFFER OPERATIONS =====================
|
// ===================== FRAMEBUFFER OPERATIONS =====================
|
||||||
|
|
||||||
|
|||||||
+14
-2
@@ -2,12 +2,24 @@ package org.embeddedt.embeddium.impl.gl.functions;
|
|||||||
|
|
||||||
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
|
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param maxTextureBufferTexels the number of texels a texture buffer may address, or 0 if texture buffers are unsupported
|
||||||
|
*/
|
||||||
public record DeviceFunctions(BufferCopyFunctions bufferCopyFunctions,
|
public record DeviceFunctions(BufferCopyFunctions bufferCopyFunctions,
|
||||||
BufferMapRangeFunctions bufferMapRangeFunctions) {
|
BufferMapRangeFunctions bufferMapRangeFunctions,
|
||||||
|
TextureBufferFunctions textureBufferFunctions,
|
||||||
|
int maxTextureBufferTexels) {
|
||||||
public DeviceFunctions(RenderDevice device) {
|
public DeviceFunctions(RenderDevice device) {
|
||||||
this(
|
this(
|
||||||
BufferCopyFunctions.pickBest(device),
|
BufferCopyFunctions.pickBest(device),
|
||||||
BufferMapRangeFunctions.pickBest(device)
|
BufferMapRangeFunctions.pickBest(device),
|
||||||
|
TextureBufferFunctions.pickBest(device)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private DeviceFunctions(BufferCopyFunctions bufferCopyFunctions,
|
||||||
|
BufferMapRangeFunctions bufferMapRangeFunctions,
|
||||||
|
TextureBufferFunctions textureBufferFunctions) {
|
||||||
|
this(bufferCopyFunctions, bufferMapRangeFunctions, textureBufferFunctions, textureBufferFunctions.queryMaxTexels());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+65
@@ -0,0 +1,65 @@
|
|||||||
|
package org.embeddedt.embeddium.impl.gl.functions;
|
||||||
|
|
||||||
|
import org.embeddedt.embeddium.impl.gl.buffer.GlBuffer;
|
||||||
|
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
|
||||||
|
import org.taumc.celeritas.lwjgl.GL31;
|
||||||
|
import org.taumc.celeritas.lwjgl.GLExtension;
|
||||||
|
|
||||||
|
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
|
||||||
|
|
||||||
|
public enum TextureBufferFunctions {
|
||||||
|
CORE {
|
||||||
|
@Override
|
||||||
|
public void texBuffer(int target, int internalFormat, GlBuffer buffer) {
|
||||||
|
LWJGL.glTexBuffer(target, internalFormat, buffer.handle());
|
||||||
|
}
|
||||||
|
},
|
||||||
|
ARB {
|
||||||
|
@Override
|
||||||
|
public void texBuffer(int target, int internalFormat, GlBuffer buffer) {
|
||||||
|
LWJGL.glTexBufferARB(target, internalFormat, buffer.handle());
|
||||||
|
}
|
||||||
|
},
|
||||||
|
EXT {
|
||||||
|
@Override
|
||||||
|
public void texBuffer(int target, int internalFormat, GlBuffer buffer) {
|
||||||
|
LWJGL.glTexBufferEXT(target, internalFormat, buffer.handle());
|
||||||
|
}
|
||||||
|
},
|
||||||
|
NONE {
|
||||||
|
@Override
|
||||||
|
public void texBuffer(int target, int internalFormat, GlBuffer buffer) {
|
||||||
|
throw new UnsupportedOperationException("Texture buffers are not supported");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
public abstract void texBuffer(int target, int internalFormat, GlBuffer buffer);
|
||||||
|
|
||||||
|
public boolean isSupported() {
|
||||||
|
return this != NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@return the number of texels a texture buffer may address, or 0 if texture buffers are unsupported}
|
||||||
|
*/
|
||||||
|
int queryMaxTexels() {
|
||||||
|
return this.isSupported() ? LWJGL.glGetInteger(GL31.GL_MAX_TEXTURE_BUFFER_SIZE) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static TextureBufferFunctions pickBest(RenderDevice device) {
|
||||||
|
// Below GL 3.2 the terrain shaders are GLSL 1.20, which can only sample texture buffers through EXT_gpu_shader4
|
||||||
|
if (!LWJGL.isOpenGLVersionSupported(3, 2) && !LWJGL.isExtensionSupported(GLExtension.EXT_gpu_shader4)) {
|
||||||
|
return NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (LWJGL.isOpenGLVersionSupported(3, 1)) {
|
||||||
|
return CORE;
|
||||||
|
} else if (LWJGL.isExtensionSupported(GLExtension.ARB_texture_buffer_object)) {
|
||||||
|
return ARB;
|
||||||
|
} else if (LWJGL.isExtensionSupported(GLExtension.EXT_texture_buffer_object)) {
|
||||||
|
return EXT;
|
||||||
|
} else {
|
||||||
|
return NONE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package org.embeddedt.embeddium.impl.gl.texture;
|
||||||
|
|
||||||
|
import org.embeddedt.embeddium.impl.gl.GlObject;
|
||||||
|
import org.embeddedt.embeddium.impl.gl.buffer.GlBuffer;
|
||||||
|
import org.embeddedt.embeddium.impl.gl.functions.TextureBufferFunctions;
|
||||||
|
import org.taumc.celeritas.lwjgl.GL30;
|
||||||
|
import org.taumc.celeritas.lwjgl.GL31;
|
||||||
|
|
||||||
|
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A texture buffer exposing a buffer object to shaders as an array of 32-bit unsigned integers.
|
||||||
|
*/
|
||||||
|
public class GlBufferTexture extends GlObject {
|
||||||
|
private GlBuffer attachedBuffer;
|
||||||
|
|
||||||
|
public GlBufferTexture() {
|
||||||
|
this.setHandle(LWJGL.glGenTextures());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Binds this texture to the active texture unit, attaching the given buffer if it is not already attached. Buffers
|
||||||
|
* are compared by identity, because a deleted buffer's name may be reused by the buffer that replaces it.
|
||||||
|
*/
|
||||||
|
public void bind(TextureBufferFunctions functions, GlBuffer buffer) {
|
||||||
|
LWJGL.glBindTexture(GL31.GL_TEXTURE_BUFFER, this.handle());
|
||||||
|
|
||||||
|
if (this.attachedBuffer != buffer) {
|
||||||
|
functions.texBuffer(GL31.GL_TEXTURE_BUFFER, GL30.GL_R32UI, buffer);
|
||||||
|
this.attachedBuffer = buffer;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void destroyInternal() {
|
||||||
|
LWJGL.glDeleteTextures(this.handle());
|
||||||
|
this.attachedBuffer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
+57
-1
@@ -3,6 +3,7 @@ package org.embeddedt.embeddium.impl.render.chunk;
|
|||||||
import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap;
|
import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap;
|
||||||
import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap;
|
import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap;
|
||||||
import org.embeddedt.embeddium.impl.gl.array.GlVertexArray;
|
import org.embeddedt.embeddium.impl.gl.array.GlVertexArray;
|
||||||
|
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeFormat;
|
||||||
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
||||||
import org.embeddedt.embeddium.impl.gl.debug.GLDebug;
|
import org.embeddedt.embeddium.impl.gl.debug.GLDebug;
|
||||||
import org.embeddedt.embeddium.impl.gl.device.CommandList;
|
import org.embeddedt.embeddium.impl.gl.device.CommandList;
|
||||||
@@ -16,8 +17,15 @@ import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList;
|
|||||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.BatchAssembler;
|
import org.embeddedt.embeddium.impl.render.chunk.multidraw.BatchAssembler;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
|
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface;
|
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderTextureSlot;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexLayout;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchMode;
|
||||||
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
|
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
|
||||||
|
import org.taumc.celeritas.lwjgl.GL13;
|
||||||
|
|
||||||
|
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
|
||||||
|
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
|
|
||||||
public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
|
public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
|
||||||
@@ -25,6 +33,20 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
|
|||||||
|
|
||||||
private final BatchAssembler.TessellationProvider tessellationProvider = this::prepareTessellation;
|
private final BatchAssembler.TessellationProvider tessellationProvider = this::prepareTessellation;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The texture unit that pulled passes read vertex data from. Loaders bind their own textures to low units, so this
|
||||||
|
* stays clear of them. Shader pack programs reserve it when they pull vertex data.
|
||||||
|
*/
|
||||||
|
public static final int VERTEX_DATA_TEXTURE_UNIT = 15;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stands in for vertex attributes in pulled passes. Compatibility profiles leave a draw undefined when attribute
|
||||||
|
* array 0 is disabled, and pulled shaders don't declare any attributes.
|
||||||
|
*/
|
||||||
|
private static final GlVertexFormat PLACEHOLDER_ATTRIBUTE_FORMAT = GlVertexFormat.builder(4)
|
||||||
|
.addElement("celeritas_Placeholder", 0, GlVertexAttributeFormat.UNSIGNED_BYTE, 4, true, false)
|
||||||
|
.build();
|
||||||
|
|
||||||
private TerrainRenderPass currentRenderPass;
|
private TerrainRenderPass currentRenderPass;
|
||||||
private GlVertexFormat currentVertexFormat;
|
private GlVertexFormat currentVertexFormat;
|
||||||
|
|
||||||
@@ -77,10 +99,24 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
|
|||||||
Iterator<ChunkRenderList> iterator = renderLists.iterator(renderPass.isReverseOrder());
|
Iterator<ChunkRenderList> iterator = renderLists.iterator(renderPass.isReverseOrder());
|
||||||
|
|
||||||
this.currentRenderPass = renderPass;
|
this.currentRenderPass = renderPass;
|
||||||
this.currentVertexFormat = this.renderPassConfiguration.getVertexTypeForPass(this.currentRenderPass).getVertexFormat();
|
|
||||||
|
boolean pulled = renderPass.vertexFetchMode() == VertexFetchMode.PULLED;
|
||||||
|
|
||||||
|
int previousActiveTexture = 0;
|
||||||
|
|
||||||
|
if (pulled) {
|
||||||
|
this.currentVertexFormat = PLACEHOLDER_ATTRIBUTE_FORMAT;
|
||||||
|
previousActiveTexture = this.activateTextureUnit(GL13.GL_TEXTURE0 + VERTEX_DATA_TEXTURE_UNIT);
|
||||||
|
} else {
|
||||||
|
this.currentVertexFormat = ChunkVertexLayout.requireAttributes(renderPass.vertexType().getLayout());
|
||||||
|
}
|
||||||
|
|
||||||
this.configureShaderInterface(shader);
|
this.configureShaderInterface(shader);
|
||||||
|
|
||||||
|
if (pulled) {
|
||||||
|
shader.setTextureSlot(ChunkShaderTextureSlot.VERTEX_DATA, VERTEX_DATA_TEXTURE_UNIT);
|
||||||
|
}
|
||||||
|
|
||||||
long timestamp = System.nanoTime();
|
long timestamp = System.nanoTime();
|
||||||
|
|
||||||
useBlockFaceCulling = useBlockFaceCulling && !renderPass.isSorted();
|
useBlockFaceCulling = useBlockFaceCulling && !renderPass.isSorted();
|
||||||
@@ -117,12 +153,20 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
|
|||||||
.ensureCapacity(commandList, batch.getIndexBufferSize());
|
.ensureCapacity(commandList, batch.getIndexBufferSize());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (pulled) {
|
||||||
|
region.getResources().bindVertexDataTexture(this.device.getDeviceFunctions());
|
||||||
|
}
|
||||||
|
|
||||||
setModelMatrixUniforms(shader, region, camera);
|
setModelMatrixUniforms(shader, region, camera);
|
||||||
shader.setSectionAges(timestamp, region.getSectionLoadTimes());
|
shader.setSectionAges(timestamp, region.getSectionLoadTimes());
|
||||||
batch.execute(commandList, cached.getTessellation(), primitiveType);
|
batch.execute(commandList, cached.getTessellation(), primitiveType);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (pulled) {
|
||||||
|
this.activateTextureUnit(previousActiveTexture);
|
||||||
|
}
|
||||||
|
|
||||||
this.currentVertexFormat = null;
|
this.currentVertexFormat = null;
|
||||||
this.currentRenderPass = null;
|
this.currentRenderPass = null;
|
||||||
|
|
||||||
@@ -132,6 +176,18 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
|
|||||||
this.end(renderPass);
|
this.end(renderPass);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Makes the given texture unit active. Platforms whose renderer caches the active unit must update that cache.
|
||||||
|
*
|
||||||
|
* @param unit the unit, as {@code GL_TEXTURE0 + n}
|
||||||
|
* @return the unit that was active before, in the same form
|
||||||
|
*/
|
||||||
|
protected int activateTextureUnit(int unit) {
|
||||||
|
LWJGL.glActiveTexture(unit);
|
||||||
|
// TODO: don't assume unit 0 was active before the pass
|
||||||
|
return GL13.GL_TEXTURE0;
|
||||||
|
}
|
||||||
|
|
||||||
private static void setModelMatrixUniforms(ChunkShaderInterface shader, RenderRegion region, CameraTransform camera) {
|
private static void setModelMatrixUniforms(ChunkShaderInterface shader, RenderRegion region, CameraTransform camera) {
|
||||||
float x = getCameraTranslation(region.getOriginX(), camera.intX, camera.fracX);
|
float x = getCameraTranslation(region.getOriginX(), camera.intX, camera.fracX);
|
||||||
float y = getCameraTranslation(region.getOriginY(), camera.intY, camera.fracY);
|
float y = getCameraTranslation(region.getOriginY(), camera.intY, camera.fracY);
|
||||||
|
|||||||
+5
@@ -54,6 +54,7 @@ import java.util.concurrent.locks.LockSupport;
|
|||||||
import java.util.function.BiFunction;
|
import java.util.function.BiFunction;
|
||||||
import java.util.function.BooleanSupplier;
|
import java.util.function.BooleanSupplier;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
public abstract class RenderSectionManager {
|
public abstract class RenderSectionManager {
|
||||||
/**
|
/**
|
||||||
@@ -1130,6 +1131,10 @@ public abstract class RenderSectionManager {
|
|||||||
|
|
||||||
list.add(String.format("G: %d/%d, I: %d/%d MiB (%d buffers)", MathUtil.toMib(deviceUsed), MathUtil.toMib(deviceAllocated), MathUtil.toMib(indexUsed), MathUtil.toMib(indexAllocated), count));
|
list.add(String.format("G: %d/%d, I: %d/%d MiB (%d buffers)", MathUtil.toMib(deviceUsed), MathUtil.toMib(deviceAllocated), MathUtil.toMib(indexUsed), MathUtil.toMib(indexAllocated), count));
|
||||||
list.add(String.format("Transfer Queue: %s", this.regions.getStagingBuffer().toString()));
|
list.add(String.format("Transfer Queue: %s", this.regions.getStagingBuffer().toString()));
|
||||||
|
list.add("Vertex: " + this.renderPassConfiguration.getAllKnownRenderPasses()
|
||||||
|
.map(pass -> pass.vertexType().getClass().getSimpleName() + " (" + pass.vertexFetchMode().name().toLowerCase(Locale.ROOT) + ")")
|
||||||
|
.distinct()
|
||||||
|
.collect(Collectors.joining(", ")));
|
||||||
|
|
||||||
var rebuildLists = this.getCurrentRenderListManager().getRebuildLists();
|
var rebuildLists = this.getCurrentRenderListManager().getRebuildLists();
|
||||||
|
|
||||||
|
|||||||
+11
-3
@@ -11,6 +11,9 @@ import org.embeddedt.embeddium.impl.render.chunk.fog.FogService;
|
|||||||
import org.embeddedt.embeddium.impl.render.chunk.shader.*;
|
import org.embeddedt.embeddium.impl.render.chunk.shader.*;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexLayout;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchGenerator;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchMode;
|
||||||
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
|
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
@@ -61,22 +64,27 @@ public abstract class ShaderChunkRenderer implements ChunkRenderer {
|
|||||||
|
|
||||||
protected GlProgram<ChunkShaderInterface> createShader(String path, ChunkShaderOptions options) {
|
protected GlProgram<ChunkShaderInterface> createShader(String path, ChunkShaderOptions options) {
|
||||||
ShaderConstants constants = options.constants();
|
ShaderConstants constants = options.constants();
|
||||||
|
var pass = options.pass();
|
||||||
|
var generatedSources = VertexFetchGenerator.sources(pass.vertexType().getLayout(),
|
||||||
|
pass.primitiveType().getVerticesPerPrimitive(), pass.vertexFetchMode(), this.enableLegacyGLPatches);
|
||||||
|
|
||||||
List<GlShader> loadedShaders = new ArrayList<>();
|
List<GlShader> loadedShaders = new ArrayList<>();
|
||||||
|
|
||||||
loadedShaders.add(ShaderLoader.loadShader(ShaderType.VERTEX,
|
loadedShaders.add(ShaderLoader.loadShader(ShaderType.VERTEX,
|
||||||
"sodium:" + path + ".vsh", constants));
|
"sodium:" + path + ".vsh", constants, generatedSources));
|
||||||
|
|
||||||
loadedShaders.add(ShaderLoader.loadShader(ShaderType.FRAGMENT,
|
loadedShaders.add(ShaderLoader.loadShader(ShaderType.FRAGMENT,
|
||||||
"sodium:" + path + ".fsh", constants));
|
"sodium:" + path + ".fsh", constants, generatedSources));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
var builder = GlProgram.builder("sodium:chunk_shader");
|
var builder = GlProgram.builder("sodium:chunk_shader");
|
||||||
loadedShaders.forEach(builder::attachShader);
|
loadedShaders.forEach(builder::attachShader);
|
||||||
|
if (pass.vertexFetchMode() == VertexFetchMode.ATTRIBUTES) {
|
||||||
int i = 0;
|
int i = 0;
|
||||||
for (var attr : options.pass().vertexType().getVertexFormat().getAttributes()) {
|
for (var attr : ChunkVertexLayout.requireAttributes(pass.vertexType().getLayout()).getAttributes()) {
|
||||||
builder.bindAttribute(attr.getName(), i++);
|
builder.bindAttribute(attr.getName(), i++);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if (!this.enableLegacyGLPatches) {
|
if (!this.enableLegacyGLPatches) {
|
||||||
builder.bindFragmentData("fragColor", ChunkShaderBindingPoints.FRAG_COLOR);
|
builder.bindFragmentData("fragColor", ChunkShaderBindingPoints.FRAG_COLOR);
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -56,7 +56,7 @@ public final class ChunkBuildBuffers {
|
|||||||
|
|
||||||
private ChunkModelBuilder createBuilder(TerrainRenderPass pass) {
|
private ChunkModelBuilder createBuilder(TerrainRenderPass pass) {
|
||||||
var vertexType = this.renderPassConfiguration.getVertexTypeForPass(pass);
|
var vertexType = this.renderPassConfiguration.getVertexTypeForPass(pass);
|
||||||
var builder = new BakedChunkModelBuilder(vertexType.createEncoder(), vertexType.getVertexFormat().getStride(), pass);
|
var builder = new BakedChunkModelBuilder(vertexType.createEncoder(), pass);
|
||||||
Objects.requireNonNull(renderData, "Buffers have not been started");
|
Objects.requireNonNull(renderData, "Buffers have not been started");
|
||||||
builder.begin(renderData, sectionIndex);
|
builder.begin(renderData, sectionIndex);
|
||||||
this.builders.put(pass, builder);
|
this.builders.put(pass, builder);
|
||||||
@@ -112,7 +112,8 @@ public final class ChunkBuildBuffers {
|
|||||||
var vertexType = renderPassConfiguration.getVertexTypeForPass(pass);
|
var vertexType = renderPassConfiguration.getVertexTypeForPass(pass);
|
||||||
var primitiveType = renderPassConfiguration.getPrimitiveTypeForPass(pass);
|
var primitiveType = renderPassConfiguration.getPrimitiveTypeForPass(pass);
|
||||||
|
|
||||||
var mergedBuffer = new NativeBuffer(vertexCount * vertexType.getVertexFormat().getStride());
|
int numPrimitives = vertexCount / primitiveType.getVerticesPerPrimitive();
|
||||||
|
var mergedBuffer = new NativeBuffer(numPrimitives * vertexType.getLayout().bytesPerPrimitive(primitiveType));
|
||||||
var mergedBufferBuilder = mergedBuffer.getDirectBuffer();
|
var mergedBufferBuilder = mergedBuffer.getDirectBuffer();
|
||||||
|
|
||||||
for (var buffer : vertexBuffers) {
|
for (var buffer : vertexBuffers) {
|
||||||
@@ -124,7 +125,6 @@ public final class ChunkBuildBuffers {
|
|||||||
NativeBuffer mergedIndexBuffer;
|
NativeBuffer mergedIndexBuffer;
|
||||||
|
|
||||||
if (pass.isSorted()) {
|
if (pass.isSorted()) {
|
||||||
int numPrimitives = vertexCount / primitiveType.getVerticesPerPrimitive();
|
|
||||||
// Generate the canonical index buffer
|
// Generate the canonical index buffer
|
||||||
mergedIndexBuffer = new NativeBuffer(primitiveType.getIndexBufferSize(numPrimitives));
|
mergedIndexBuffer = new NativeBuffer(primitiveType.getIndexBufferSize(numPrimitives));
|
||||||
|
|
||||||
|
|||||||
+5
-2
@@ -17,11 +17,14 @@ public class BakedChunkModelBuilder implements ChunkModelBuilder {
|
|||||||
|
|
||||||
private BuiltRenderSectionData renderData;
|
private BuiltRenderSectionData renderData;
|
||||||
|
|
||||||
public BakedChunkModelBuilder(ChunkVertexEncoder encoder, int stride, TerrainRenderPass pass) {
|
public BakedChunkModelBuilder(ChunkVertexEncoder encoder, TerrainRenderPass pass) {
|
||||||
var vertexBuffers = new ChunkMeshBufferBuilder[ModelQuadFacing.COUNT];
|
var vertexBuffers = new ChunkMeshBufferBuilder[ModelQuadFacing.COUNT];
|
||||||
|
var primitiveType = pass.primitiveType();
|
||||||
|
int bytesPerPrimitive = pass.vertexType().getLayout().bytesPerPrimitive(primitiveType);
|
||||||
|
|
||||||
for (int facing = 0; facing < ModelQuadFacing.COUNT; facing++) {
|
for (int facing = 0; facing < ModelQuadFacing.COUNT; facing++) {
|
||||||
vertexBuffers[facing] = new ChunkMeshBufferBuilder(encoder, stride, 64 * 1024, pass.isSorted() && facing == ModelQuadFacing.UNASSIGNED.ordinal());
|
vertexBuffers[facing] = new ChunkMeshBufferBuilder(encoder, bytesPerPrimitive, primitiveType.getVerticesPerPrimitive(),
|
||||||
|
64 * 1024, pass.isSorted() && facing == ModelQuadFacing.UNASSIGNED.ordinal());
|
||||||
}
|
}
|
||||||
|
|
||||||
this.encoder = encoder;
|
this.encoder = encoder;
|
||||||
|
|||||||
+31
-4
@@ -7,7 +7,9 @@ import org.embeddedt.embeddium.impl.gl.arena.GlBufferArena;
|
|||||||
import org.embeddedt.embeddium.impl.gl.arena.staging.StagingBuffer;
|
import org.embeddedt.embeddium.impl.gl.arena.staging.StagingBuffer;
|
||||||
import org.embeddedt.embeddium.impl.gl.buffer.GlBuffer;
|
import org.embeddedt.embeddium.impl.gl.buffer.GlBuffer;
|
||||||
import org.embeddedt.embeddium.impl.gl.device.CommandList;
|
import org.embeddedt.embeddium.impl.gl.device.CommandList;
|
||||||
|
import org.embeddedt.embeddium.impl.gl.functions.DeviceFunctions;
|
||||||
import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation;
|
import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation;
|
||||||
|
import org.embeddedt.embeddium.impl.gl.texture.GlBufferTexture;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
|
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
|
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataStorage;
|
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataStorage;
|
||||||
@@ -162,15 +164,17 @@ public class RenderRegion {
|
|||||||
var storage = this.sectionRenderData.get(pass);
|
var storage = this.sectionRenderData.get(pass);
|
||||||
|
|
||||||
if (storage == null) {
|
if (storage == null) {
|
||||||
int stride = renderPassConfiguration.getVertexTypeForPass(pass).getVertexFormat().getStride();
|
var primitiveType = renderPassConfiguration.getPrimitiveTypeForPass(pass);
|
||||||
|
int bytesPerPrimitive = renderPassConfiguration.getVertexTypeForPass(pass).getLayout().bytesPerPrimitive(primitiveType);
|
||||||
|
|
||||||
if (this.commonVertexStride % stride != 0) {
|
if (this.commonVertexStride % bytesPerPrimitive != 0) {
|
||||||
throw new IllegalStateException("Pass " + pass + " uses a vertex stride of " + stride
|
throw new IllegalStateException("Pass " + pass + " uses " + bytesPerPrimitive + " bytes per primitive"
|
||||||
+ ", which does not divide the region's common vertex stride of " + this.commonVertexStride
|
+ ", which does not divide the region's common vertex stride of " + this.commonVertexStride
|
||||||
+ "; its vertex format was not declared by the render pass configuration");
|
+ "; its vertex format was not declared by the render pass configuration");
|
||||||
}
|
}
|
||||||
|
|
||||||
this.sectionRenderData.put(pass, storage = new SectionRenderDataStorage(renderPassConfiguration.getPrimitiveTypeForPass(pass), pass.isSorted(), this.commonVertexStride / stride));
|
int verticesPerArenaElement = (this.commonVertexStride / bytesPerPrimitive) * primitiveType.getVerticesPerPrimitive();
|
||||||
|
this.sectionRenderData.put(pass, storage = new SectionRenderDataStorage(primitiveType, pass.isSorted(), verticesPerArenaElement));
|
||||||
this.passSetUpdateCount++;
|
this.passSetUpdateCount++;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -307,6 +311,7 @@ public class RenderRegion {
|
|||||||
private final GlBufferArena geometryArena;
|
private final GlBufferArena geometryArena;
|
||||||
private final StagingBuffer stagingBuffer;
|
private final StagingBuffer stagingBuffer;
|
||||||
private GlBufferArena indexArena;
|
private GlBufferArena indexArena;
|
||||||
|
private GlBufferTexture vertexDataTexture;
|
||||||
private final Map<TerrainRenderPass.TessellationKey, GlTessellation> tessellations = new Object2ReferenceOpenHashMap<>();
|
private final Map<TerrainRenderPass.TessellationKey, GlTessellation> tessellations = new Object2ReferenceOpenHashMap<>();
|
||||||
|
|
||||||
public DeviceResources(CommandList commandList, StagingBuffer stagingBuffer, int commonVertexStride) {
|
public DeviceResources(CommandList commandList, StagingBuffer stagingBuffer, int commonVertexStride) {
|
||||||
@@ -338,6 +343,24 @@ public class RenderRegion {
|
|||||||
return this.geometryArena.getBufferObject();
|
return this.geometryArena.getBufferObject();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Binds a texture buffer over the geometry arena to the active texture unit, for passes that pull vertex data.
|
||||||
|
*/
|
||||||
|
public void bindVertexDataTexture(DeviceFunctions functions) {
|
||||||
|
long texels = this.geometryArena.getDeviceAllocatedMemoryL() / 4;
|
||||||
|
|
||||||
|
if (texels > functions.maxTextureBufferTexels()) {
|
||||||
|
throw new IllegalStateException("Geometry arena of " + texels + " texels exceeds the device's texture buffer limit of "
|
||||||
|
+ functions.maxTextureBufferTexels());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.vertexDataTexture == null) {
|
||||||
|
this.vertexDataTexture = new GlBufferTexture();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.vertexDataTexture.bind(functions.textureBufferFunctions(), this.geometryArena.getBufferObject());
|
||||||
|
}
|
||||||
|
|
||||||
public GlBuffer getIndexBuffer() {
|
public GlBuffer getIndexBuffer() {
|
||||||
if (this.indexArena == null) {
|
if (this.indexArena == null) {
|
||||||
throw new IllegalStateException("Attempted to retrieve index buffer for a non-indexed region");
|
throw new IllegalStateException("Attempted to retrieve index buffer for a non-indexed region");
|
||||||
@@ -347,6 +370,10 @@ public class RenderRegion {
|
|||||||
|
|
||||||
public void delete(CommandList commandList) {
|
public void delete(CommandList commandList) {
|
||||||
this.deleteTessellations(commandList);
|
this.deleteTessellations(commandList);
|
||||||
|
if (this.vertexDataTexture != null) {
|
||||||
|
this.vertexDataTexture.delete();
|
||||||
|
this.vertexDataTexture = null;
|
||||||
|
}
|
||||||
this.geometryArena.delete(commandList);
|
this.geometryArena.delete(commandList);
|
||||||
if (this.indexArena != null) {
|
if (this.indexArena != null) {
|
||||||
this.indexArena.delete(commandList);
|
this.indexArena.delete(commandList);
|
||||||
|
|||||||
+1
-1
@@ -45,7 +45,7 @@ public class RenderRegionManager {
|
|||||||
*/
|
*/
|
||||||
private static int computeCommonVertexStride(RenderPassConfiguration<?> renderPassConfiguration) {
|
private static int computeCommonVertexStride(RenderPassConfiguration<?> renderPassConfiguration) {
|
||||||
return renderPassConfiguration.getAllKnownRenderPasses()
|
return renderPassConfiguration.getAllKnownRenderPasses()
|
||||||
.mapToInt(pass -> pass.vertexType().getVertexFormat().getStride() * pass.primitiveType().getVerticesPerPrimitive())
|
.mapToInt(pass -> pass.vertexType().getLayout().bytesPerPrimitive(pass.primitiveType()))
|
||||||
.reduce(1, MathUtil::lcm);
|
.reduce(1, MathUtil::lcm);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+5
@@ -2,6 +2,7 @@ package org.embeddedt.embeddium.impl.render.chunk.shader;
|
|||||||
|
|
||||||
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
|
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchMode;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@@ -21,6 +22,10 @@ public record ChunkShaderOptions(List<ChunkShaderComponent.Factory<?>> component
|
|||||||
constants.add("CELERITAS_NO_LIGHTMAP");
|
constants.add("CELERITAS_NO_LIGHTMAP");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (this.pass.vertexFetchMode() == VertexFetchMode.PULLED) {
|
||||||
|
constants.add("USE_VERTEX_PULLING");
|
||||||
|
}
|
||||||
|
|
||||||
constants.addAll(pass.extraDefines());
|
constants.addAll(pass.extraDefines());
|
||||||
|
|
||||||
var vertexType = pass.vertexType();
|
var vertexType = pass.vertexType();
|
||||||
|
|||||||
+2
-1
@@ -2,7 +2,8 @@ package org.embeddedt.embeddium.impl.render.chunk.shader;
|
|||||||
|
|
||||||
public enum ChunkShaderTextureSlot {
|
public enum ChunkShaderTextureSlot {
|
||||||
BLOCK,
|
BLOCK,
|
||||||
LIGHT;
|
LIGHT,
|
||||||
|
VERTEX_DATA;
|
||||||
|
|
||||||
public static final ChunkShaderTextureSlot[] VALUES = ChunkShaderTextureSlot.values();
|
public static final ChunkShaderTextureSlot[] VALUES = ChunkShaderTextureSlot.values();
|
||||||
}
|
}
|
||||||
+5
@@ -8,6 +8,8 @@ import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix4f;
|
|||||||
import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType;
|
import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType;
|
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchGenerator;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchMode;
|
||||||
import org.joml.Matrix4fc;
|
import org.joml.Matrix4fc;
|
||||||
import org.taumc.celeritas.lwjgl.MemoryStack;
|
import org.taumc.celeritas.lwjgl.MemoryStack;
|
||||||
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
|
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
|
||||||
@@ -47,6 +49,9 @@ public class DefaultChunkShaderInterface implements ChunkShaderInterface {
|
|||||||
if (!options.pass().hasNoLightmap()) {
|
if (!options.pass().hasNoLightmap()) {
|
||||||
this.uniformTextures.put(ChunkShaderTextureSlot.LIGHT, context.bindUniform("u_LightTex", GlUniformInt::new));
|
this.uniformTextures.put(ChunkShaderTextureSlot.LIGHT, context.bindUniform("u_LightTex", GlUniformInt::new));
|
||||||
}
|
}
|
||||||
|
if (options.pass().vertexFetchMode() == VertexFetchMode.PULLED) {
|
||||||
|
this.uniformTextures.put(ChunkShaderTextureSlot.VERTEX_DATA, context.bindUniform(VertexFetchGenerator.VERTEX_DATA_SAMPLER, GlUniformInt::new));
|
||||||
|
}
|
||||||
|
|
||||||
this.components = options.components().stream().map(c -> c.create(context, environment)).toList();
|
this.components = options.components().stream().map(c -> c.create(context, environment)).toList();
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-3
@@ -5,10 +5,11 @@ import lombok.EqualsAndHashCode;
|
|||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Singular;
|
import lombok.Singular;
|
||||||
import lombok.experimental.Accessors;
|
import lombok.experimental.Accessors;
|
||||||
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType;
|
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
|
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexLayout;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchMode;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -56,8 +57,9 @@ public class TerrainRenderPass {
|
|||||||
|
|
||||||
private final @NotNull ChunkPrimitiveType primitiveType;
|
private final @NotNull ChunkPrimitiveType primitiveType;
|
||||||
private final @NotNull ChunkVertexType vertexType;
|
private final @NotNull ChunkVertexType vertexType;
|
||||||
|
private final @NotNull VertexFetchMode vertexFetchMode;
|
||||||
|
|
||||||
public record TessellationKey(GlVertexFormat vertexFormat, ChunkPrimitiveType primitiveType, boolean sorted) {}
|
public record TessellationKey(ChunkVertexLayout vertexLayout, VertexFetchMode vertexFetchMode, ChunkPrimitiveType primitiveType, boolean sorted) {}
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@EqualsAndHashCode.Exclude
|
@EqualsAndHashCode.Exclude
|
||||||
@@ -89,7 +91,8 @@ public class TerrainRenderPass {
|
|||||||
this.hasNoLightmap = hasNoLightmap;
|
this.hasNoLightmap = hasNoLightmap;
|
||||||
this.primitiveType = primitiveType;
|
this.primitiveType = primitiveType;
|
||||||
this.vertexType = vertexType;
|
this.vertexType = vertexType;
|
||||||
this.tessellationKey = new TessellationKey(vertexType.getVertexFormat(), primitiveType, useTranslucencySorting);
|
this.vertexFetchMode = VertexFetchMode.select(vertexType.getLayout());
|
||||||
|
this.tessellationKey = new TessellationKey(vertexType.getLayout(), this.vertexFetchMode, primitiveType, useTranslucencySorting);
|
||||||
this.extraDefines = Map.copyOf(extraDefines);
|
this.extraDefines = Map.copyOf(extraDefines);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,6 +128,10 @@ public class TerrainRenderPass {
|
|||||||
return this.vertexType;
|
return this.vertexType;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public VertexFetchMode vertexFetchMode() {
|
||||||
|
return this.vertexFetchMode;
|
||||||
|
}
|
||||||
|
|
||||||
public Map<String, String> extraDefines() {
|
public Map<String, String> extraDefines() {
|
||||||
return this.extraDefines;
|
return this.extraDefines;
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-12
@@ -10,7 +10,8 @@ import java.nio.ByteBuffer;
|
|||||||
|
|
||||||
public class ChunkMeshBufferBuilder {
|
public class ChunkMeshBufferBuilder {
|
||||||
private final ChunkVertexEncoder encoder;
|
private final ChunkVertexEncoder encoder;
|
||||||
private final int stride;
|
private final int bytesPerPrimitive;
|
||||||
|
private final int verticesPerPrimitive;
|
||||||
|
|
||||||
private final int initialCapacity;
|
private final int initialCapacity;
|
||||||
private final TranslucentQuadRecorder analyzer;
|
private final TranslucentQuadRecorder analyzer;
|
||||||
@@ -20,9 +21,10 @@ public class ChunkMeshBufferBuilder {
|
|||||||
private int capacity;
|
private int capacity;
|
||||||
private int sectionIndex;
|
private int sectionIndex;
|
||||||
|
|
||||||
public ChunkMeshBufferBuilder(ChunkVertexEncoder encoder, int stride, int initialCapacity, boolean collectSortState) {
|
public ChunkMeshBufferBuilder(ChunkVertexEncoder encoder, int bytesPerPrimitive, int verticesPerPrimitive, int initialCapacity, boolean collectSortState) {
|
||||||
this.encoder = encoder;
|
this.encoder = encoder;
|
||||||
this.stride = stride;
|
this.bytesPerPrimitive = bytesPerPrimitive;
|
||||||
|
this.verticesPerPrimitive = verticesPerPrimitive;
|
||||||
|
|
||||||
this.buffer = null;
|
this.buffer = null;
|
||||||
|
|
||||||
@@ -33,18 +35,21 @@ public class ChunkMeshBufferBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void push(ChunkVertexEncoder.Vertex[] vertices, Material material) {
|
public void push(ChunkVertexEncoder.Vertex[] vertices, Material material) {
|
||||||
|
if (vertices.length != this.verticesPerPrimitive) {
|
||||||
|
throw new IllegalArgumentException("Expected one primitive of " + this.verticesPerPrimitive + " vertices, got " + vertices.length);
|
||||||
|
}
|
||||||
|
|
||||||
if (this.encoder.supportsBilinearCorrection()) {
|
if (this.encoder.supportsBilinearCorrection()) {
|
||||||
postprocessVertices(vertices);
|
postprocessVertices(vertices);
|
||||||
}
|
}
|
||||||
|
|
||||||
var vertexStart = this.count * this.stride;
|
var primitiveStart = this.byteSize();
|
||||||
var vertexSize = vertices.length * this.stride;
|
|
||||||
|
|
||||||
if (vertexStart + vertexSize >= this.capacity) {
|
if (primitiveStart + this.bytesPerPrimitive >= this.capacity) {
|
||||||
this.grow(vertexSize);
|
this.grow(this.bytesPerPrimitive);
|
||||||
}
|
}
|
||||||
|
|
||||||
long ptr = LWJGL.memAddress(this.buffer, vertexStart);
|
long ptr = LWJGL.memAddress(this.buffer, primitiveStart);
|
||||||
|
|
||||||
if (this.analyzer != null) {
|
if (this.analyzer != null) {
|
||||||
for (ChunkVertexEncoder.Vertex vertex : vertices) {
|
for (ChunkVertexEncoder.Vertex vertex : vertices) {
|
||||||
@@ -52,9 +57,7 @@ public class ChunkMeshBufferBuilder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (ChunkVertexEncoder.Vertex vertex : vertices) {
|
this.encoder.writePrimitive(ptr, material, vertices, this.sectionIndex);
|
||||||
ptr = this.encoder.write(ptr, material, vertex, this.sectionIndex);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.count += vertices.length;
|
this.count += vertices.length;
|
||||||
}
|
}
|
||||||
@@ -137,10 +140,14 @@ public class ChunkMeshBufferBuilder {
|
|||||||
throw new IllegalStateException("No vertex data in buffer");
|
throw new IllegalStateException("No vertex data in buffer");
|
||||||
}
|
}
|
||||||
|
|
||||||
return LWJGL.memSlice(this.buffer, 0, this.stride * this.count);
|
return LWJGL.memSlice(this.buffer, 0, this.byteSize());
|
||||||
}
|
}
|
||||||
|
|
||||||
public int count() {
|
public int count() {
|
||||||
return this.count;
|
return this.count;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private int byteSize() {
|
||||||
|
return (this.count / this.verticesPerPrimitive) * this.bytesPerPrimitive;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+8
-1
@@ -2,8 +2,15 @@ package org.embeddedt.embeddium.impl.render.chunk.vertex.format;
|
|||||||
|
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
|
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
|
||||||
|
|
||||||
|
@FunctionalInterface
|
||||||
public interface ChunkVertexEncoder {
|
public interface ChunkVertexEncoder {
|
||||||
long write(long ptr, Material material, Vertex vertex, int sectionIndex);
|
/**
|
||||||
|
* Writes one primitive starting at {@code ptr}.
|
||||||
|
*
|
||||||
|
* @return the pointer just past the primitive, which is {@code ptr} plus the layout's
|
||||||
|
* {@link ChunkVertexLayout#bytesPerPrimitive bytesPerPrimitive}
|
||||||
|
*/
|
||||||
|
long writePrimitive(long ptr, Material material, Vertex[] vertices, int sectionIndex);
|
||||||
|
|
||||||
default boolean supportsBilinearCorrection() {
|
default boolean supportsBilinearCorrection() {
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
+99
@@ -0,0 +1,99 @@
|
|||||||
|
package org.embeddedt.embeddium.impl.render.chunk.vertex.format;
|
||||||
|
|
||||||
|
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttribute;
|
||||||
|
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType;
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Describes how a vertex type's data is laid out in the geometry buffer. Each primitive is stored as one record: an
|
||||||
|
* optional header holding per-primitive elements, followed by its vertices.
|
||||||
|
* <p>
|
||||||
|
* Only layouts without a header can be fetched through vertex attributes. Any layout can be pulled by the vertex
|
||||||
|
* shader, see {@link VertexFetchGenerator}.
|
||||||
|
*/
|
||||||
|
public record ChunkVertexLayout(GlVertexFormat vertex, @Nullable Header header) {
|
||||||
|
/**
|
||||||
|
* @param verticesPerRecord the number of vertices that follow each header
|
||||||
|
*/
|
||||||
|
public record Header(GlVertexFormat format, int verticesPerRecord) {
|
||||||
|
public Header {
|
||||||
|
Objects.requireNonNull(format);
|
||||||
|
|
||||||
|
if (verticesPerRecord <= 0) {
|
||||||
|
throw new IllegalArgumentException("Records must contain at least one vertex");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public ChunkVertexLayout {
|
||||||
|
Objects.requireNonNull(vertex);
|
||||||
|
validateWordAligned(vertex);
|
||||||
|
|
||||||
|
if (header != null) {
|
||||||
|
validateWordAligned(header.format());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ChunkVertexLayout of(GlVertexFormat vertex) {
|
||||||
|
return new ChunkVertexLayout(vertex, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ChunkVertexLayout withHeader(GlVertexFormat vertex, GlVertexFormat header, int verticesPerRecord) {
|
||||||
|
return new ChunkVertexLayout(vertex, new Header(header, verticesPerRecord));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pulled records are fetched as 32-bit words, so no component may straddle a word boundary.
|
||||||
|
*/
|
||||||
|
private static void validateWordAligned(GlVertexFormat format) {
|
||||||
|
if (format.getStride() % 4 != 0) {
|
||||||
|
throw new IllegalArgumentException("Stride of " + format + " is not a multiple of 4 bytes");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (GlVertexAttribute attribute : format.getAttributes()) {
|
||||||
|
int componentSize = attribute.getFormat().size();
|
||||||
|
|
||||||
|
if (attribute.getPointer() % componentSize != 0) {
|
||||||
|
throw new IllegalArgumentException("Attribute " + attribute.getName() + " at offset " + attribute.getPointer()
|
||||||
|
+ " is not aligned to its " + componentSize + "-byte components");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@return the number of bytes one primitive of the given type occupies in the geometry buffer}
|
||||||
|
*/
|
||||||
|
public int bytesPerPrimitive(ChunkPrimitiveType primitiveType) {
|
||||||
|
int vertices = primitiveType.getVerticesPerPrimitive();
|
||||||
|
|
||||||
|
if (this.header == null) {
|
||||||
|
return this.vertex.getStride() * vertices;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vertices != this.header.verticesPerRecord()) {
|
||||||
|
throw new IllegalArgumentException("Layout holds " + this.header.verticesPerRecord() + " vertices per record, but "
|
||||||
|
+ primitiveType + " has " + vertices);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.header.format().getStride() + this.vertex.getStride() * vertices;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean supportsAttributeFetch() {
|
||||||
|
return this.header == null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@return the attribute format of the given layout}
|
||||||
|
* @throws UnsupportedOperationException if the layout cannot be fetched through vertex attributes
|
||||||
|
*/
|
||||||
|
public static GlVertexFormat requireAttributes(ChunkVertexLayout layout) {
|
||||||
|
if (layout.supportsAttributeFetch()) {
|
||||||
|
return layout.vertex();
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new UnsupportedOperationException("Layout must be pulled by the vertex shader: " + layout);
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-2
@@ -1,6 +1,5 @@
|
|||||||
package org.embeddedt.embeddium.impl.render.chunk.vertex.format;
|
package org.embeddedt.embeddium.impl.render.chunk.vertex.format;
|
||||||
|
|
||||||
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
|
||||||
import org.jetbrains.annotations.MustBeInvokedByOverriders;
|
import org.jetbrains.annotations.MustBeInvokedByOverriders;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
@@ -22,7 +21,7 @@ public interface ChunkVertexType {
|
|||||||
*/
|
*/
|
||||||
float getTextureScale();
|
float getTextureScale();
|
||||||
|
|
||||||
GlVertexFormat getVertexFormat();
|
ChunkVertexLayout getLayout();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@return a newly constructed instance of a vertex encoder for the given vertex type}
|
* {@return a newly constructed instance of a vertex encoder for the given vertex type}
|
||||||
|
|||||||
+389
@@ -0,0 +1,389 @@
|
|||||||
|
package org.embeddedt.embeddium.impl.render.chunk.vertex.format;
|
||||||
|
|
||||||
|
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttribute;
|
||||||
|
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeFormat;
|
||||||
|
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.TreeSet;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates the GLSL that declares every element of a {@link ChunkVertexLayout} as a vertex shader input.
|
||||||
|
* <p>
|
||||||
|
* With attribute fetch, the elements are declared as {@code in} variables. When pulled, they are declared as globals of the
|
||||||
|
* same names and types, and {@code _vert_fetch()} fills them from the {@link #VERTEX_DATA_SAMPLER} texture buffer,
|
||||||
|
* converting each component the way attribute fetch would for the same {@link GlVertexAttribute}.
|
||||||
|
* <p>
|
||||||
|
* Callers may declare an element with a different type than its own, as a shader may declare an attribute. Missing
|
||||||
|
* components are taken from {@code (0, 0, 0, 1)}, extra ones are dropped, and components are cast if the scalar types
|
||||||
|
* differ.
|
||||||
|
*/
|
||||||
|
public final class VertexFetchGenerator {
|
||||||
|
public static final String IMPORT_NAME = "sodium:generated/vertex_fetch.glsl";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The {@code usamplerBuffer} that pulled vertex data is read from.
|
||||||
|
*/
|
||||||
|
public static final String VERTEX_DATA_SAMPLER = "u_VertexData";
|
||||||
|
|
||||||
|
public enum Scope {
|
||||||
|
HEADER,
|
||||||
|
VERTEX
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum Conversion {
|
||||||
|
UINT,
|
||||||
|
SINT,
|
||||||
|
FLOAT_BITS,
|
||||||
|
UNORM,
|
||||||
|
SNORM,
|
||||||
|
UINT_TO_FLOAT,
|
||||||
|
SINT_TO_FLOAT
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One component of an element, held in bits {@code [shift, shift + bits)} of a 32-bit word. The word index is
|
||||||
|
* relative to the start of the header or vertex the component belongs to.
|
||||||
|
*/
|
||||||
|
public record Component(Scope scope, int word, int shift, int bits, Conversion conversion) {}
|
||||||
|
|
||||||
|
public record Element(String name, GlslType type, List<Component> components) {}
|
||||||
|
|
||||||
|
public enum ScalarType {
|
||||||
|
FLOAT("float", "", "0.0", "1.0"),
|
||||||
|
INT("int", "i", "0", "1"),
|
||||||
|
UINT("uint", "u", "0u", "1u");
|
||||||
|
|
||||||
|
private final String name;
|
||||||
|
private final String vectorPrefix;
|
||||||
|
private final String zero;
|
||||||
|
private final String one;
|
||||||
|
|
||||||
|
ScalarType(String name, String vectorPrefix, String zero, String one) {
|
||||||
|
this.name = name;
|
||||||
|
this.vectorPrefix = vectorPrefix;
|
||||||
|
this.zero = zero;
|
||||||
|
this.one = one;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A scalar or vector type, the only kinds a vertex input can have here.
|
||||||
|
*/
|
||||||
|
public record GlslType(ScalarType scalar, int count) {
|
||||||
|
public GlslType {
|
||||||
|
if (count < 1 || count > 4) {
|
||||||
|
throw new IllegalArgumentException("Vector types have 1 to 4 components, not " + count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static GlslType parse(String name) {
|
||||||
|
for (ScalarType scalar : ScalarType.values()) {
|
||||||
|
if (name.equals(scalar.name)) {
|
||||||
|
return new GlslType(scalar, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
String prefix = scalar.vectorPrefix + "vec";
|
||||||
|
|
||||||
|
if (name.length() == prefix.length() + 1 && name.startsWith(prefix)) {
|
||||||
|
int count = name.charAt(prefix.length()) - '0';
|
||||||
|
|
||||||
|
if (count >= 2 && count <= 4) {
|
||||||
|
return new GlslType(scalar, count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new IllegalArgumentException("Unsupported vertex input type " + name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@return GLSL converting a value of type {@code from} to this type, the way attribute fetch would}
|
||||||
|
*/
|
||||||
|
public String adapt(String expression, GlslType from) {
|
||||||
|
if (this.equals(from)) {
|
||||||
|
return expression;
|
||||||
|
}
|
||||||
|
|
||||||
|
var out = new StringBuilder(this.toString()).append('(').append(expression);
|
||||||
|
|
||||||
|
for (int i = from.count; i < this.count; i++) {
|
||||||
|
out.append(", ").append(i == 3 ? this.scalar.one : this.scalar.zero);
|
||||||
|
}
|
||||||
|
|
||||||
|
return out.append(')').toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return this.count == 1 ? this.scalar.name : this.scalar.vectorPrefix + "vec" + this.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private VertexFetchGenerator() {}
|
||||||
|
|
||||||
|
public static Map<String, String> sources(ChunkVertexLayout layout, int verticesPerPrimitive, VertexFetchMode mode, boolean legacyGlsl) {
|
||||||
|
return sources(layout, verticesPerPrimitive, mode, legacyGlsl, Map.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param declaredTypes GLSL types to declare elements with instead of their own, by element name
|
||||||
|
*/
|
||||||
|
public static Map<String, String> sources(ChunkVertexLayout layout, int verticesPerPrimitive, VertexFetchMode mode, boolean legacyGlsl,
|
||||||
|
Map<String, GlslType> declaredTypes) {
|
||||||
|
return Map.of(IMPORT_NAME, generate(layout, verticesPerPrimitive, mode, legacyGlsl, declaredTypes));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<Element> plan(ChunkVertexLayout layout) {
|
||||||
|
var elements = new ArrayList<Element>();
|
||||||
|
|
||||||
|
if (layout.header() != null) {
|
||||||
|
addElements(elements, layout.header().format(), Scope.HEADER);
|
||||||
|
}
|
||||||
|
|
||||||
|
addElements(elements, layout.vertex(), Scope.VERTEX);
|
||||||
|
|
||||||
|
return elements;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void addElements(List<Element> elements, GlVertexFormat format, Scope scope) {
|
||||||
|
for (GlVertexAttribute attribute : format.getAttributes()) {
|
||||||
|
Conversion conversion = conversionOf(attribute);
|
||||||
|
int componentSize = attribute.getFormat().size();
|
||||||
|
var components = new ArrayList<Component>(attribute.getCount());
|
||||||
|
|
||||||
|
for (int i = 0; i < attribute.getCount(); i++) {
|
||||||
|
int offset = attribute.getPointer() + (i * componentSize);
|
||||||
|
components.add(new Component(scope, offset / 4, (offset % 4) * 8, componentSize * 8, conversion));
|
||||||
|
}
|
||||||
|
|
||||||
|
elements.add(new Element(attribute.getName(), new GlslType(scalarType(conversion), attribute.getCount()), components));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Conversion conversionOf(GlVertexAttribute attribute) {
|
||||||
|
GlVertexAttributeFormat format = attribute.getFormat();
|
||||||
|
|
||||||
|
if (format.equals(GlVertexAttributeFormat.FLOAT)) {
|
||||||
|
if (attribute.isIntType()) {
|
||||||
|
throw new IllegalArgumentException("Float attribute " + attribute.getName() + " cannot be an integer type");
|
||||||
|
}
|
||||||
|
|
||||||
|
return Conversion.FLOAT_BITS;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean signed = format.equals(GlVertexAttributeFormat.BYTE) || format.equals(GlVertexAttributeFormat.SHORT);
|
||||||
|
|
||||||
|
if (attribute.isIntType()) {
|
||||||
|
return signed ? Conversion.SINT : Conversion.UINT;
|
||||||
|
} else if (attribute.isNormalized()) {
|
||||||
|
return signed ? Conversion.SNORM : Conversion.UNORM;
|
||||||
|
} else {
|
||||||
|
return signed ? Conversion.SINT_TO_FLOAT : Conversion.UINT_TO_FLOAT;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ScalarType scalarType(Conversion conversion) {
|
||||||
|
return switch (conversion) {
|
||||||
|
case UINT -> ScalarType.UINT;
|
||||||
|
case SINT -> ScalarType.INT;
|
||||||
|
default -> ScalarType.FLOAT;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String generate(ChunkVertexLayout layout, int verticesPerPrimitive, VertexFetchMode mode, boolean legacyGlsl) {
|
||||||
|
return generate(layout, verticesPerPrimitive, mode, legacyGlsl, Map.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String generate(ChunkVertexLayout layout, int verticesPerPrimitive, VertexFetchMode mode, boolean legacyGlsl,
|
||||||
|
Map<String, GlslType> declaredTypes) {
|
||||||
|
if (mode == VertexFetchMode.ATTRIBUTES && !layout.supportsAttributeFetch()) {
|
||||||
|
throw new IllegalArgumentException("Layout cannot be fetched through vertex attributes: " + layout);
|
||||||
|
}
|
||||||
|
|
||||||
|
int verticesPerRecord = layout.header() != null ? layout.header().verticesPerRecord() : verticesPerPrimitive;
|
||||||
|
List<Element> elements = plan(layout);
|
||||||
|
var out = new StringBuilder();
|
||||||
|
|
||||||
|
for (Element element : elements) {
|
||||||
|
out.append("#define VERT_HAS_").append(element.name()).append('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
out.append('\n');
|
||||||
|
|
||||||
|
String storage = mode == VertexFetchMode.ATTRIBUTES ? "in " : "";
|
||||||
|
|
||||||
|
for (Element element : elements) {
|
||||||
|
out.append(storage).append(declaredType(element, declaredTypes)).append(' ').append(element.name()).append(";\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
out.append("\nint _vert_corner;\n\n");
|
||||||
|
|
||||||
|
if (mode == VertexFetchMode.ATTRIBUTES) {
|
||||||
|
out.append("void _vert_fetch() {\n");
|
||||||
|
out.append(" _vert_corner = gl_VertexID % ").append(verticesPerRecord).append(";\n");
|
||||||
|
out.append("}\n");
|
||||||
|
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean needsFloatHelper = legacyGlsl && elements.stream()
|
||||||
|
.flatMap(e -> e.components().stream())
|
||||||
|
.anyMatch(c -> c.conversion() == Conversion.FLOAT_BITS);
|
||||||
|
|
||||||
|
out.append("#define VERT_CAN_FETCH_CORNERS\n\n");
|
||||||
|
out.append("uniform usamplerBuffer ").append(VERTEX_DATA_SAMPLER).append(";\n\n");
|
||||||
|
|
||||||
|
if (needsFloatHelper) {
|
||||||
|
appendFloatHelper(out);
|
||||||
|
}
|
||||||
|
|
||||||
|
String fetch = legacyGlsl ? "texelFetchBuffer" : "texelFetch";
|
||||||
|
int vertexWords = layout.vertex().getStride() / 4;
|
||||||
|
int headerWords = layout.header() != null ? layout.header().format().getStride() / 4 : 0;
|
||||||
|
int recordWords = headerWords + (verticesPerRecord * vertexWords);
|
||||||
|
|
||||||
|
List<Element> headerElements = elements.stream().filter(e -> e.components().get(0).scope() == Scope.HEADER).toList();
|
||||||
|
List<Element> vertexElements = elements.stream().filter(e -> e.components().get(0).scope() == Scope.VERTEX).toList();
|
||||||
|
|
||||||
|
// Holds one corner's per-vertex elements as their own types, so other corners of the primitive can be read too
|
||||||
|
out.append("struct _VertInputs {\n");
|
||||||
|
|
||||||
|
for (Element element : vertexElements) {
|
||||||
|
out.append(" ").append(element.type()).append(' ').append(element.name()).append(";\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
out.append("};\n\n");
|
||||||
|
|
||||||
|
out.append("_VertInputs _vert_fetch_corner(int corner) {\n");
|
||||||
|
out.append(" int _vf_vertex = ((gl_VertexID / ").append(verticesPerRecord).append(") * ").append(recordWords).append(") + ");
|
||||||
|
|
||||||
|
if (headerWords != 0) {
|
||||||
|
out.append(headerWords).append(" + ");
|
||||||
|
}
|
||||||
|
|
||||||
|
out.append("(corner * ").append(vertexWords).append(");\n");
|
||||||
|
appendWordFetches(out, vertexElements, "_vf_vertex", fetch);
|
||||||
|
out.append(" _VertInputs v;\n");
|
||||||
|
|
||||||
|
for (Element element : vertexElements) {
|
||||||
|
out.append(" v.").append(element.name()).append(" = ").append(naturalExpression(element, legacyGlsl)).append(";\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
out.append(" return v;\n");
|
||||||
|
out.append("}\n\n");
|
||||||
|
|
||||||
|
out.append("void _vert_fetch() {\n");
|
||||||
|
out.append(" _vert_corner = gl_VertexID % ").append(verticesPerRecord).append(";\n");
|
||||||
|
|
||||||
|
if (!headerElements.isEmpty()) {
|
||||||
|
out.append(" int _vf_record = (gl_VertexID / ").append(verticesPerRecord).append(") * ").append(recordWords).append(";\n");
|
||||||
|
appendWordFetches(out, headerElements, "_vf_record", fetch);
|
||||||
|
|
||||||
|
for (Element element : headerElements) {
|
||||||
|
out.append(" ").append(element.name()).append(" = ")
|
||||||
|
.append(declaredType(element, declaredTypes).adapt(naturalExpression(element, legacyGlsl), element.type())).append(";\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
out.append(" _VertInputs v = _vert_fetch_corner(_vert_corner);\n");
|
||||||
|
|
||||||
|
for (Element element : vertexElements) {
|
||||||
|
out.append(" ").append(element.name()).append(" = ")
|
||||||
|
.append(declaredType(element, declaredTypes).adapt("v." + element.name(), element.type())).append(";\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
out.append("}\n");
|
||||||
|
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void appendWordFetches(StringBuilder out, List<Element> elements, String base, String fetch) {
|
||||||
|
var words = new TreeSet<Integer>();
|
||||||
|
|
||||||
|
for (Element element : elements) {
|
||||||
|
for (Component component : element.components()) {
|
||||||
|
words.add(component.word());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int word : words) {
|
||||||
|
Scope scope = elements.get(0).components().get(0).scope();
|
||||||
|
out.append(" uint ").append(wordName(scope, word)).append(" = ").append(fetch).append('(').append(VERTEX_DATA_SAMPLER)
|
||||||
|
.append(", ").append(base).append(" + ").append(word).append(").r;\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String naturalExpression(Element element, boolean legacyGlsl) {
|
||||||
|
var values = element.components().stream().map(component -> componentExpression(component, legacyGlsl)).toList();
|
||||||
|
|
||||||
|
return values.size() == 1 ? values.get(0) : element.type() + "(" + String.join(", ", values) + ")";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static GlslType declaredType(Element element, Map<String, GlslType> declaredTypes) {
|
||||||
|
return declaredTypes.getOrDefault(element.name(), element.type());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decodes IEEE 754 single-precision bits using only integer and float arithmetic, for GLSL without
|
||||||
|
* {@code uintBitsToFloat}. Exact for normal numbers; denormals become zero, and infinities and NaNs are not handled.
|
||||||
|
*/
|
||||||
|
private static void appendFloatHelper(StringBuilder out) {
|
||||||
|
out.append("float _vf_bits_to_float(uint b) {\n");
|
||||||
|
out.append(" uint e = (b >> 23u) & 0xFFu;\n");
|
||||||
|
out.append(" if (e == 0u) return 0.0;\n");
|
||||||
|
out.append(" float f = (1.0 + float(b & 0x7FFFFFu) / 8388608.0) * exp2(float(int(e) - 127));\n");
|
||||||
|
out.append(" return (b >> 31u) != 0u ? -f : f;\n");
|
||||||
|
out.append("}\n\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String wordName(Scope scope, int word) {
|
||||||
|
return (scope == Scope.HEADER ? "_vf_h" : "_vf_v") + word;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String componentExpression(Component component, boolean legacyGlsl) {
|
||||||
|
String word = wordName(component.scope(), component.word());
|
||||||
|
int bits = component.bits();
|
||||||
|
|
||||||
|
String unsigned;
|
||||||
|
if (bits == 32) {
|
||||||
|
unsigned = word;
|
||||||
|
} else if (component.shift() == 0) {
|
||||||
|
unsigned = "(" + word + " & " + mask(bits) + ")";
|
||||||
|
} else {
|
||||||
|
unsigned = "((" + word + " >> " + component.shift() + "u) & " + mask(bits) + ")";
|
||||||
|
}
|
||||||
|
|
||||||
|
return switch (component.conversion()) {
|
||||||
|
case UINT -> unsigned;
|
||||||
|
case SINT -> signedExpression(component, word);
|
||||||
|
case FLOAT_BITS -> (legacyGlsl ? "_vf_bits_to_float(" : "uintBitsToFloat(") + word + ")";
|
||||||
|
case UNORM -> "(float(" + unsigned + ") / " + ((1L << bits) - 1) + ".0)";
|
||||||
|
case SNORM -> "max(float(" + signedExpression(component, word) + ") / " + ((1L << (bits - 1)) - 1) + ".0, -1.0)";
|
||||||
|
case UINT_TO_FLOAT -> "float(" + unsigned + ")";
|
||||||
|
case SINT_TO_FLOAT -> "float(" + signedExpression(component, word) + ")";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moves the component to the top of the word, then sign-extends it with an arithmetic right shift.
|
||||||
|
*/
|
||||||
|
private static String signedExpression(Component component, String word) {
|
||||||
|
int bits = component.bits();
|
||||||
|
|
||||||
|
if (bits == 32) {
|
||||||
|
return "int(" + word + ")";
|
||||||
|
}
|
||||||
|
|
||||||
|
int leftShift = 32 - component.shift() - bits;
|
||||||
|
String raised = leftShift == 0 ? word : "(" + word + " << " + leftShift + "u)";
|
||||||
|
|
||||||
|
return "(int(" + raised + ") >> " + (32 - bits) + ")";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String mask(int bits) {
|
||||||
|
return "0x" + Long.toHexString((1L << bits) - 1).toUpperCase() + "u";
|
||||||
|
}
|
||||||
|
}
|
||||||
+35
@@ -0,0 +1,35 @@
|
|||||||
|
package org.embeddedt.embeddium.impl.render.chunk.vertex.format;
|
||||||
|
|
||||||
|
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How the vertex shader obtains vertex data.
|
||||||
|
*/
|
||||||
|
public enum VertexFetchMode {
|
||||||
|
/**
|
||||||
|
* Vertex data is bound as vertex attributes.
|
||||||
|
*/
|
||||||
|
ATTRIBUTES,
|
||||||
|
/**
|
||||||
|
* The vertex shader reads vertex data from a texture buffer over the region's geometry buffer.
|
||||||
|
*/
|
||||||
|
PULLED;
|
||||||
|
|
||||||
|
private static final boolean PREFER_PULLING = Boolean.getBoolean("celeritas.preferVertexPulling");
|
||||||
|
|
||||||
|
public static VertexFetchMode select(ChunkVertexLayout layout) {
|
||||||
|
if (!layout.supportsAttributeFetch()) {
|
||||||
|
if (!isPullingSupported()) {
|
||||||
|
throw new UnsupportedOperationException("Layout must be pulled by the vertex shader, which this device does not support: " + layout);
|
||||||
|
}
|
||||||
|
|
||||||
|
return PULLED;
|
||||||
|
}
|
||||||
|
|
||||||
|
return PREFER_PULLING && isPullingSupported() ? PULLED : ATTRIBUTES;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isPullingSupported() {
|
||||||
|
return RenderDevice.INSTANCE.getDeviceFunctions().textureBufferFunctions().isSupported();
|
||||||
|
}
|
||||||
|
}
|
||||||
+16
-6
@@ -4,6 +4,7 @@ import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeFormat;
|
|||||||
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
|
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexLayout;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
|
||||||
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
|
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
|
||||||
|
|
||||||
@@ -21,6 +22,8 @@ public class CompactChunkVertex implements ChunkVertexType {
|
|||||||
|
|
||||||
public static final int STRIDE = 24;
|
public static final int STRIDE = 24;
|
||||||
|
|
||||||
|
public static final ChunkVertexLayout LAYOUT = ChunkVertexLayout.of(VERTEX_FORMAT);
|
||||||
|
|
||||||
private static final int POSITION_BITS = 21;
|
private static final int POSITION_BITS = 21;
|
||||||
private static final int POSITION_LOW_BITS = 5;
|
private static final int POSITION_LOW_BITS = 5;
|
||||||
private static final int POSITION_MASK = (1 << POSITION_BITS) - 1;
|
private static final int POSITION_MASK = (1 << POSITION_BITS) - 1;
|
||||||
@@ -61,13 +64,23 @@ public class CompactChunkVertex implements ChunkVertexType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public GlVertexFormat getVertexFormat() {
|
public ChunkVertexLayout getLayout() {
|
||||||
return VERTEX_FORMAT;
|
return LAYOUT;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ChunkVertexEncoder createEncoder() {
|
public ChunkVertexEncoder createEncoder() {
|
||||||
return (ptr, material, vertex, sectionIndex) -> {
|
return (ptr, material, vertices, sectionIndex) -> {
|
||||||
|
for (var vertex : vertices) {
|
||||||
|
writeVertex(ptr, material, vertex, sectionIndex);
|
||||||
|
ptr += STRIDE;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ptr;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void writeVertex(long ptr, Material material, ChunkVertexEncoder.Vertex vertex, int sectionIndex) {
|
||||||
int x = encodePosition(vertex.x);
|
int x = encodePosition(vertex.x);
|
||||||
int y = encodePosition(vertex.y);
|
int y = encodePosition(vertex.y);
|
||||||
int z = encodePosition(vertex.z);
|
int z = encodePosition(vertex.z);
|
||||||
@@ -89,9 +102,6 @@ public class CompactChunkVertex implements ChunkVertexType {
|
|||||||
|
|
||||||
LWJGL.memPutInt(ptr + 16, (encodeDrawParameters(material, sectionIndex, u, v) << 0) | (encodeLight(vertex.light) << 16));
|
LWJGL.memPutInt(ptr + 16, (encodeDrawParameters(material, sectionIndex, u, v) << 0) | (encodeLight(vertex.light) << 16));
|
||||||
LWJGL.memPutInt(ptr + 20, vertex.rdhFactor);
|
LWJGL.memPutInt(ptr + 20, vertex.rdhFactor);
|
||||||
|
|
||||||
return ptr + STRIDE;
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
+21
-7
@@ -4,6 +4,7 @@ import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeFormat;
|
|||||||
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
|
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexLayout;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
|
||||||
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
|
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
|
||||||
|
|
||||||
@@ -22,6 +23,8 @@ public class VanillaLikeChunkVertex implements ChunkVertexType {
|
|||||||
.addElement("a_RdhFactor", 28, GlVertexAttributeFormat.BYTE, 4, true, false)
|
.addElement("a_RdhFactor", 28, GlVertexAttributeFormat.BYTE, 4, true, false)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
|
public static final ChunkVertexLayout LAYOUT = ChunkVertexLayout.of(VERTEX_FORMAT);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public float getPositionScale() {
|
public float getPositionScale() {
|
||||||
return 1f;
|
return 1f;
|
||||||
@@ -38,13 +41,28 @@ public class VanillaLikeChunkVertex implements ChunkVertexType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public GlVertexFormat getVertexFormat() {
|
public ChunkVertexLayout getLayout() {
|
||||||
return VERTEX_FORMAT;
|
return LAYOUT;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ChunkVertexEncoder createEncoder() {
|
public ChunkVertexEncoder createEncoder() {
|
||||||
return (ptr, material, vertex, sectionIndex) -> {
|
return (ptr, material, vertices, sectionIndex) -> {
|
||||||
|
for (var vertex : vertices) {
|
||||||
|
writeVertex(ptr, material, vertex, sectionIndex);
|
||||||
|
ptr += STRIDE;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ptr;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeVertex(long ptr, Material material, ChunkVertexEncoder.Vertex vertex, int sectionIndex) {
|
||||||
|
writeVertexWithoutRdhFactor(ptr, material, vertex, sectionIndex);
|
||||||
|
LWJGL.memPutInt(ptr + 28, vertex.rdhFactor);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeVertexWithoutRdhFactor(long ptr, Material material, ChunkVertexEncoder.Vertex vertex, int sectionIndex) {
|
||||||
LWJGL.memPutFloat(ptr + 0, vertex.x);
|
LWJGL.memPutFloat(ptr + 0, vertex.x);
|
||||||
LWJGL.memPutFloat(ptr + 4, vertex.y);
|
LWJGL.memPutFloat(ptr + 4, vertex.y);
|
||||||
LWJGL.memPutFloat(ptr + 8, vertex.z);
|
LWJGL.memPutFloat(ptr + 8, vertex.z);
|
||||||
@@ -52,10 +70,6 @@ public class VanillaLikeChunkVertex implements ChunkVertexType {
|
|||||||
LWJGL.memPutFloat(ptr + 16, encodeTexture(vertex.u));
|
LWJGL.memPutFloat(ptr + 16, encodeTexture(vertex.u));
|
||||||
LWJGL.memPutFloat(ptr + 20, encodeTexture(vertex.v));
|
LWJGL.memPutFloat(ptr + 20, encodeTexture(vertex.v));
|
||||||
LWJGL.memPutInt(ptr + 24, (encodeDrawParameters(material, sectionIndex) << 0) | (encodeLight(vertex.light) << 16));
|
LWJGL.memPutInt(ptr + 24, (encodeDrawParameters(material, sectionIndex) << 0) | (encodeLight(vertex.light) << 16));
|
||||||
LWJGL.memPutInt(ptr + 28, vertex.rdhFactor);
|
|
||||||
|
|
||||||
return ptr + STRIDE;
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static int encodeDrawParameters(Material material, int sectionIndex) {
|
private static int encodeDrawParameters(Material material, int sectionIndex) {
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
|
|||||||
import org.embeddedt.embeddium.impl.gl.shader.ShaderParser;
|
import org.embeddedt.embeddium.impl.gl.shader.ShaderParser;
|
||||||
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
|
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.function.Function;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
|
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
|
||||||
@@ -24,7 +26,22 @@ public class ShaderLoader {
|
|||||||
* @return An OpenGL shader object compiled with the given user defines
|
* @return An OpenGL shader object compiled with the given user defines
|
||||||
*/
|
*/
|
||||||
public static GlShader loadShader(ShaderType type, String name, ShaderConstants constants) {
|
public static GlShader loadShader(ShaderType type, String name, ShaderConstants constants) {
|
||||||
return new GlShader(type, name, downgradeIfNeeded(type, ShaderParser.parseShader(getShaderSource(name), ShaderLoader::getShaderSource, constants)));
|
return loadShader(type, name, constants, Map.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Like {@link #loadShader(ShaderType, String, ShaderConstants)}, but imports of names in {@code generatedSources}
|
||||||
|
* resolve to the given source instead of the classpath.
|
||||||
|
*/
|
||||||
|
public static GlShader loadShader(ShaderType type, String name, ShaderConstants constants, Map<String, String> generatedSources) {
|
||||||
|
return new GlShader(type, name, downgradeIfNeeded(type, ShaderParser.parseShader(getShaderSource(name), sourceProvider(generatedSources), constants)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Function<String, String> sourceProvider(Map<String, String> generatedSources) {
|
||||||
|
return name -> {
|
||||||
|
String generated = generatedSources.get(name);
|
||||||
|
return generated != null ? generated : getShaderSource(name);
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final Pattern VERSION_DIRECTIVE = Pattern.compile("^#version.*$", Pattern.MULTILINE);
|
private static final Pattern VERSION_DIRECTIVE = Pattern.compile("^#version.*$", Pattern.MULTILINE);
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ void main() {
|
|||||||
v_RdhFactor.rgb *= lightColor.rgb;
|
v_RdhFactor.rgb *= lightColor.rgb;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
int corner = gl_VertexID & 3;
|
int corner = _vert_corner;
|
||||||
v_QuadCoord = vec2(corner >= 2 ? 1.0 : 0.0,
|
v_QuadCoord = vec2(corner >= 2 ? 1.0 : 0.0,
|
||||||
corner == 1 || corner == 2 ? 1.0 : 0.0);
|
corner == 1 || corner == 2 ? 1.0 : 0.0);
|
||||||
v_TexCoord = _vert_tex_diffuse_coord;
|
v_TexCoord = _vert_tex_diffuse_coord;
|
||||||
|
|||||||
@@ -30,13 +30,17 @@ vec3 _get_draw_translation(uint pos) {
|
|||||||
return _get_relative_chunk_coord(pos) * vec3(16.0);
|
return _get_relative_chunk_coord(pos) * vec3(16.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
#ifdef USE_VERTEX_COMPRESSION
|
#import <sodium:generated/vertex_fetch.glsl>
|
||||||
in uvec4 a_PosId;
|
|
||||||
in vec4 a_Color;
|
|
||||||
in uvec2 a_TexCoord;
|
|
||||||
in uint a_LightCoord;
|
|
||||||
in vec4 a_RdhFactor;
|
|
||||||
|
|
||||||
|
vec4 _get_rdh_factor() {
|
||||||
|
#ifdef VERT_HAS_a_RdhFactor
|
||||||
|
return a_RdhFactor;
|
||||||
|
#else
|
||||||
|
return vec4(0.0);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef USE_VERTEX_COMPRESSION
|
||||||
#if !defined(VERT_POS_SCALE)
|
#if !defined(VERT_POS_SCALE)
|
||||||
#error "VERT_POS_SCALE not defined"
|
#error "VERT_POS_SCALE not defined"
|
||||||
#elif !defined(VERT_POS_OFFSET)
|
#elif !defined(VERT_POS_OFFSET)
|
||||||
@@ -45,16 +49,26 @@ in vec4 a_RdhFactor;
|
|||||||
#error "VERT_TEX_SCALE not defined"
|
#error "VERT_TEX_SCALE not defined"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
vec3 _vert_decode_position(uvec4 pos_id) {
|
||||||
|
uvec3 position = (pos_id.xyz << 5u) | ((uvec3(pos_id.w) >> uvec3(0u, 5u, 10u)) & uvec3(0x1Fu));
|
||||||
|
return vec3(position) * VERT_POS_SCALE + VERT_POS_OFFSET;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The low bits of each texture coordinate are stored with the draw parameters
|
||||||
|
vec2 _vert_decode_tex_coord(uvec2 tex_coord, uint light_coord) {
|
||||||
|
uvec2 coord = (tex_coord << 2u) | ((uvec2(light_coord & 0xFFFFu) >> uvec2(4u, 6u)) & uvec2(0x3u));
|
||||||
|
return vec2(coord) * VERT_TEX_SCALE;
|
||||||
|
}
|
||||||
|
|
||||||
void _vert_init() {
|
void _vert_init() {
|
||||||
|
_vert_fetch();
|
||||||
|
|
||||||
uint packed_draw_params = (a_LightCoord & 0xFFFFu);
|
uint packed_draw_params = (a_LightCoord & 0xFFFFu);
|
||||||
|
|
||||||
uvec3 position = (a_PosId.xyz << 5u) | ((uvec3(a_PosId.w) >> uvec3(0u, 5u, 10u)) & uvec3(0x1Fu));
|
_vert_position = _vert_decode_position(a_PosId);
|
||||||
uvec2 tex_coord = (a_TexCoord << 2u) | ((uvec2(packed_draw_params) >> uvec2(4u, 6u)) & uvec2(0x3u));
|
_vert_tex_diffuse_coord = _vert_decode_tex_coord(a_TexCoord, a_LightCoord);
|
||||||
|
|
||||||
_vert_position = (vec3(position) * VERT_POS_SCALE + VERT_POS_OFFSET);
|
|
||||||
_vert_tex_diffuse_coord = (vec2(tex_coord) * VERT_TEX_SCALE);
|
|
||||||
_vert_color = a_Color;
|
_vert_color = a_Color;
|
||||||
_vert_rdh_factor = a_RdhFactor;
|
_vert_rdh_factor = _get_rdh_factor();
|
||||||
|
|
||||||
_material_params = (packed_draw_params) & 0xFu;
|
_material_params = (packed_draw_params) & 0xFu;
|
||||||
_draw_id = (packed_draw_params >> 8) & 0xFFu;
|
_draw_id = (packed_draw_params >> 8) & 0xFFu;
|
||||||
@@ -63,17 +77,21 @@ void _vert_init() {
|
|||||||
|
|
||||||
#else
|
#else
|
||||||
|
|
||||||
in vec3 a_PosId;
|
vec3 _vert_decode_position(vec3 pos_id) {
|
||||||
in vec4 a_Color;
|
return pos_id;
|
||||||
in vec2 a_TexCoord;
|
}
|
||||||
in uint a_LightCoord;
|
|
||||||
in vec4 a_RdhFactor;
|
vec2 _vert_decode_tex_coord(vec2 tex_coord, uint light_coord) {
|
||||||
|
return tex_coord;
|
||||||
|
}
|
||||||
|
|
||||||
void _vert_init() {
|
void _vert_init() {
|
||||||
_vert_position = a_PosId;
|
_vert_fetch();
|
||||||
_vert_tex_diffuse_coord = a_TexCoord;
|
|
||||||
|
_vert_position = _vert_decode_position(a_PosId);
|
||||||
|
_vert_tex_diffuse_coord = _vert_decode_tex_coord(a_TexCoord, a_LightCoord);
|
||||||
_vert_color = a_Color;
|
_vert_color = a_Color;
|
||||||
_vert_rdh_factor = a_RdhFactor;
|
_vert_rdh_factor = _get_rdh_factor();
|
||||||
|
|
||||||
uint packed_draw_params = (a_LightCoord & 0xFFFFu);
|
uint packed_draw_params = (a_LightCoord & 0xFFFFu);
|
||||||
// Vertex Material
|
// Vertex Material
|
||||||
@@ -86,3 +104,15 @@ void _vert_init() {
|
|||||||
_vert_tex_light_coord = ivec2((uvec2((a_LightCoord >> 16) & 0xFFFFu) >> uvec2(0, 8)) & uvec2(0xFFu));
|
_vert_tex_light_coord = ivec2((uvec2((a_LightCoord >> 16) & 0xFFFFu) >> uvec2(0, 8)) & uvec2(0xFFu));
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#ifdef VERT_CAN_FETCH_CORNERS
|
||||||
|
// Decoded values of another corner of this vertex's primitive, which pulled vertex data makes available
|
||||||
|
vec3 _vert_corner_position(int corner) {
|
||||||
|
return _vert_decode_position(_vert_fetch_corner(corner).a_PosId);
|
||||||
|
}
|
||||||
|
|
||||||
|
vec2 _vert_corner_tex_coord(int corner) {
|
||||||
|
_VertInputs v = _vert_fetch_corner(corner);
|
||||||
|
return _vert_decode_tex_coord(v.a_TexCoord, v.a_LightCoord);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
+280
@@ -0,0 +1,280 @@
|
|||||||
|
package org.embeddedt.embeddium.impl.render.chunk.vertex.format;
|
||||||
|
|
||||||
|
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttribute;
|
||||||
|
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeFormat;
|
||||||
|
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchGenerator.Component;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchGenerator.Element;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchGenerator.Scope;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.impl.CompactChunkVertex;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.impl.VanillaLikeChunkVertex;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.ByteOrder;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class VertexFetchGeneratorTest {
|
||||||
|
/**
|
||||||
|
* A layout with a header, using every conversion the generator supports.
|
||||||
|
*/
|
||||||
|
private static final ChunkVertexLayout HEADER_LAYOUT = ChunkVertexLayout.withHeader(
|
||||||
|
GlVertexFormat.builder(12)
|
||||||
|
.addElement("a_PosId", 0, GlVertexAttributeFormat.FLOAT, 2, false, false)
|
||||||
|
.addElement("a_TexCoord", 8, GlVertexAttributeFormat.SHORT, 2, false, false)
|
||||||
|
.build(),
|
||||||
|
GlVertexFormat.builder(12)
|
||||||
|
.addElement("a_Color", 0, GlVertexAttributeFormat.UNSIGNED_SHORT, 2, true, false)
|
||||||
|
.addElement("a_RdhFactor", 4, GlVertexAttributeFormat.SHORT, 2, true, false)
|
||||||
|
.addElement("a_LightCoord", 8, GlVertexAttributeFormat.BYTE, 4, false, true)
|
||||||
|
.build(),
|
||||||
|
4);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void compactPlanMatchesAttributeFetch() {
|
||||||
|
assertPlanMatchesAttributeFetch(CompactChunkVertex.LAYOUT, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void vanillaLikePlanMatchesAttributeFetch() {
|
||||||
|
assertPlanMatchesAttributeFetch(VanillaLikeChunkVertex.LAYOUT, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void headerPlanMatchesAttributeFetch() {
|
||||||
|
assertPlanMatchesAttributeFetch(HEADER_LAYOUT, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsComponentsStraddlingWords() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> ChunkVertexLayout.of(GlVertexFormat.builder(8)
|
||||||
|
.addElement("a_PosId", 1, GlVertexAttributeFormat.UNSIGNED_SHORT, 2, false, true)
|
||||||
|
.build()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsStridesThatAreNotWords() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> ChunkVertexLayout.of(GlVertexFormat.builder(6)
|
||||||
|
.addElement("a_PosId", 0, GlVertexAttributeFormat.UNSIGNED_SHORT, 2, false, true)
|
||||||
|
.build()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void headerLayoutsCannotUseAttributes() {
|
||||||
|
assertFalse(HEADER_LAYOUT.supportsAttributeFetch());
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> VertexFetchGenerator.generate(HEADER_LAYOUT, 4, VertexFetchMode.ATTRIBUTES, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void legacyPullingDecodesFloatsWithoutBitCasts() {
|
||||||
|
String source = VertexFetchGenerator.generate(VanillaLikeChunkVertex.LAYOUT, 4, VertexFetchMode.PULLED, true);
|
||||||
|
|
||||||
|
assertTrue(source.contains("texelFetchBuffer("));
|
||||||
|
assertTrue(source.contains("_vf_bits_to_float("));
|
||||||
|
assertFalse(source.contains("uintBitsToFloat"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void declaresEveryElementOfTheLayout() {
|
||||||
|
var layout = ChunkVertexLayout.of(GlVertexFormat.builder(8)
|
||||||
|
.addElement("mc_Entity", 0, GlVertexAttributeFormat.SHORT, 2, false, false)
|
||||||
|
.addElement("anything_else", 4, GlVertexAttributeFormat.UNSIGNED_INT, 1, false, true)
|
||||||
|
.build());
|
||||||
|
|
||||||
|
String source = VertexFetchGenerator.generate(layout, 4, VertexFetchMode.ATTRIBUTES, false);
|
||||||
|
|
||||||
|
assertTrue(source.contains("in vec2 mc_Entity;"));
|
||||||
|
assertTrue(source.contains("in uint anything_else;"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void declaredTypesPadLikeAttributeFetch() {
|
||||||
|
var layout = ChunkVertexLayout.of(GlVertexFormat.builder(4)
|
||||||
|
.addElement("mc_Entity", 0, GlVertexAttributeFormat.SHORT, 2, false, false)
|
||||||
|
.build());
|
||||||
|
var declared = Map.of("mc_Entity", VertexFetchGenerator.GlslType.parse("vec4"));
|
||||||
|
|
||||||
|
String attributes = VertexFetchGenerator.generate(layout, 4, VertexFetchMode.ATTRIBUTES, false, declared);
|
||||||
|
String pulled = VertexFetchGenerator.generate(layout, 4, VertexFetchMode.PULLED, false, declared);
|
||||||
|
|
||||||
|
assertTrue(attributes.contains("in vec4 mc_Entity;"));
|
||||||
|
assertTrue(pulled.contains("\nvec4 mc_Entity;"));
|
||||||
|
assertTrue(pulled.contains("v.mc_Entity = vec2(float((int((_vf_v0 << 16u)) >> 16)), float((int(_vf_v0) >> 16)));"), pulled);
|
||||||
|
assertTrue(pulled.contains("mc_Entity = vec4(v.mc_Entity, 0.0, 1.0);"), pulled);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void declaredTypesTruncateAndCast() {
|
||||||
|
var layout = ChunkVertexLayout.of(GlVertexFormat.builder(4)
|
||||||
|
.addElement("at_midBlock", 0, GlVertexAttributeFormat.BYTE, 4, false, false)
|
||||||
|
.build());
|
||||||
|
var declared = Map.of("at_midBlock", VertexFetchGenerator.GlslType.parse("ivec2"));
|
||||||
|
|
||||||
|
String pulled = VertexFetchGenerator.generate(layout, 4, VertexFetchMode.PULLED, false, declared);
|
||||||
|
|
||||||
|
assertTrue(pulled.contains("at_midBlock = ivec2(v.at_midBlock);"), pulled);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void adaptsValuesLikeAttributeFetch() {
|
||||||
|
var vec4 = VertexFetchGenerator.GlslType.parse("vec4");
|
||||||
|
|
||||||
|
assertEquals("x", vec4.adapt("x", vec4));
|
||||||
|
assertEquals("vec3(x)", VertexFetchGenerator.GlslType.parse("vec3").adapt("x", vec4));
|
||||||
|
assertEquals("vec4(x, 0.0, 1.0)", vec4.adapt("x", VertexFetchGenerator.GlslType.parse("vec2")));
|
||||||
|
assertEquals("ivec4(x, 1)", VertexFetchGenerator.GlslType.parse("ivec4").adapt("x", VertexFetchGenerator.GlslType.parse("vec3")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parsesOnlyScalarAndVectorTypes() {
|
||||||
|
assertEquals(new VertexFetchGenerator.GlslType(VertexFetchGenerator.ScalarType.UINT, 3), VertexFetchGenerator.GlslType.parse("uvec3"));
|
||||||
|
assertEquals(new VertexFetchGenerator.GlslType(VertexFetchGenerator.ScalarType.INT, 1), VertexFetchGenerator.GlslType.parse("int"));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> VertexFetchGenerator.GlslType.parse("mat4"));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> VertexFetchGenerator.GlslType.parse("vec5"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirrors the arithmetic of the generated {@code _vf_bits_to_float}, which must be exact for normal floats.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void legacyFloatDecodeIsExactForNormals() {
|
||||||
|
var random = new Random(5678);
|
||||||
|
|
||||||
|
for (int i = 0; i < 1_000_000; i++) {
|
||||||
|
int bits = random.nextInt();
|
||||||
|
int exponent = (bits >>> 23) & 0xFF;
|
||||||
|
|
||||||
|
if (exponent == 0 || exponent == 0xFF) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
float magnitude = (1.0f + (float) (bits & 0x7FFFFF) / 8388608.0f) * Math.scalb(1.0f, exponent - 127);
|
||||||
|
float decoded = (bits >>> 31) != 0 ? -magnitude : magnitude;
|
||||||
|
|
||||||
|
assertEquals(Float.intBitsToFloat(bits), decoded);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void compactPulledSourceIsUnchanged() throws IOException {
|
||||||
|
assertEquals(readResource("compact_pulled.glsl"),
|
||||||
|
VertexFetchGenerator.generate(CompactChunkVertex.LAYOUT, 4, VertexFetchMode.PULLED, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void compactAttributeSourceIsUnchanged() throws IOException {
|
||||||
|
assertEquals(readResource("compact_attributes.glsl"),
|
||||||
|
VertexFetchGenerator.generate(CompactChunkVertex.LAYOUT, 4, VertexFetchMode.ATTRIBUTES, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fills records with random bytes, then checks that every component the plan extracts from 32-bit words equals what
|
||||||
|
* attribute fetch reads from the attribute's own offset and type.
|
||||||
|
*/
|
||||||
|
private static void assertPlanMatchesAttributeFetch(ChunkVertexLayout layout, int verticesPerPrimitive) {
|
||||||
|
var header = layout.header();
|
||||||
|
int headerStride = header != null ? header.format().getStride() : 0;
|
||||||
|
int vertices = header != null ? header.verticesPerRecord() : verticesPerPrimitive;
|
||||||
|
int vertexStride = layout.vertex().getStride();
|
||||||
|
|
||||||
|
var random = new Random(1234);
|
||||||
|
var record = ByteBuffer.allocate(headerStride + vertices * vertexStride).order(ByteOrder.LITTLE_ENDIAN);
|
||||||
|
List<Element> plan = VertexFetchGenerator.plan(layout);
|
||||||
|
|
||||||
|
assertFalse(plan.isEmpty());
|
||||||
|
|
||||||
|
for (int iteration = 0; iteration < 1000; iteration++) {
|
||||||
|
random.nextBytes(record.array());
|
||||||
|
|
||||||
|
for (int corner = 0; corner < vertices; corner++) {
|
||||||
|
int vertexBase = headerStride + corner * vertexStride;
|
||||||
|
|
||||||
|
for (Element element : plan) {
|
||||||
|
boolean inHeader = element.components().get(0).scope() == Scope.HEADER;
|
||||||
|
GlVertexAttribute attribute = (inHeader ? header.format() : layout.vertex()).getAttribute(element.name());
|
||||||
|
int base = inHeader ? 0 : vertexBase;
|
||||||
|
|
||||||
|
for (int i = 0; i < element.components().size(); i++) {
|
||||||
|
Component component = element.components().get(i);
|
||||||
|
int word = record.getInt(base + component.word() * 4);
|
||||||
|
|
||||||
|
double expected = attributeFetch(record, base + attribute.getPointer() + i * attribute.getFormat().size(), attribute);
|
||||||
|
double actual = interpret(component, word);
|
||||||
|
|
||||||
|
assertEquals(expected, actual, "component " + i + " of " + element.name());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double attributeFetch(ByteBuffer record, int offset, GlVertexAttribute attribute) {
|
||||||
|
GlVertexAttributeFormat format = attribute.getFormat();
|
||||||
|
|
||||||
|
if (format.equals(GlVertexAttributeFormat.FLOAT)) {
|
||||||
|
return record.getFloat(offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
long value;
|
||||||
|
int bits = format.size() * 8;
|
||||||
|
boolean signed = format.equals(GlVertexAttributeFormat.BYTE) || format.equals(GlVertexAttributeFormat.SHORT);
|
||||||
|
|
||||||
|
if (format.equals(GlVertexAttributeFormat.UNSIGNED_BYTE)) {
|
||||||
|
value = Byte.toUnsignedLong(record.get(offset));
|
||||||
|
} else if (format.equals(GlVertexAttributeFormat.BYTE)) {
|
||||||
|
value = record.get(offset);
|
||||||
|
} else if (format.equals(GlVertexAttributeFormat.UNSIGNED_SHORT)) {
|
||||||
|
value = Short.toUnsignedLong(record.getShort(offset));
|
||||||
|
} else if (format.equals(GlVertexAttributeFormat.SHORT)) {
|
||||||
|
value = record.getShort(offset);
|
||||||
|
} else if (format.equals(GlVertexAttributeFormat.UNSIGNED_INT)) {
|
||||||
|
value = Integer.toUnsignedLong(record.getInt(offset));
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("Unhandled format " + format);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (attribute.isIntType() || !attribute.isNormalized()) {
|
||||||
|
return attribute.isIntType() ? value : (float) value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (signed) {
|
||||||
|
return Math.max((float) value / (float) ((1L << (bits - 1)) - 1), -1.0f);
|
||||||
|
} else {
|
||||||
|
return (float) value / (float) ((1L << bits) - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Evaluates a planned component the way the generated GLSL does.
|
||||||
|
*/
|
||||||
|
private static double interpret(Component component, int word) {
|
||||||
|
int bits = component.bits();
|
||||||
|
long unsigned = bits == 32 ? Integer.toUnsignedLong(word) : (word >>> component.shift()) & ((1L << bits) - 1);
|
||||||
|
long signed = bits == 32 ? word : (word << (32 - component.shift() - bits)) >> (32 - bits);
|
||||||
|
|
||||||
|
return switch (component.conversion()) {
|
||||||
|
case UINT -> unsigned;
|
||||||
|
case SINT -> signed;
|
||||||
|
case FLOAT_BITS -> Float.intBitsToFloat(word);
|
||||||
|
case UNORM -> (float) unsigned / (float) ((1L << bits) - 1);
|
||||||
|
case SNORM -> Math.max((float) signed / (float) ((1L << (bits - 1)) - 1), -1.0f);
|
||||||
|
case UINT_TO_FLOAT -> (float) unsigned;
|
||||||
|
case SINT_TO_FLOAT -> (float) signed;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String readResource(String name) throws IOException {
|
||||||
|
try (InputStream in = VertexFetchGeneratorTest.class.getResourceAsStream(name)) {
|
||||||
|
assertNotNull(in, "missing test resource " + name);
|
||||||
|
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
#define VERT_HAS_a_PosId
|
||||||
|
#define VERT_HAS_a_Color
|
||||||
|
#define VERT_HAS_a_TexCoord
|
||||||
|
#define VERT_HAS_a_LightCoord
|
||||||
|
#define VERT_HAS_a_RdhFactor
|
||||||
|
|
||||||
|
in uvec4 a_PosId;
|
||||||
|
in vec4 a_Color;
|
||||||
|
in uvec2 a_TexCoord;
|
||||||
|
in uint a_LightCoord;
|
||||||
|
in vec4 a_RdhFactor;
|
||||||
|
|
||||||
|
int _vert_corner;
|
||||||
|
|
||||||
|
void _vert_fetch() {
|
||||||
|
_vert_corner = gl_VertexID % 4;
|
||||||
|
}
|
||||||
+52
@@ -0,0 +1,52 @@
|
|||||||
|
#define VERT_HAS_a_PosId
|
||||||
|
#define VERT_HAS_a_Color
|
||||||
|
#define VERT_HAS_a_TexCoord
|
||||||
|
#define VERT_HAS_a_LightCoord
|
||||||
|
#define VERT_HAS_a_RdhFactor
|
||||||
|
|
||||||
|
uvec4 a_PosId;
|
||||||
|
vec4 a_Color;
|
||||||
|
uvec2 a_TexCoord;
|
||||||
|
uint a_LightCoord;
|
||||||
|
vec4 a_RdhFactor;
|
||||||
|
|
||||||
|
int _vert_corner;
|
||||||
|
|
||||||
|
#define VERT_CAN_FETCH_CORNERS
|
||||||
|
|
||||||
|
uniform usamplerBuffer u_VertexData;
|
||||||
|
|
||||||
|
struct _VertInputs {
|
||||||
|
uvec4 a_PosId;
|
||||||
|
vec4 a_Color;
|
||||||
|
uvec2 a_TexCoord;
|
||||||
|
uint a_LightCoord;
|
||||||
|
vec4 a_RdhFactor;
|
||||||
|
};
|
||||||
|
|
||||||
|
_VertInputs _vert_fetch_corner(int corner) {
|
||||||
|
int _vf_vertex = ((gl_VertexID / 4) * 24) + (corner * 6);
|
||||||
|
uint _vf_v0 = texelFetch(u_VertexData, _vf_vertex + 0).r;
|
||||||
|
uint _vf_v1 = texelFetch(u_VertexData, _vf_vertex + 1).r;
|
||||||
|
uint _vf_v2 = texelFetch(u_VertexData, _vf_vertex + 2).r;
|
||||||
|
uint _vf_v3 = texelFetch(u_VertexData, _vf_vertex + 3).r;
|
||||||
|
uint _vf_v4 = texelFetch(u_VertexData, _vf_vertex + 4).r;
|
||||||
|
uint _vf_v5 = texelFetch(u_VertexData, _vf_vertex + 5).r;
|
||||||
|
_VertInputs v;
|
||||||
|
v.a_PosId = uvec4((_vf_v0 & 0xFFFFu), ((_vf_v0 >> 16u) & 0xFFFFu), (_vf_v1 & 0xFFFFu), ((_vf_v1 >> 16u) & 0xFFFFu));
|
||||||
|
v.a_Color = vec4((float((_vf_v2 & 0xFFu)) / 255.0), (float(((_vf_v2 >> 8u) & 0xFFu)) / 255.0), (float(((_vf_v2 >> 16u) & 0xFFu)) / 255.0), (float(((_vf_v2 >> 24u) & 0xFFu)) / 255.0));
|
||||||
|
v.a_TexCoord = uvec2((_vf_v3 & 0xFFFFu), ((_vf_v3 >> 16u) & 0xFFFFu));
|
||||||
|
v.a_LightCoord = _vf_v4;
|
||||||
|
v.a_RdhFactor = vec4(max(float((int((_vf_v5 << 24u)) >> 24)) / 127.0, -1.0), max(float((int((_vf_v5 << 16u)) >> 24)) / 127.0, -1.0), max(float((int((_vf_v5 << 8u)) >> 24)) / 127.0, -1.0), max(float((int(_vf_v5) >> 24)) / 127.0, -1.0));
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _vert_fetch() {
|
||||||
|
_vert_corner = gl_VertexID % 4;
|
||||||
|
_VertInputs v = _vert_fetch_corner(_vert_corner);
|
||||||
|
a_PosId = v.a_PosId;
|
||||||
|
a_Color = v.a_Color;
|
||||||
|
a_TexCoord = v.a_TexCoord;
|
||||||
|
a_LightCoord = v.a_LightCoord;
|
||||||
|
a_RdhFactor = v.a_RdhFactor;
|
||||||
|
}
|
||||||
+13
@@ -1,5 +1,6 @@
|
|||||||
package org.embeddedt.embeddium.impl.modern.render.chunk;
|
package org.embeddedt.embeddium.impl.modern.render.chunk;
|
||||||
|
|
||||||
|
import com.mojang.blaze3d.platform.GlStateManager;
|
||||||
import org.embeddedt.embeddium.impl.Celeritas;
|
import org.embeddedt.embeddium.impl.Celeritas;
|
||||||
import org.embeddedt.embeddium.impl.gl.compat.FogHelper;
|
import org.embeddedt.embeddium.impl.gl.compat.FogHelper;
|
||||||
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
|
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
|
||||||
@@ -7,6 +8,7 @@ import org.embeddedt.embeddium.impl.render.chunk.DefaultChunkRenderer;
|
|||||||
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
|
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface;
|
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderTextureSlot;
|
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderTextureSlot;
|
||||||
|
import org.lwjgl.opengl.GL13C;
|
||||||
|
|
||||||
public class ModernChunkRenderer extends DefaultChunkRenderer {
|
public class ModernChunkRenderer extends DefaultChunkRenderer {
|
||||||
public ModernChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) {
|
public ModernChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) {
|
||||||
@@ -29,6 +31,17 @@ public class ModernChunkRenderer extends DefaultChunkRenderer {
|
|||||||
return Celeritas.options().performance.useBlockFaceCulling /*? if shaders {*/ && !net.irisshaders.iris.shadows.ShadowRenderingState.areShadowsCurrentlyBeingRendered() /*?}*/;
|
return Celeritas.options().performance.useBlockFaceCulling /*? if shaders {*/ && !net.irisshaders.iris.shadows.ShadowRenderingState.areShadowsCurrentlyBeingRendered() /*?}*/;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected int activateTextureUnit(int unit) {
|
||||||
|
//? if >=26.1 {
|
||||||
|
/*int previous = GL13C.GL_TEXTURE0 + org.embeddedt.embeddium.impl.mixin.core.GlStateManagerAccessor.celeritas$getActiveTexture();
|
||||||
|
*///?} else {
|
||||||
|
int previous = GlStateManager._getActiveTexture();
|
||||||
|
//?}
|
||||||
|
GlStateManager._activeTexture(unit);
|
||||||
|
return previous;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void configureShaderInterface(ChunkShaderInterface shader) {
|
protected void configureShaderInterface(ChunkShaderInterface shader) {
|
||||||
shader.setTextureSlot(ChunkShaderTextureSlot.BLOCK, 0);
|
shader.setTextureSlot(ChunkShaderTextureSlot.BLOCK, 0);
|
||||||
|
|||||||
+17
-18
@@ -189,12 +189,7 @@ public class ImmersiveConnectionRenderer implements ResourceManagerReloadListene
|
|||||||
int color,
|
int color,
|
||||||
boolean lightForStart
|
boolean lightForStart
|
||||||
) {
|
) {
|
||||||
static final ThreadLocal<ChunkVertexEncoder.Vertex[]> vertexHolder = ThreadLocal.withInitial(() -> new ChunkVertexEncoder.Vertex[1]);
|
void copyTo(ChunkVertexEncoder.Vertex sodiumVertex, int offX, int offY, int offZ, int lightStart, int lightEnd) {
|
||||||
|
|
||||||
void write(
|
|
||||||
ChunkMeshBufferBuilder vertexSink, Material material, int offX, int offY, int offZ, int lightStart, int lightEnd
|
|
||||||
) {
|
|
||||||
ChunkVertexEncoder.Vertex sodiumVertex = new ChunkVertexEncoder.Vertex();
|
|
||||||
sodiumVertex.x = offX + posX;
|
sodiumVertex.x = offX + posX;
|
||||||
sodiumVertex.y = offY + posY;
|
sodiumVertex.y = offY + posY;
|
||||||
sodiumVertex.z = offZ + posZ;
|
sodiumVertex.z = offZ + posZ;
|
||||||
@@ -202,28 +197,32 @@ public class ImmersiveConnectionRenderer implements ResourceManagerReloadListene
|
|||||||
sodiumVertex.u = texU;
|
sodiumVertex.u = texU;
|
||||||
sodiumVertex.v = texV;
|
sodiumVertex.v = texV;
|
||||||
sodiumVertex.light = lightForStart ? lightStart : lightEnd;
|
sodiumVertex.light = lightForStart ? lightStart : lightEnd;
|
||||||
ChunkVertexEncoder.Vertex[] array = vertexHolder.get();
|
|
||||||
array[0] = sodiumVertex;
|
|
||||||
vertexSink.push(array, material);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private record Quad(Vertex v0, Vertex v1, Vertex v2, Vertex v3) {
|
private record Quad(Vertex v0, Vertex v1, Vertex v2, Vertex v3) {
|
||||||
|
static final ThreadLocal<ChunkVertexEncoder.Vertex[]> vertexHolder = ThreadLocal.withInitial(ChunkVertexEncoder.Vertex::uninitializedQuad);
|
||||||
|
|
||||||
void write(
|
void write(
|
||||||
ChunkModelBuilder out, Material material, int offX, int offY, int offZ, int lightStart, int lightEnd
|
ChunkModelBuilder out, Material material, int offX, int offY, int offZ, int lightStart, int lightEnd
|
||||||
) {
|
) {
|
||||||
var vertexSink = out.getVertexBuffer(ModelQuadFacing.UNASSIGNED);
|
var vertexSink = out.getVertexBuffer(ModelQuadFacing.UNASSIGNED);
|
||||||
int quadStart = vertexSink.count();
|
var vertices = vertexHolder.get();
|
||||||
// clockwise
|
// clockwise
|
||||||
v0.write(vertexSink, material, offX, offY, offZ, lightStart, lightEnd);
|
push(vertexSink, vertices, material, v0, v1, v2, v3, offX, offY, offZ, lightStart, lightEnd);
|
||||||
v1.write(vertexSink, material, offX, offY, offZ, lightStart, lightEnd);
|
|
||||||
v2.write(vertexSink, material, offX, offY, offZ, lightStart, lightEnd);
|
|
||||||
v3.write(vertexSink, material, offX, offY, offZ, lightStart, lightEnd);
|
|
||||||
// counter-clockwise
|
// counter-clockwise
|
||||||
v0.write(vertexSink, material, offX, offY, offZ, lightStart, lightEnd);
|
push(vertexSink, vertices, material, v0, v3, v2, v1, offX, offY, offZ, lightStart, lightEnd);
|
||||||
v3.write(vertexSink, material, offX, offY, offZ, lightStart, lightEnd);
|
}
|
||||||
v2.write(vertexSink ,material, offX, offY, offZ, lightStart, lightEnd);
|
|
||||||
v1.write(vertexSink, material, offX, offY, offZ, lightStart, lightEnd);
|
private static void push(
|
||||||
|
ChunkMeshBufferBuilder vertexSink, ChunkVertexEncoder.Vertex[] vertices, Material material,
|
||||||
|
Vertex a, Vertex b, Vertex c, Vertex d, int offX, int offY, int offZ, int lightStart, int lightEnd
|
||||||
|
) {
|
||||||
|
a.copyTo(vertices[0], offX, offY, offZ, lightStart, lightEnd);
|
||||||
|
b.copyTo(vertices[1], offX, offY, offZ, lightStart, lightEnd);
|
||||||
|
c.copyTo(vertices[2], offX, offY, offZ, lightStart, lightEnd);
|
||||||
|
d.copyTo(vertices[3], offX, offY, offZ, lightStart, lightEnd);
|
||||||
|
vertexSink.push(vertices, material);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
package org.embeddedt.embeddium.impl.mixin.core;
|
||||||
|
|
||||||
|
import com.mojang.blaze3d.platform.GlStateManager;
|
||||||
|
import org.spongepowered.asm.mixin.Mixin;
|
||||||
|
import org.spongepowered.asm.mixin.gen.Accessor;
|
||||||
|
|
||||||
|
@Mixin(GlStateManager.class)
|
||||||
|
public interface GlStateManagerAccessor {
|
||||||
|
/**
|
||||||
|
* {@return the cached active texture unit, as an index rather than {@code GL_TEXTURE0 + n}}
|
||||||
|
*/
|
||||||
|
@Accessor("activeTexture")
|
||||||
|
static int celeritas$getActiveTexture() {
|
||||||
|
throw new AssertionError();
|
||||||
|
}
|
||||||
|
}
|
||||||
+7
-2
@@ -10,6 +10,8 @@ import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
|
|||||||
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkFogMode;
|
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkFogMode;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderOptions;
|
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderOptions;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexLayout;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchMode;
|
||||||
import net.irisshaders.iris.Iris;
|
import net.irisshaders.iris.Iris;
|
||||||
import net.irisshaders.iris.gl.blending.BlendModeOverride;
|
import net.irisshaders.iris.gl.blending.BlendModeOverride;
|
||||||
import net.irisshaders.iris.gl.blending.BufferBlendOverride;
|
import net.irisshaders.iris.gl.blending.BufferBlendOverride;
|
||||||
@@ -89,10 +91,13 @@ public class IrisChunkProgramOverrides {
|
|||||||
|
|
||||||
createdShaders.values().forEach(builder::attachShader);
|
createdShaders.values().forEach(builder::attachShader);
|
||||||
|
|
||||||
|
var terrainPass = pass.toTerrainPass(configuration);
|
||||||
|
if (terrainPass.vertexFetchMode() == VertexFetchMode.ATTRIBUTES) {
|
||||||
int i = 0;
|
int i = 0;
|
||||||
var vertexType = configuration.getVertexTypeForPass(pass.toTerrainPass(configuration));
|
var vertexType = configuration.getVertexTypeForPass(terrainPass);
|
||||||
for (var attr : vertexType.getVertexFormat().getAttributes()) {
|
for (var attr : ChunkVertexLayout.requireAttributes(vertexType.getLayout()).getAttributes()) {
|
||||||
builder.bindAttribute(attr.getName(), i++);
|
builder.bindAttribute(attr.getName(), i++);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return builder
|
return builder
|
||||||
.link((shader) -> {
|
.link((shader) -> {
|
||||||
|
|||||||
+20
-20
@@ -4,34 +4,34 @@ import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeFormat;
|
|||||||
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkMeshFormats;
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkMeshFormats;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexLayout;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Like HFPModelVertexType, but extended to support Iris. The extensions aren't particularly efficient right now.
|
* Like HFPModelVertexType, but extended to support Iris.
|
||||||
*/
|
*/
|
||||||
public class XHFPModelVertexType implements ChunkVertexType {
|
public class XHFPModelVertexType implements ChunkVertexType {
|
||||||
public static final ChunkVertexType BASE_VERTEX_TYPE = ChunkMeshFormats.VANILLA_LIKE;
|
public static final ChunkVertexType BASE_VERTEX_TYPE = ChunkMeshFormats.VANILLA_LIKE;
|
||||||
|
|
||||||
public static final int STRIDE = 48;
|
public static final int HEADER_STRIDE = 8;
|
||||||
public static final GlVertexFormat VERTEX_FORMAT = GlVertexFormat.builder(STRIDE)
|
public static final int VERTEX_STRIDE = 28;
|
||||||
// Exclude the rdh factor as shaders cannot use it
|
|
||||||
.addElements(BASE_VERTEX_TYPE.getVertexFormat().getAttributes().stream().filter(a -> !a.getName().equals("a_RdhFactor")).toList())
|
/**
|
||||||
.addElement("mc_midTexCoord", GlVertexFormat.NEXT_ALIGNED_POINTER, GlVertexAttributeFormat.UNSIGNED_SHORT, 2, false, false)
|
* Packs the block's position within its section (4 bits per axis), whether {@code at_midBlock} has an offset
|
||||||
.addElement("at_tangent", GlVertexFormat.NEXT_ALIGNED_POINTER, GlVertexAttributeFormat.BYTE, 4, true, false)
|
* (bit 12), and the block's light emission (bits 16 to 23).
|
||||||
.addElement("iris_Normal", GlVertexFormat.NEXT_ALIGNED_POINTER, GlVertexAttributeFormat.BYTE, 3, true, false)
|
*/
|
||||||
.addElement("mc_Entity", GlVertexFormat.NEXT_ALIGNED_POINTER, GlVertexAttributeFormat.SHORT, 2, false, false)
|
public static final String BLOCK_INFO = "celeritas_BlockInfo";
|
||||||
.addElement("at_midBlock", GlVertexFormat.NEXT_ALIGNED_POINTER, GlVertexAttributeFormat.BYTE, 4, false, false)
|
|
||||||
|
public static final GlVertexFormat HEADER_FORMAT = GlVertexFormat.builder(HEADER_STRIDE)
|
||||||
|
.addElement("mc_Entity", 0, GlVertexAttributeFormat.SHORT, 2, false, false)
|
||||||
|
.addElement(BLOCK_INFO, 4, GlVertexAttributeFormat.UNSIGNED_INT, 1, false, true)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
private static final int TEXTURE_MAX_VALUE = 32768;
|
public static final GlVertexFormat VERTEX_FORMAT = GlVertexFormat.builder(VERTEX_STRIDE)
|
||||||
|
.addElements(ChunkVertexLayout.requireAttributes(BASE_VERTEX_TYPE.getLayout()).getAttributes().stream().filter(a -> !a.getName().equals("a_RdhFactor")).toList())
|
||||||
public static final float MID_TEX_SCALE = 1.0f / TEXTURE_MAX_VALUE;
|
.build();
|
||||||
|
|
||||||
public static int encodeTexture(float u, float v) {
|
|
||||||
return ((Math.round(u * TEXTURE_MAX_VALUE) & 0xFFFF) << 0) |
|
|
||||||
((Math.round(v * TEXTURE_MAX_VALUE) & 0xFFFF) << 16);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
public static final ChunkVertexLayout LAYOUT = ChunkVertexLayout.withHeader(VERTEX_FORMAT, HEADER_FORMAT, 4);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public float getTextureScale() {
|
public float getTextureScale() {
|
||||||
@@ -49,8 +49,8 @@ public class XHFPModelVertexType implements ChunkVertexType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public GlVertexFormat getVertexFormat() {
|
public ChunkVertexLayout getLayout() {
|
||||||
return VERTEX_FORMAT;
|
return LAYOUT;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
+25
-66
@@ -14,28 +14,21 @@ import org.embeddedt.embeddium.impl.modern.render.chunk.ContextAwareChunkVertexE
|
|||||||
import org.embeddedt.embeddium.impl.modern.render.chunk.compile.pipeline.BlockRenderContext;
|
import org.embeddedt.embeddium.impl.modern.render.chunk.compile.pipeline.BlockRenderContext;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
|
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
|
||||||
import net.irisshaders.iris.vertices.ExtendedDataHelper;
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.impl.VanillaLikeChunkVertex;
|
||||||
import net.irisshaders.iris.vertices.NormI8;
|
|
||||||
import net.irisshaders.iris.vertices.NormalHelper;
|
|
||||||
import org.embeddedt.embeddium.impl.render.texture.TextureAtlasExtended;
|
import org.embeddedt.embeddium.impl.render.texture.TextureAtlasExtended;
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
import org.joml.Vector3f;
|
|
||||||
import org.lwjgl.system.MemoryUtil;
|
import org.lwjgl.system.MemoryUtil;
|
||||||
import org.taumc.celeritas.shaders.CeleritasShaders;
|
import org.taumc.celeritas.shaders.CeleritasShaders;
|
||||||
|
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
import static net.irisshaders.iris.compat.sodium.impl.vertex_format.terrain_xhfp.XHFPModelVertexType.STRIDE;
|
import static net.irisshaders.iris.compat.sodium.impl.vertex_format.terrain_xhfp.XHFPModelVertexType.HEADER_STRIDE;
|
||||||
|
import static net.irisshaders.iris.compat.sodium.impl.vertex_format.terrain_xhfp.XHFPModelVertexType.VERTEX_STRIDE;
|
||||||
|
|
||||||
public class XHFPTerrainVertex implements ChunkVertexEncoder, ContextAwareChunkVertexEncoder {
|
public class XHFPTerrainVertex implements ChunkVertexEncoder, ContextAwareChunkVertexEncoder {
|
||||||
|
|
||||||
private final QuadViewTerrain.QuadViewTerrainUnsafe quad = new QuadViewTerrain.QuadViewTerrainUnsafe();
|
|
||||||
private final Vector3f normal = new Vector3f();
|
|
||||||
|
|
||||||
private int vertexCount;
|
|
||||||
private float uSum;
|
|
||||||
private float vSum;
|
|
||||||
|
|
||||||
private static final BlockState AIR = Blocks.AIR.defaultBlockState();
|
private static final BlockState AIR = Blocks.AIR.defaultBlockState();
|
||||||
|
|
||||||
@@ -56,13 +49,8 @@ public class XHFPTerrainVertex implements ChunkVertexEncoder, ContextAwareChunkV
|
|||||||
|
|
||||||
private final FallbackTextureMaterials fallbackMaterials = WorldRenderingSettings.INSTANCE.getFallbackTextureMaterialMapping();
|
private final FallbackTextureMaterials fallbackMaterials = WorldRenderingSettings.INSTANCE.getFallbackTextureMaterialMapping();
|
||||||
|
|
||||||
private final ChunkVertexEncoder baseEncoder = XHFPModelVertexType.BASE_VERTEX_TYPE.createEncoder();
|
private static final int MC_ENTITY_OFFSET = XHFPModelVertexType.HEADER_FORMAT.getAttribute("mc_Entity").getPointer();
|
||||||
|
private static final int BLOCK_INFO_OFFSET = XHFPModelVertexType.HEADER_FORMAT.getAttribute(XHFPModelVertexType.BLOCK_INFO).getPointer();
|
||||||
private static final int MID_TEX_OFFSET = XHFPModelVertexType.VERTEX_FORMAT.getAttribute("mc_midTexCoord").getPointer();
|
|
||||||
private static final int MC_ENTITY_OFFSET = XHFPModelVertexType.VERTEX_FORMAT.getAttribute("mc_Entity").getPointer();
|
|
||||||
private static final int MID_BLOCK_OFFSET = XHFPModelVertexType.VERTEX_FORMAT.getAttribute("at_midBlock").getPointer();
|
|
||||||
private static final int NORMAL_OFFSET = XHFPModelVertexType.VERTEX_FORMAT.getAttribute("iris_Normal").getPointer();
|
|
||||||
private static final int TANGENT_OFFSET = XHFPModelVertexType.VERTEX_FORMAT.getAttribute("at_tangent").getPointer();
|
|
||||||
|
|
||||||
private static final ClassValue<AtomicBoolean> GET_APPEARANCE_CRASHED = new ClassValue<>() {
|
private static final ClassValue<AtomicBoolean> GET_APPEARANCE_CRASHED = new ClassValue<>() {
|
||||||
@Override
|
@Override
|
||||||
@@ -150,73 +138,44 @@ public class XHFPTerrainVertex implements ChunkVertexEncoder, ContextAwareChunkV
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public long write(long ptr,
|
public long writePrimitive(long ptr, Material material, Vertex[] vertices, int chunkId) {
|
||||||
Material material, Vertex vertex, int chunkId) {
|
long vertexPtr = ptr + HEADER_STRIDE;
|
||||||
|
float uSum = 0.0f;
|
||||||
|
float vSum = 0.0f;
|
||||||
|
|
||||||
|
for (Vertex vertex : vertices) {
|
||||||
uSum += vertex.u;
|
uSum += vertex.u;
|
||||||
vSum += vertex.v;
|
vSum += vertex.v;
|
||||||
vertexCount++;
|
|
||||||
|
|
||||||
vertex.rdhFactor = 0;
|
VanillaLikeChunkVertex.writeVertexWithoutRdhFactor(vertexPtr, material, vertex, chunkId);
|
||||||
this.baseEncoder.write(ptr, material, vertex, chunkId);
|
|
||||||
|
|
||||||
MemoryUtil.memPutShort(ptr + MC_ENTITY_OFFSET + 2, renderType);
|
vertexPtr += VERTEX_STRIDE;
|
||||||
MemoryUtil.memPutInt(ptr + MID_BLOCK_OFFSET, ignoreMidBlock ? 0 : ExtendedDataHelper.computeMidBlock(vertex.x, vertex.y, vertex.z, localPosX, localPosY, localPosZ));
|
}
|
||||||
MemoryUtil.memPutByte(ptr + MID_BLOCK_OFFSET + 3, lightValue);
|
|
||||||
|
|
||||||
if (vertexCount == 4) {
|
float midU = uSum / vertices.length;
|
||||||
vertexCount = 0;
|
float midV = vSum / vertices.length;
|
||||||
|
|
||||||
uSum *= 0.25f;
|
|
||||||
vSum *= 0.25f;
|
|
||||||
|
|
||||||
int midUV = XHFPModelVertexType.encodeTexture(uSum, vSum);
|
|
||||||
|
|
||||||
MemoryUtil.memPutInt(ptr + MID_TEX_OFFSET, midUV);
|
|
||||||
MemoryUtil.memPutInt(ptr + MID_TEX_OFFSET - STRIDE, midUV);
|
|
||||||
MemoryUtil.memPutInt(ptr + MID_TEX_OFFSET - STRIDE * 2, midUV);
|
|
||||||
MemoryUtil.memPutInt(ptr + MID_TEX_OFFSET - STRIDE * 3, midUV);
|
|
||||||
|
|
||||||
short blockId = this.blockId;
|
short blockId = this.blockId;
|
||||||
|
|
||||||
if (blockId == -1 && fallbackMaterials != null) {
|
if (blockId == -1 && fallbackMaterials != null) {
|
||||||
// Try to fall back to the "canonical" block ID for the texture, this can often greatly improve
|
// Try to fall back to the "canonical" block ID for the texture, this can often greatly improve
|
||||||
// the visuals of facade-style blocks
|
// the visuals of facade-style blocks
|
||||||
TextureAtlasSprite sprite = ((TextureAtlasExtended)blocksAtlas).celeritas$findFromUV(uSum, vSum);
|
TextureAtlasSprite sprite = ((TextureAtlasExtended)blocksAtlas).celeritas$findFromUV(midU, midV);
|
||||||
if (sprite != null) {
|
if (sprite != null) {
|
||||||
blockId = (short) fallbackMaterials.getFallbackId(sprite, this.blockState);
|
blockId = (short) fallbackMaterials.getFallbackId(sprite, this.blockState);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
MemoryUtil.memPutShort(ptr + MC_ENTITY_OFFSET, blockId);
|
MemoryUtil.memPutShort(ptr + MC_ENTITY_OFFSET, blockId);
|
||||||
MemoryUtil.memPutShort(ptr + MC_ENTITY_OFFSET - STRIDE, blockId);
|
MemoryUtil.memPutShort(ptr + MC_ENTITY_OFFSET + 2, renderType);
|
||||||
MemoryUtil.memPutShort(ptr + MC_ENTITY_OFFSET - STRIDE * 2, blockId);
|
|
||||||
MemoryUtil.memPutShort(ptr + MC_ENTITY_OFFSET - STRIDE * 3, blockId);
|
|
||||||
|
|
||||||
uSum = 0;
|
// Vertex positions are relative to the section, so only the block's position within it is needed
|
||||||
vSum = 0;
|
MemoryUtil.memPutInt(ptr + BLOCK_INFO_OFFSET, (localPosX & 15)
|
||||||
|
| ((localPosY & 15) << 4)
|
||||||
|
| ((localPosZ & 15) << 8)
|
||||||
|
| (ignoreMidBlock ? 0 : 1 << 12)
|
||||||
|
| ((lightValue & 0xFF) << 16));
|
||||||
|
|
||||||
// normal computation
|
return vertexPtr;
|
||||||
// Implementation based on the algorithm found here:
|
|
||||||
// https://github.com/IrisShaders/ShaderDoc/blob/master/vertex-format-extensions.md#surface-normal-vector
|
|
||||||
|
|
||||||
quad.setup(ptr, STRIDE);
|
|
||||||
NormalHelper.computeFaceNormal(normal, quad);
|
|
||||||
int packedNormal = NormI8.pack(normal);
|
|
||||||
|
|
||||||
|
|
||||||
MemoryUtil.memPutInt(ptr + NORMAL_OFFSET, packedNormal);
|
|
||||||
MemoryUtil.memPutInt(ptr + NORMAL_OFFSET - STRIDE, packedNormal);
|
|
||||||
MemoryUtil.memPutInt(ptr + NORMAL_OFFSET - STRIDE * 2, packedNormal);
|
|
||||||
MemoryUtil.memPutInt(ptr + NORMAL_OFFSET - STRIDE * 3, packedNormal);
|
|
||||||
|
|
||||||
int tangent = NormalHelper.computeTangent(normal.x, normal.y, normal.z, quad);
|
|
||||||
|
|
||||||
MemoryUtil.memPutInt(ptr + TANGENT_OFFSET, tangent);
|
|
||||||
MemoryUtil.memPutInt(ptr + TANGENT_OFFSET - STRIDE, tangent);
|
|
||||||
MemoryUtil.memPutInt(ptr + TANGENT_OFFSET - STRIDE * 2, tangent);
|
|
||||||
MemoryUtil.memPutInt(ptr + TANGENT_OFFSET - STRIDE * 3, tangent);
|
|
||||||
}
|
|
||||||
|
|
||||||
return ptr + STRIDE;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-2
@@ -335,7 +335,7 @@ public class IrisRenderingPipeline implements WorldRenderingPipeline, ShaderRend
|
|||||||
() -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent;
|
() -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent;
|
||||||
|
|
||||||
IntFunction<ProgramSamplers> createTerrainSamplers = (programId) -> {
|
IntFunction<ProgramSamplers> createTerrainSamplers = (programId) -> {
|
||||||
ProgramSamplers.Builder builder = ProgramSamplers.builder(programId, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS);
|
ProgramSamplers.Builder builder = IrisSamplers.terrainSamplerBuilder(programId);
|
||||||
|
|
||||||
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap().getOrDefault(TextureStage.GBUFFERS_AND_SHADOW, Object2ObjectMaps.emptyMap()));
|
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap().getOrDefault(TextureStage.GBUFFERS_AND_SHADOW, Object2ObjectMaps.emptyMap()));
|
||||||
|
|
||||||
@@ -378,7 +378,7 @@ public class IrisRenderingPipeline implements WorldRenderingPipeline, ShaderRend
|
|||||||
this.dhCompat = new DHCompat(this, shadowDirectives.isDhShadowEnabled().orElse(true));
|
this.dhCompat = new DHCompat(this, shadowDirectives.isDhShadowEnabled().orElse(true));
|
||||||
|
|
||||||
IntFunction<ProgramSamplers> createShadowTerrainSamplers = (programId) -> {
|
IntFunction<ProgramSamplers> createShadowTerrainSamplers = (programId) -> {
|
||||||
ProgramSamplers.Builder builder = ProgramSamplers.builder(programId, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS);
|
ProgramSamplers.Builder builder = IrisSamplers.terrainSamplerBuilder(programId);
|
||||||
|
|
||||||
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap().getOrDefault(TextureStage.GBUFFERS_AND_SHADOW, Object2ObjectMaps.emptyMap()));
|
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap().getOrDefault(TextureStage.GBUFFERS_AND_SHADOW, Object2ObjectMaps.emptyMap()));
|
||||||
|
|
||||||
|
|||||||
+175
-29
@@ -1,6 +1,7 @@
|
|||||||
package net.irisshaders.iris.pipeline.foss_transform;
|
package net.irisshaders.iris.pipeline.foss_transform;
|
||||||
|
|
||||||
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
|
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
|
||||||
|
import net.irisshaders.iris.compat.sodium.impl.vertex_format.terrain_xhfp.XHFPModelVertexType;
|
||||||
import net.irisshaders.iris.gl.blending.AlphaTest;
|
import net.irisshaders.iris.gl.blending.AlphaTest;
|
||||||
import net.irisshaders.iris.pipeline.transform.Patch;
|
import net.irisshaders.iris.pipeline.transform.Patch;
|
||||||
import net.irisshaders.iris.pipeline.transform.parameter.Parameters;
|
import net.irisshaders.iris.pipeline.transform.parameter.Parameters;
|
||||||
@@ -10,7 +11,11 @@ import net.irisshaders.iris.shaderpack.preprocessor.JcppProcessor;
|
|||||||
import org.apache.commons.lang3.mutable.MutableObject;
|
import org.apache.commons.lang3.mutable.MutableObject;
|
||||||
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
|
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
|
||||||
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
|
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkMeshFormats;
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkMeshFormats;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexLayout;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchGenerator;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchMode;
|
||||||
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
|
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
|
||||||
import org.taumc.glsl.ShaderParser;
|
import org.taumc.glsl.ShaderParser;
|
||||||
import org.taumc.glsl.ShaderPrinter;
|
import org.taumc.glsl.ShaderPrinter;
|
||||||
@@ -124,6 +129,7 @@ public class ShaderTransformer {
|
|||||||
EnumMap<ShaderType, String> result = new EnumMap<>(ShaderType.class);
|
EnumMap<ShaderType, String> result = new EnumMap<>(ShaderType.class);
|
||||||
EnumMap<ShaderType, Transformer> types = new EnumMap<>(ShaderType.class);
|
EnumMap<ShaderType, Transformer> types = new EnumMap<>(ShaderType.class);
|
||||||
EnumMap<ShaderType, String> prepatched = new EnumMap<>(ShaderType.class);
|
EnumMap<ShaderType, String> prepatched = new EnumMap<>(ShaderType.class);
|
||||||
|
Map<String, VertexFetchGenerator.GlslType> vertexInputTypes = new HashMap<>();
|
||||||
|
|
||||||
for (ShaderType type : ShaderType.values()) {
|
for (ShaderType type : ShaderType.values()) {
|
||||||
parameters.type = type;
|
parameters.type = type;
|
||||||
@@ -223,6 +229,11 @@ public class ShaderTransformer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
CompTransformer.transformEach(transformer, parameters);
|
CompTransformer.transformEach(transformer, parameters);
|
||||||
|
|
||||||
|
if (patchType == Patch.SODIUM && type == ShaderType.VERTEX) {
|
||||||
|
vertexInputTypes.putAll(takeLayoutInputs(transformer, ((SodiumParameters) parameters).vertexType.getLayout()));
|
||||||
|
}
|
||||||
|
|
||||||
types.put(type, transformer);
|
types.put(type, transformer);
|
||||||
|
|
||||||
var extensions = versionPattern.matcher(getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim();
|
var extensions = versionPattern.matcher(getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim();
|
||||||
@@ -235,7 +246,7 @@ public class ShaderTransformer {
|
|||||||
String header = prepatched.get(entry.getKey());
|
String header = prepatched.get(entry.getKey());
|
||||||
if (entry.getKey() == ShaderType.VERTEX && patchType == Patch.SODIUM) {
|
if (entry.getKey() == ShaderType.VERTEX && patchType == Patch.SODIUM) {
|
||||||
// Inject _vert_init contents
|
// Inject _vert_init contents
|
||||||
header += computeCeleritasHeader((SodiumParameters)parameters);
|
header += computeCeleritasHeader((SodiumParameters)parameters, vertexInputTypes);
|
||||||
}
|
}
|
||||||
String formattedShader = getFormattedShader(tree, header);
|
String formattedShader = getFormattedShader(tree, header);
|
||||||
result.put(entry.getKey(), formattedShader);
|
result.put(entry.getKey(), formattedShader);
|
||||||
@@ -244,11 +255,51 @@ public class ShaderTransformer {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String computeCeleritasHeader(SodiumParameters parameters) {
|
/**
|
||||||
|
* Removes the vertex stage's declarations of inputs that the layout provides, and returns the types they were declared
|
||||||
|
* with. The generated header then declares those inputs with the same types.
|
||||||
|
*/
|
||||||
|
private static Map<String, VertexFetchGenerator.GlslType> takeLayoutInputs(Transformer translationUnit, ChunkVertexLayout layout) {
|
||||||
|
Set<String> layoutNames = new HashSet<>();
|
||||||
|
layout.vertex().getAttributes().forEach(attribute -> layoutNames.add(attribute.getName()));
|
||||||
|
|
||||||
|
if (layout.header() != null) {
|
||||||
|
layout.header().format().getAttributes().forEach(attribute -> layoutNames.add(attribute.getName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, VertexFetchGenerator.GlslType> declaredTypes = new HashMap<>();
|
||||||
|
|
||||||
|
for (int qualifier : new int[] { GLSLLexer.IN, GLSLLexer.ATTRIBUTE }) {
|
||||||
|
translationUnit.findQualifiers(qualifier).forEach((name, declaration) -> {
|
||||||
|
if (!layoutNames.contains(name)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var specifier = declaration.fully_specified_type().type_specifier();
|
||||||
|
|
||||||
|
if (specifier.array_specifier() != null) {
|
||||||
|
throw new IllegalStateException("Vertex input " + name + " cannot be declared as an array");
|
||||||
|
}
|
||||||
|
|
||||||
|
declaredTypes.put(name, VertexFetchGenerator.GlslType.parse(specifier.type_specifier_nonarray().getText()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
declaredTypes.keySet().forEach(translationUnit::removeVariable);
|
||||||
|
|
||||||
|
return declaredTypes;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String computeCeleritasHeader(SodiumParameters parameters, Map<String, VertexFetchGenerator.GlslType> vertexInputTypes) {
|
||||||
var defines = parameters.vertexType.getDefines();
|
var defines = parameters.vertexType.getDefines();
|
||||||
String chunkVertexHeader = org.embeddedt.embeddium.impl.gl.shader.ShaderParser.parseShader(ShaderLoader.getShaderSource("sodium:include/chunk_vertex.glsl"), ShaderLoader::getShaderSource,
|
var generatedSources = VertexFetchGenerator.sources(parameters.vertexType.getLayout(),
|
||||||
|
QuadPrimitiveType.TRIANGULATED.getVerticesPerPrimitive(), parameters.vertexFetchMode, false, vertexInputTypes);
|
||||||
|
String chunkVertexHeader = org.embeddedt.embeddium.impl.gl.shader.ShaderParser.parseShader(ShaderLoader.getShaderSource("sodium:include/chunk_vertex.glsl"), ShaderLoader.sourceProvider(generatedSources),
|
||||||
ShaderConstants.builder().addAll(defines).build());
|
ShaderConstants.builder().addAll(defines).build());
|
||||||
return "\n\n" + chunkVertexHeader + "\n\n";
|
String quadInputFunctions = parameters.vertexFetchMode == VertexFetchMode.PULLED
|
||||||
|
? String.join("\n\n", QUAD_INPUT_FUNCTIONS) + "\n\n"
|
||||||
|
: "";
|
||||||
|
return "\n\n" + chunkVertexHeader + "\n\n" + quadInputFunctions;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void patchVanillaCore(Transformer translationUnit, VanillaParameters parameters) {
|
private static void patchVanillaCore(Transformer translationUnit, VanillaParameters parameters) {
|
||||||
@@ -274,35 +325,130 @@ public class ShaderTransformer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void replaceMidTexCoord(Transformer translationUnit, float textureScale) {
|
/**
|
||||||
int type = translationUnit.findType("mc_midTexCoord");
|
* XHFP doesn't store {@code at_midBlock}: it is derived from the block's position within its section, which the vertex
|
||||||
if (type != 0) {
|
* position is relative to, and stored in 1/64ths of a block with the block's light emission in {@code w}.
|
||||||
translationUnit.removeVariable("mc_midTexCoord");
|
*/
|
||||||
}
|
public static void replaceMidBlock(Transformer translationUnit, SodiumParameters parameters) {
|
||||||
translationUnit.replaceExpression("mc_midTexCoord", "iris_MidTex");
|
if (!(parameters.vertexType instanceof XHFPModelVertexType)) {
|
||||||
switch (type) {
|
|
||||||
case 0:
|
|
||||||
return;
|
return;
|
||||||
case GLSLLexer.BOOL:
|
|
||||||
return;
|
|
||||||
case GLSLLexer.FLOAT:
|
|
||||||
translationUnit.injectFunction("float iris_MidTex = (mc_midTexCoord.x * " + textureScale + ").x;"); //TODO go back to variable if order is fixed
|
|
||||||
break;
|
|
||||||
case GLSLLexer.VEC2:
|
|
||||||
translationUnit.injectFunction("vec2 iris_MidTex = (mc_midTexCoord.xy * " + textureScale + ").xy;");
|
|
||||||
break;
|
|
||||||
case GLSLLexer.VEC3:
|
|
||||||
translationUnit.injectFunction("vec3 iris_MidTex = vec3(mc_midTexCoord.xy * " + textureScale + ", 0.0);");
|
|
||||||
break;
|
|
||||||
case GLSLLexer.VEC4:
|
|
||||||
translationUnit.injectFunction("vec4 iris_MidTex = vec4(mc_midTexCoord.xy * " + textureScale + ", 0.0, 1.0);");
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
translationUnit.injectVariable("in vec2 mc_midTexCoord;"); //TODO why is this inserted oddly?
|
var declaredType = findInputType(translationUnit, "at_midBlock");
|
||||||
|
|
||||||
|
if (declaredType == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
translationUnit.removeVariable("at_midBlock");
|
||||||
|
translationUnit.injectVariable(declaredType + " at_midBlock;");
|
||||||
|
translationUnit.injectFunction(String.join("\n",
|
||||||
|
"vec4 iris_ComputeMidBlock() {",
|
||||||
|
" uint info = " + XHFPModelVertexType.BLOCK_INFO + ";",
|
||||||
|
" vec3 block = vec3(uvec3(info, info >> 4u, info >> 8u) & uvec3(15u));",
|
||||||
|
" vec3 offset = (info & 0x1000u) != 0u ? (block + 0.5 - _vert_position) * 64.0 : vec3(0.0);",
|
||||||
|
" return vec4(offset, float((info >> 16u) & 0xFFu));",
|
||||||
|
"}"));
|
||||||
|
// Assigned in main, after _vert_init has provided _vert_position
|
||||||
|
translationUnit.prependMain("at_midBlock = " + declaredType.adapt("iris_ComputeMidBlock()", VertexFetchGenerator.GlslType.parse("vec4")) + ";");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inputs that are constant across a quad and that pulled formats can compute from its corners, with the GLSL
|
||||||
|
* computing each.
|
||||||
|
*/
|
||||||
|
private static final Map<String, Map.Entry<VertexFetchGenerator.GlslType, String>> QUAD_INPUTS = Map.of(
|
||||||
|
"iris_Normal", Map.entry(VertexFetchGenerator.GlslType.parse("vec3"), "iris_ComputeFaceNormal()"),
|
||||||
|
"at_tangent", Map.entry(VertexFetchGenerator.GlslType.parse("vec4"), "iris_ComputeTangent()"),
|
||||||
|
"mc_midTexCoord", Map.entry(VertexFetchGenerator.GlslType.parse("vec2"), "iris_ComputeMidTexCoord()"));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirror NormalHelper#computeFaceNormal and NormalHelper#computeTangent, including leaving zero-length vectors as they
|
||||||
|
* are. Ordered so each function follows the ones it calls, which is why they go in the header rather than being
|
||||||
|
* injected: the transformer doesn't keep injected functions in order.
|
||||||
|
*/
|
||||||
|
private static final List<String> QUAD_INPUT_FUNCTIONS = List.of(
|
||||||
|
String.join("\n",
|
||||||
|
"vec3 iris_NormalizeOrZero(vec3 v) {",
|
||||||
|
" float lengthSquared = dot(v, v);",
|
||||||
|
" return lengthSquared == 0.0 ? v : v * inversesqrt(lengthSquared);",
|
||||||
|
"}"),
|
||||||
|
String.join("\n",
|
||||||
|
"vec3 iris_ComputeFaceNormal() {",
|
||||||
|
" vec3 p0 = _vert_corner_position(0);",
|
||||||
|
" vec3 p1 = _vert_corner_position(1);",
|
||||||
|
" vec3 p2 = _vert_corner_position(2);",
|
||||||
|
" vec3 p3 = _vert_corner_position(3);",
|
||||||
|
" return iris_NormalizeOrZero(cross(p2 - p0, p3 - p1));",
|
||||||
|
"}"),
|
||||||
|
String.join("\n",
|
||||||
|
"vec4 iris_ComputeTangent() {",
|
||||||
|
" vec3 normal = iris_ComputeFaceNormal();",
|
||||||
|
" vec3 p0 = _vert_corner_position(0);",
|
||||||
|
" vec2 t0 = _vert_corner_tex_coord(0);",
|
||||||
|
" vec3 edge1 = _vert_corner_position(1) - p0;",
|
||||||
|
" vec3 edge2 = _vert_corner_position(2) - p0;",
|
||||||
|
" vec2 delta1 = _vert_corner_tex_coord(1) - t0;",
|
||||||
|
" vec2 delta2 = _vert_corner_tex_coord(2) - t0;",
|
||||||
|
" float denom = delta1.x * delta2.y - delta2.x * delta1.y;",
|
||||||
|
" float f = denom == 0.0 ? 1.0 : 1.0 / denom;",
|
||||||
|
" vec3 tangent = iris_NormalizeOrZero(f * (delta2.y * edge1 - delta1.y * edge2));",
|
||||||
|
" vec3 bitangent = iris_NormalizeOrZero(f * (-delta2.x * edge1 + delta1.x * edge2));",
|
||||||
|
" return vec4(tangent, dot(bitangent, cross(tangent, normal)) < 0.0 ? -1.0 : 1.0);",
|
||||||
|
"}"),
|
||||||
|
String.join("\n",
|
||||||
|
"vec2 iris_ComputeMidTexCoord() {",
|
||||||
|
" vec2 sum = _vert_corner_tex_coord(0) + _vert_corner_tex_coord(1) + _vert_corner_tex_coord(2) + _vert_corner_tex_coord(3);",
|
||||||
|
" return sum * 0.25;",
|
||||||
|
"}"));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pulled formats can read every corner of a quad, so inputs that are constant across it are computed rather than
|
||||||
|
* stored when the layout lacks them. Must run after {@link #patchMultiTexCoord3}, which can declare
|
||||||
|
* {@code mc_midTexCoord}, and before {@code _vert_init()} is prepended to main.
|
||||||
|
*/
|
||||||
|
public static void replaceQuadInputs(Transformer translationUnit, SodiumParameters parameters) {
|
||||||
|
if (parameters.vertexFetchMode != VertexFetchMode.PULLED) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var layout = parameters.vertexType.getLayout();
|
||||||
|
Set<String> storedNames = new HashSet<>();
|
||||||
|
layout.vertex().getAttributes().forEach(attribute -> storedNames.add(attribute.getName()));
|
||||||
|
|
||||||
|
if (layout.header() != null) {
|
||||||
|
layout.header().format().getAttributes().forEach(attribute -> storedNames.add(attribute.getName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var entry : QUAD_INPUTS.entrySet()) {
|
||||||
|
String name = entry.getKey();
|
||||||
|
|
||||||
|
if (storedNames.contains(name)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var declaredType = findInputType(translationUnit, name);
|
||||||
|
|
||||||
|
if (declaredType == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
translationUnit.removeVariable(name);
|
||||||
|
translationUnit.injectVariable(declaredType + " " + name + ";");
|
||||||
|
translationUnit.prependMain(name + " = " + declaredType.adapt(entry.getValue().getValue(), entry.getValue().getKey()) + ";");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static VertexFetchGenerator.GlslType findInputType(Transformer translationUnit, String name) {
|
||||||
|
for (int qualifier : new int[] { GLSLLexer.IN, GLSLLexer.ATTRIBUTE }) {
|
||||||
|
var declaration = translationUnit.findQualifiers(qualifier).get(name);
|
||||||
|
|
||||||
|
if (declaration != null) {
|
||||||
|
return VertexFetchGenerator.GlslType.parse(declaration.fully_specified_type().type_specifier().getText());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void addIfNotExists(Transformer translationUnit, String name, String code) {
|
public static void addIfNotExists(Transformer translationUnit, String name, String code) {
|
||||||
|
|||||||
+5
-4
@@ -1,6 +1,5 @@
|
|||||||
package net.irisshaders.iris.pipeline.foss_transform;
|
package net.irisshaders.iris.pipeline.foss_transform;
|
||||||
|
|
||||||
import net.irisshaders.iris.compat.sodium.impl.vertex_format.terrain_xhfp.XHFPModelVertexType;
|
|
||||||
import net.irisshaders.iris.pipeline.transform.parameter.SodiumParameters;
|
import net.irisshaders.iris.pipeline.transform.parameter.SodiumParameters;
|
||||||
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
|
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
|
||||||
import org.taumc.glsl.Transformer;
|
import org.taumc.glsl.Transformer;
|
||||||
@@ -28,7 +27,8 @@ public class SodiumTransformer {
|
|||||||
translationUnit.rename("vaUV2", "_vert_tex_light_coord");
|
translationUnit.rename("vaUV2", "_vert_tex_light_coord");
|
||||||
|
|
||||||
translationUnit.replaceExpression("textureMatrix", "mat4(1.0f)");
|
translationUnit.replaceExpression("textureMatrix", "mat4(1.0f)");
|
||||||
replaceMidTexCoord(translationUnit, XHFPModelVertexType.MID_TEX_SCALE);
|
replaceMidBlock(translationUnit, parameters);
|
||||||
|
replaceQuadInputs(translationUnit, parameters);
|
||||||
|
|
||||||
injectVertInit(translationUnit, parameters);
|
injectVertInit(translationUnit, parameters);
|
||||||
}
|
}
|
||||||
@@ -37,8 +37,6 @@ public class SodiumTransformer {
|
|||||||
public static void patchSodium(Transformer translationUnit, SodiumParameters parameters) {
|
public static void patchSodium(Transformer translationUnit, SodiumParameters parameters) {
|
||||||
commonPatch(translationUnit, parameters, false);
|
commonPatch(translationUnit, parameters, false);
|
||||||
|
|
||||||
replaceMidTexCoord(translationUnit, XHFPModelVertexType.MID_TEX_SCALE);
|
|
||||||
|
|
||||||
translationUnit.replaceExpression("gl_TextureMatrix[0]", "mat4(1.0f)");
|
translationUnit.replaceExpression("gl_TextureMatrix[0]", "mat4(1.0f)");
|
||||||
translationUnit.replaceExpression("gl_TextureMatrix[1]", "iris_LightmapTextureMatrix");
|
translationUnit.replaceExpression("gl_TextureMatrix[1]", "iris_LightmapTextureMatrix");
|
||||||
translationUnit.injectFunction("uniform mat4 iris_LightmapTextureMatrix;");
|
translationUnit.injectFunction("uniform mat4 iris_LightmapTextureMatrix;");
|
||||||
@@ -98,6 +96,9 @@ public class SodiumTransformer {
|
|||||||
"vec4 getVertexPosition() { return vec4(_vert_position + u_RegionOffset + _get_draw_translation(_draw_id), 1.0f); }");
|
"vec4 getVertexPosition() { return vec4(_vert_position + u_RegionOffset + _get_draw_translation(_draw_id), 1.0f); }");
|
||||||
translationUnit.replaceExpression("gl_Vertex", "getVertexPosition()");
|
translationUnit.replaceExpression("gl_Vertex", "getVertexPosition()");
|
||||||
|
|
||||||
|
replaceMidBlock(translationUnit, parameters);
|
||||||
|
replaceQuadInputs(translationUnit, parameters);
|
||||||
|
|
||||||
// inject here so that _vert_position is available to the above. (injections
|
// inject here so that _vert_position is available to the above. (injections
|
||||||
// inject in reverse order if performed piece-wise but in correct order if
|
// inject in reverse order if performed piece-wise but in correct order if
|
||||||
// performed as an array of injections)
|
// performed as an array of injections)
|
||||||
|
|||||||
+1
-1
@@ -60,7 +60,7 @@ public class TransformPatcherBridge {
|
|||||||
AlphaTest alpha, ShaderAttributeInputs inputs,
|
AlphaTest alpha, ShaderAttributeInputs inputs,
|
||||||
Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap, TerrainRenderPass pass) {
|
Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap, TerrainRenderPass pass) {
|
||||||
return transform(name, sources,
|
return transform(name, sources,
|
||||||
new SodiumParameters(Patch.SODIUM, textureMap, alpha, inputs, pass.vertexType()));
|
new SodiumParameters(Patch.SODIUM, textureMap, alpha, inputs, pass.vertexType(), pass.vertexFetchMode()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Map<ShaderType, String> patchComposite(
|
public static Map<ShaderType, String> patchComposite(
|
||||||
|
|||||||
+5
-1
@@ -10,23 +10,27 @@ import net.irisshaders.iris.pipeline.transform.Patch;
|
|||||||
import net.irisshaders.iris.shaderpack.texture.TextureStage;
|
import net.irisshaders.iris.shaderpack.texture.TextureStage;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
||||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchMode;
|
||||||
|
|
||||||
@EqualsAndHashCode(callSuper = true)
|
@EqualsAndHashCode(callSuper = true)
|
||||||
public class SodiumParameters extends Parameters {
|
public class SodiumParameters extends Parameters {
|
||||||
public final ShaderAttributeInputs inputs;
|
public final ShaderAttributeInputs inputs;
|
||||||
public final AlphaTest alpha;
|
public final AlphaTest alpha;
|
||||||
public final ChunkVertexType vertexType;
|
public final ChunkVertexType vertexType;
|
||||||
|
public final VertexFetchMode vertexFetchMode;
|
||||||
|
|
||||||
public SodiumParameters(Patch patch,
|
public SodiumParameters(Patch patch,
|
||||||
Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap,
|
Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap,
|
||||||
AlphaTest alpha,
|
AlphaTest alpha,
|
||||||
ShaderAttributeInputs inputs,
|
ShaderAttributeInputs inputs,
|
||||||
ChunkVertexType vertexType) {
|
ChunkVertexType vertexType,
|
||||||
|
VertexFetchMode vertexFetchMode) {
|
||||||
super(patch, textureMap);
|
super(patch, textureMap);
|
||||||
this.inputs = inputs;
|
this.inputs = inputs;
|
||||||
|
|
||||||
this.alpha = alpha;
|
this.alpha = alpha;
|
||||||
this.vertexType = vertexType;
|
this.vertexType = vertexType;
|
||||||
|
this.vertexFetchMode = vertexFetchMode;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ package net.irisshaders.iris.samplers;
|
|||||||
|
|
||||||
import com.google.common.collect.ImmutableList;
|
import com.google.common.collect.ImmutableList;
|
||||||
import com.google.common.collect.ImmutableSet;
|
import com.google.common.collect.ImmutableSet;
|
||||||
|
import com.mojang.blaze3d.platform.GlStateManager;
|
||||||
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
|
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
|
||||||
import net.irisshaders.iris.gl.image.GlImage;
|
import net.irisshaders.iris.gl.image.GlImage;
|
||||||
|
import net.irisshaders.iris.gl.program.ProgramSamplers;
|
||||||
import net.irisshaders.iris.gl.sampler.GlSampler;
|
import net.irisshaders.iris.gl.sampler.GlSampler;
|
||||||
import net.irisshaders.iris.gl.sampler.SamplerHolder;
|
import net.irisshaders.iris.gl.sampler.SamplerHolder;
|
||||||
import net.irisshaders.iris.gl.state.StateUpdateNotifiers;
|
import net.irisshaders.iris.gl.state.StateUpdateNotifiers;
|
||||||
@@ -16,6 +18,8 @@ import net.irisshaders.iris.shadows.ShadowRenderTargets;
|
|||||||
import net.irisshaders.iris.targets.RenderTarget;
|
import net.irisshaders.iris.targets.RenderTarget;
|
||||||
import net.irisshaders.iris.targets.RenderTargets;
|
import net.irisshaders.iris.targets.RenderTargets;
|
||||||
import net.minecraft.client.renderer.texture.AbstractTexture;
|
import net.minecraft.client.renderer.texture.AbstractTexture;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.DefaultChunkRenderer;
|
||||||
|
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchGenerator;
|
||||||
|
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.function.IntSupplier;
|
import java.util.function.IntSupplier;
|
||||||
@@ -28,6 +32,14 @@ public class IrisSamplers {
|
|||||||
|
|
||||||
public static final ImmutableSet<Integer> WORLD_RESERVED_TEXTURE_UNITS = ImmutableSet.of(0, 1, 2);
|
public static final ImmutableSet<Integer> WORLD_RESERVED_TEXTURE_UNITS = ImmutableSet.of(0, 1, 2);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Terrain programs that pull vertex data also reserve the unit Celeritas binds it to.
|
||||||
|
*/
|
||||||
|
private static final ImmutableSet<Integer> PULLED_TERRAIN_RESERVED_TEXTURE_UNITS = ImmutableSet.<Integer>builder()
|
||||||
|
.addAll(WORLD_RESERVED_TEXTURE_UNITS)
|
||||||
|
.add(DefaultChunkRenderer.VERTEX_DATA_TEXTURE_UNIT)
|
||||||
|
.build();
|
||||||
|
|
||||||
// TODO: In composite programs, there shouldn't be any reserved textures.
|
// TODO: In composite programs, there shouldn't be any reserved textures.
|
||||||
// We need a way to restore these texture bindings.
|
// We need a way to restore these texture bindings.
|
||||||
public static final ImmutableSet<Integer> COMPOSITE_RESERVED_TEXTURE_UNITS = ImmutableSet.of(1, 2);
|
public static final ImmutableSet<Integer> COMPOSITE_RESERVED_TEXTURE_UNITS = ImmutableSet.of(1, 2);
|
||||||
@@ -40,6 +52,23 @@ public class IrisSamplers {
|
|||||||
// no construction allowed
|
// no construction allowed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts the samplers of a Celeritas terrain program. Units are only reserved for vertex data when the program reads
|
||||||
|
* it, so that other programs keep every unit for the pack.
|
||||||
|
*/
|
||||||
|
public static ProgramSamplers.Builder terrainSamplerBuilder(int programId) {
|
||||||
|
boolean pulled = GlStateManager._glGetUniformLocation(programId, VertexFetchGenerator.VERTEX_DATA_SAMPLER) != -1;
|
||||||
|
|
||||||
|
if (!pulled) {
|
||||||
|
return ProgramSamplers.builder(programId, WORLD_RESERVED_TEXTURE_UNITS);
|
||||||
|
}
|
||||||
|
|
||||||
|
ProgramSamplers.Builder builder = ProgramSamplers.builder(programId, PULLED_TERRAIN_RESERVED_TEXTURE_UNITS);
|
||||||
|
builder.addExternalSampler(DefaultChunkRenderer.VERTEX_DATA_TEXTURE_UNIT, VertexFetchGenerator.VERTEX_DATA_SAMPLER);
|
||||||
|
|
||||||
|
return builder;
|
||||||
|
}
|
||||||
|
|
||||||
public static void initRenderer() {
|
public static void initRenderer() {
|
||||||
SHADOW_SAMPLER_NEAREST = new GlSampler(false, false, true, true);
|
SHADOW_SAMPLER_NEAREST = new GlSampler(false, false, true, true);
|
||||||
SHADOW_SAMPLER_LINEAR = new GlSampler(true, false, true, true);
|
SHADOW_SAMPLER_LINEAR = new GlSampler(true, false, true, true);
|
||||||
|
|||||||
Reference in new issue
Block a user