Improve terrain fog quality and refactor cloud rendering #52

Merged
embeddedt merged 8 commits from rdh/celeritas:sky-fog into stonecutter 2026-11-19 21:51:49 -05:00
21 changed files with 943 additions and 668 deletions
Showing only changes of commit ffab197dab - Show all commits

No files matched your search

@@ -23,10 +23,14 @@ public class GlBufferTexture extends GlObject {
* are compared by identity, because a deleted buffer's name may be reused by the buffer that replaces it. * 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) { public void bind(TextureBufferFunctions functions, GlBuffer buffer) {
this.bind(functions, buffer, GL30.GL_R32UI);
}
public void bind(TextureBufferFunctions functions, GlBuffer buffer, int internalFormat) {
LWJGL.glBindTexture(GL31.GL_TEXTURE_BUFFER, this.handle()); LWJGL.glBindTexture(GL31.GL_TEXTURE_BUFFER, this.handle());
if (this.attachedBuffer != buffer) { if (this.attachedBuffer != buffer) {
functions.texBuffer(GL31.GL_TEXTURE_BUFFER, GL30.GL_R32UI, buffer); functions.texBuffer(GL31.GL_TEXTURE_BUFFER, internalFormat, buffer);
this.attachedBuffer = buffer; this.attachedBuffer = buffer;
} }
} }
@@ -56,14 +56,6 @@ public final class SkyTextureCopy {
this.valid = true; this.valid = true;
} }
public void bind() {
if (!this.valid) {
return;
}
this.glState.bindTexture(DefaultChunkRenderer.SKY_TEXTURE_UNIT, GL11.GL_TEXTURE_2D, this.texture);
}
public void delete() { public void delete() {
if (this.texture != 0) { if (this.texture != 0) {
LWJGL.glDeleteTextures(this.texture); LWJGL.glDeleteTextures(this.texture);
@@ -0,0 +1,20 @@
package org.embeddedt.embeddium.impl.render.clouds;
import org.joml.Matrix4fc;
/**
* What the platform knows about the clouds for one frame.
*
* @param modelView the camera rotation, without translation
* @param cloudHeight the height of the bottom of the clouds
* @param ticks the game time in ticks, including the partial tick
* @param red the cloud color
* @param range how far clouds are drawn, in blocks
* @param fogEnd the distance at which clouds have faded out completely
*/
public record CloudFrame(Matrix4fc modelView, Matrix4fc projection,
double cameraX, double cameraY, double cameraZ,
float cloudHeight, double ticks,
float red, float green, float blue,
boolean fancy, float range, float fogEnd) {
}
@@ -0,0 +1,15 @@
package org.embeddedt.embeddium.impl.render.clouds;
/**
* Sets up the GL state clouds are drawn with. Platforms implement this so they can use their own render state objects
* and keep their state caches in sync.
*/
public interface CloudRenderState {
/**
* Sets up blending and depth testing and writing. Fancy clouds are drawn with back face culling, fast clouds
* without.
*/
void setup(boolean fancy);
void restore();
}
@@ -0,0 +1,400 @@
package org.embeddedt.embeddium.impl.render.clouds;
import org.embeddedt.embeddium.impl.gl.array.GlVertexArray;
import org.embeddedt.embeddium.impl.gl.buffer.GlBufferTarget;
import org.embeddedt.embeddium.impl.gl.buffer.GlBufferUsage;
import org.embeddedt.embeddium.impl.gl.buffer.GlMutableBuffer;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.gl.shader.GlProgram;
import org.embeddedt.embeddium.impl.gl.shader.GlShader;
import org.embeddedt.embeddium.impl.gl.shader.ShaderBindingContext;
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat3v;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat4v;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformInt;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix4f;
import org.embeddedt.embeddium.impl.gl.state.GlStateService;
import org.embeddedt.embeddium.impl.gl.texture.GlBufferTexture;
import org.embeddedt.embeddium.impl.render.chunk.SharedQuadIndexBuffer;
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType;
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
import org.taumc.celeritas.lwjgl.GL11;
import org.taumc.celeritas.lwjgl.GL12;
import org.taumc.celeritas.lwjgl.GL13;
import org.taumc.celeritas.lwjgl.GL30;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
/**
* Draws clouds without vertex data, like vanilla since 1.21.6. The visible faces are written to a buffer texture, and
* the vertex shader builds each vertex from {@code gl_VertexID}. The face format matches vanilla's, so shader packs can
* generate the same vertices. Unlike vanilla, each cell is tinted by its pixel in the clouds texture.
*/
public final class CloudRenderer {
public static final int FACES_TEXTURE_UNIT = 3;
public static final int COLORS_TEXTURE_UNIT = 4;
private static final int DIRECTION_DOWN = 0;
private static final int DIRECTION_UP = 1;
private static final int DIRECTION_NORTH = 2;
private static final int DIRECTION_SOUTH = 3;
private static final int DIRECTION_WEST = 4;
private static final int DIRECTION_EAST = 5;
private static final int FLAG_INSIDE_FACE = 1 << 4;
private static final int FLAG_USE_TOP_COLOR = 1 << 5;
// A 256 px clouds texture makes 12 block cells
private static final float TEXTURE_SIZE_IN_BLOCKS = 3072.0f;
private static final float CLOUD_THICKNESS = 4.0f;
private static final float CLOUD_ALPHA = 0.8f;
private static final double BLOCKS_PER_TICK = 0.03;
private static final int BYTES_PER_FACE = 3 * Short.BYTES;
private enum CameraPosition {
ABOVE_CLOUDS,
INSIDE_CLOUDS,
BELOW_CLOUDS
}
private final GlStateService glState;
private final CloudTexture texture;
private final float cellSizeX, cellSizeZ;
private final GlProgram<ShaderInterface> program;
private final GlMutableBuffer faceBuffer;
private final GlBufferTexture faceTexture;
private final SharedQuadIndexBuffer indexBuffer;
private final GlVertexArray vertexArray;
private final int colorTexture;
private ByteBuffer faceData = ByteBuffer.allocateDirect(1024 * BYTES_PER_FACE).order(ByteOrder.nativeOrder());
private int faceCount;
private boolean needsRebuild = true;
private int prevCellX, prevCellZ, prevRadius;
private CameraPosition prevCameraPosition;
private boolean prevFancy;
private int centerCellX, centerCellZ;
private float offsetX, offsetY, offsetZ;
public CloudRenderer(CommandList commandList, GlStateService glState, CloudTexture texture) {
this.glState = glState;
this.texture = texture;
this.cellSizeX = TEXTURE_SIZE_IN_BLOCKS / texture.width;
this.cellSizeZ = TEXTURE_SIZE_IN_BLOCKS / texture.height;
this.program = createProgram();
this.faceBuffer = commandList.createMutableBuffer();
this.faceTexture = new GlBufferTexture();
this.indexBuffer = new SharedQuadIndexBuffer(commandList, QuadPrimitiveType.TRIANGULATED);
this.vertexArray = new GlVertexArray();
this.colorTexture = this.createColorTexture();
}
/**
* Updates the faces for the frame.
*
* @return whether there is anything to draw
*/
public boolean prepare(CommandList commandList, CloudFrame frame) {
double textureWidthBlocks = this.texture.width * this.cellSizeX;
double textureHeightBlocks = this.texture.height * this.cellSizeZ;
double cloudX = frame.cameraX() + frame.ticks() * BLOCKS_PER_TICK;
double cloudZ = frame.cameraZ() + 3.96;
cloudX -= Math.floor(cloudX / textureWidthBlocks) * textureWidthBlocks;
cloudZ -= Math.floor(cloudZ / textureHeightBlocks) * textureHeightBlocks;
int cellX = (int) Math.floor(cloudX / this.cellSizeX);
int cellZ = (int) Math.floor(cloudZ / this.cellSizeZ);
float relativeBottomY = frame.cloudHeight() - (float) frame.cameraY() + 0.33f;
float relativeTopY = relativeBottomY + CLOUD_THICKNESS;
CameraPosition cameraPosition;
if (relativeTopY < 0.0f) {
cameraPosition = CameraPosition.ABOVE_CLOUDS;
} else if (relativeBottomY > 0.0f) {
cameraPosition = CameraPosition.BELOW_CLOUDS;
} else {
cameraPosition = CameraPosition.INSIDE_CLOUDS;
}
int radius = (int) Math.ceil(frame.range() / Math.min(this.cellSizeX, this.cellSizeZ));
if (this.needsRebuild || cellX != this.prevCellX || cellZ != this.prevCellZ || radius != this.prevRadius
|| cameraPosition != this.prevCameraPosition || frame.fancy() != this.prevFancy) {
this.needsRebuild = false;
this.prevCellX = cellX;
this.prevCellZ = cellZ;
this.prevRadius = radius;
this.prevCameraPosition = cameraPosition;
this.prevFancy = frame.fancy();
this.buildFaces(cameraPosition, cellX, cellZ, frame.fancy(), radius);
this.faceData.flip();
commandList.uploadData(this.faceBuffer, this.faceData, GlBufferUsage.DYNAMIC_DRAW);
this.indexBuffer.ensureCapacity(commandList, this.faceCount * 6);
}
this.centerCellX = cellX;
this.centerCellZ = cellZ;
this.offsetX = -(float) (cloudX - cellX * this.cellSizeX);
this.offsetY = relativeBottomY;
this.offsetZ = -(float) (cloudZ - cellZ * this.cellSizeZ);
return this.faceCount != 0;
}
/**
* Draws the faces from {@link #prepare} with our own program.
*/
public void render(CommandList commandList, CloudRenderState state, CloudFrame frame) {
state.setup(frame.fancy());
this.program.bind();
this.program.getInterface().setup(this, frame);
this.bindTextures();
this.draw(commandList);
this.program.unbind();
state.restore();
}
/**
* Binds the faces to {@link #FACES_TEXTURE_UNIT} and the cell colors to {@link #COLORS_TEXTURE_UNIT}.
*/
public void bindTextures() {
this.glState.bindTexture(COLORS_TEXTURE_UNIT, GL11.GL_TEXTURE_2D, this.colorTexture);
int previous = this.glState.activateTextureUnit(GL13.GL_TEXTURE0 + FACES_TEXTURE_UNIT);
this.faceTexture.bind(RenderDevice.INSTANCE.getDeviceFunctions().textureBufferFunctions(), this.faceBuffer, GL30.GL_R16I);
this.glState.activateTextureUnit(previous);
}
/**
* Draws the faces with the bound program.
*/
public void draw(CommandList commandList) {
commandList.bindVertexArray(this.vertexArray);
commandList.bindBuffer(GlBufferTarget.ELEMENT_BUFFER, this.indexBuffer.getBufferObject());
LWJGL.glDrawElementsBaseVertex(GL11.GL_TRIANGLES, this.faceCount * 6, GL11.GL_UNSIGNED_INT, 0L, 0);
commandList.unbindVertexArray();
}
public int getCenterCellX() {
return this.centerCellX;
}
public int getCenterCellZ() {
return this.centerCellZ;
}
public float getOffsetX() {
return this.offsetX;
}
public float getOffsetY() {
return this.offsetY;
}
public float getOffsetZ() {
return this.offsetZ;
}
public float getCellSizeX() {
return this.cellSizeX;
}
public float getCellSizeZ() {
return this.cellSizeZ;
}
public float getCellHeight() {
return CLOUD_THICKNESS;
}
public static float getAlpha() {
return CLOUD_ALPHA;
}
public void delete(CommandList commandList) {
this.program.delete();
commandList.deleteBuffer(this.faceBuffer);
this.faceTexture.delete();
this.indexBuffer.delete(commandList);
commandList.deleteVertexArray(this.vertexArray);
LWJGL.glDeleteTextures(this.colorTexture);
}
private void buildFaces(CameraPosition cameraPosition, int centerCellX, int centerCellZ, boolean fancy, int radius) {
this.faceData.clear();
this.faceCount = 0;
// Rings of cells around the camera, so the faces are drawn front to back
for (int ring = 0; ring <= 2 * radius; ring++) {
for (int x = -ring; x <= ring; x++) {
int z = ring - Math.abs(x);
if (z > radius || x * x + z * z > radius * radius) {
continue;
}
if (z != 0) {
this.buildCell(cameraPosition, centerCellX, centerCellZ, fancy, x, -z);
}
this.buildCell(cameraPosition, centerCellX, centerCellZ, fancy, x, z);
}
}
}
private void buildCell(CameraPosition cameraPosition, int centerCellX, int centerCellZ, boolean fancy, int x, int z) {
int cell = this.texture.cell(centerCellX + x, centerCellZ + z);
if (cell == 0) {
return;
}
if (!fancy) {
this.addFace(x, z, DIRECTION_DOWN, FLAG_USE_TOP_COLOR);
return;
}
if (cameraPosition != CameraPosition.BELOW_CLOUDS) {
this.addFace(x, z, DIRECTION_UP, 0);
}
if (cameraPosition != CameraPosition.ABOVE_CLOUDS) {
this.addFace(x, z, DIRECTION_DOWN, 0);
}
// Only the sides that face the camera
if ((cell & CloudTexture.OPEN_NORTH) != 0 && z > 0) {
this.addFace(x, z, DIRECTION_NORTH, 0);
}
if ((cell & CloudTexture.OPEN_SOUTH) != 0 && z < 0) {
this.addFace(x, z, DIRECTION_SOUTH, 0);
}
if ((cell & CloudTexture.OPEN_WEST) != 0 && x > 0) {
this.addFace(x, z, DIRECTION_WEST, 0);
}
if ((cell & CloudTexture.OPEN_EAST) != 0 && x < 0) {
this.addFace(x, z, DIRECTION_EAST, 0);
}
// Seen from inside the clouds
if (Math.abs(x) <= 1 && Math.abs(z) <= 1) {
for (int direction = DIRECTION_DOWN; direction <= DIRECTION_EAST; direction++) {
this.addFace(x, z, direction, FLAG_INSIDE_FACE);
}
}
}
private void addFace(int x, int z, int direction, int flags) {
if (this.faceData.remaining() < BYTES_PER_FACE) {
ByteBuffer grown = ByteBuffer.allocateDirect(this.faceData.capacity() * 2).order(ByteOrder.nativeOrder());
this.faceData.flip();
grown.put(this.faceData);
this.faceData = grown;
}
// The low bits of the cell position are stored with the flags, as vanilla does
int directionAndFlags = direction | flags | ((x & 1) << 7) | ((z & 1) << 6);
this.faceData.putShort((short) (x >> 1));
this.faceData.putShort((short) (z >> 1));
this.faceData.putShort((short) directionAndFlags);
this.faceCount++;
}
private int createColorTexture() {
int texture = LWJGL.glGenTextures();
ByteBuffer pixels = ByteBuffer.allocateDirect(this.texture.pixels.length * 4).order(ByteOrder.LITTLE_ENDIAN);
// ABGR as little endian ints is RGBA in memory
pixels.asIntBuffer().put(this.texture.pixels);
this.glState.bindTexture(COLORS_TEXTURE_UNIT, GL11.GL_TEXTURE_2D, texture);
int previous = this.glState.activateTextureUnit(GL13.GL_TEXTURE0 + COLORS_TEXTURE_UNIT);
LWJGL.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 4);
LWJGL.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, 0);
LWJGL.glPixelStorei(GL11.GL_UNPACK_SKIP_ROWS, 0);
LWJGL.glPixelStorei(GL11.GL_UNPACK_SKIP_PIXELS, 0);
LWJGL.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, this.texture.width, this.texture.height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixels);
LWJGL.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
LWJGL.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
LWJGL.glTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LEVEL, 0);
this.glState.activateTextureUnit(previous);
return texture;
}
private static GlProgram<ShaderInterface> createProgram() {
ShaderConstants constants = ShaderConstants.builder().build();
GlShader vertexShader = ShaderLoader.loadShader(ShaderType.VERTEX, "sodium:clouds/clouds.vsh", constants);
GlShader fragmentShader = ShaderLoader.loadShader(ShaderType.FRAGMENT, "sodium:clouds/clouds.fsh", constants);
try {
return GlProgram.builder("celeritas:clouds")
.attachShader(vertexShader)
.attachShader(fragmentShader)
.bindFragmentData("fragColor", 0)
.link(ShaderInterface::new);
} finally {
vertexShader.delete();
fragmentShader.delete();
}
}
private static final class ShaderInterface {
private final GlUniformMatrix4f modelViewMatrix, projectionMatrix;
private final GlUniformFloat4v colorModulator;
private final GlUniformFloat3v cloudOffset, cellSize;
private final GlUniformInt centerCellX, centerCellZ;
private final GlUniformFloat fogEnd;
private final GlUniformInt facesSampler, colorsSampler;
private ShaderInterface(ShaderBindingContext context) {
this.modelViewMatrix = context.bindUniform("ModelViewMat", GlUniformMatrix4f::new);
this.projectionMatrix = context.bindUniform("ProjMat", GlUniformMatrix4f::new);
this.colorModulator = context.bindUniform("ColorModulator", GlUniformFloat4v::new);
this.cloudOffset = context.bindUniform("CloudOffset", GlUniformFloat3v::new);
this.cellSize = context.bindUniform("CellSize", GlUniformFloat3v::new);
this.centerCellX = context.bindUniform("CenterCellX", GlUniformInt::new);
this.centerCellZ = context.bindUniform("CenterCellZ", GlUniformInt::new);
this.fogEnd = context.bindUniform("FogEnd", GlUniformFloat::new);
this.facesSampler = context.bindUniform("CloudFaces", GlUniformInt::new);
this.colorsSampler = context.bindUniform("CloudColors", GlUniformInt::new);
}
private void setup(CloudRenderer renderer, CloudFrame frame) {
this.modelViewMatrix.set(frame.modelView());
this.projectionMatrix.set(frame.projection());
this.colorModulator.set(new float[] { frame.red(), frame.green(), frame.blue(), CLOUD_ALPHA });
this.cloudOffset.set(renderer.offsetX, renderer.offsetY, renderer.offsetZ);
this.cellSize.set(renderer.cellSizeX, CLOUD_THICKNESS, renderer.cellSizeZ);
this.centerCellX.setInt(renderer.centerCellX);
this.centerCellZ.setInt(renderer.centerCellZ);
this.fogEnd.setFloat(frame.fogEnd());
this.facesSampler.setInt(FACES_TEXTURE_UNIT);
this.colorsSampler.setInt(COLORS_TEXTURE_UNIT);
}
}
}
@@ -0,0 +1,78 @@
package org.embeddedt.embeddium.impl.render.clouds;
/**
* The cells of the clouds texture, one per pixel.
*/
public final class CloudTexture {
static final int OPEN_NORTH = 1;
static final int OPEN_SOUTH = 2;
static final int OPEN_WEST = 4;
static final int OPEN_EAST = 8;
static final int FILLED = 16;
final int width, height;
final int[] pixels;
final byte[] cells;
/**
* @param pixels the pixels in rows along X, packed as ABGR (as {@code NativeImage#getPixelRGBA} returns them)
*/
public CloudTexture(int width, int height, int[] pixels) {
if (pixels.length != width * height) {
throw new IllegalArgumentException("Expected " + (width * height) + " pixels, got " + pixels.length);
}
this.width = width;
this.height = height;
this.pixels = pixels;
this.cells = new byte[pixels.length];
for (int z = 0; z < height; z++) {
for (int x = 0; x < width; x++) {
int pixel = this.pixel(x, z);
if (!isFilled(pixel)) {
continue;
}
// A side is open where the neighbor differs. Between two filled cells of different colors, only the
// side of the cell to the south or east is open, so the boundary is drawn once.
int flags = FILLED;
int north = this.pixel(x, z - 1);
int south = this.pixel(x, z + 1);
int west = this.pixel(x - 1, z);
int east = this.pixel(x + 1, z);
if (north != pixel) {
flags |= OPEN_NORTH;
}
if (!isFilled(south) && south != pixel) {
flags |= OPEN_SOUTH;
}
if (west != pixel) {
flags |= OPEN_WEST;
}
if (!isFilled(east) && east != pixel) {
flags |= OPEN_EAST;
}
this.cells[x + z * width] = (byte) flags;
}
}
}
int cell(int x, int z) {
return this.cells[Math.floorMod(x, this.width) + Math.floorMod(z, this.height) * this.width];
}
private int pixel(int x, int z) {
return this.pixels[Math.floorMod(x, this.width) + Math.floorMod(z, this.height) * this.width];
}
private static boolean isFilled(int abgr) {
return (abgr >>> 24) > 1;
}
}
@@ -1,23 +1,26 @@
#version 150 #version 150
#import <sodium:include/fog.glsl> uniform float FogEnd;
uniform mat4 ProjMat;
uniform vec4 ColorModulator;
in vec4 vertexColor; in vec4 vertexColor;
in float vertexDistance; in float vertexDistance;
out vec4 fragColor; out vec4 fragColor;
// Custom cloud fog algorithm by Balint, for use in Sodium
void main() { void main() {
vec4 color = vertexColor * ColorModulator; vec4 color = vertexColor;
if (color.a < 0.1) { if (color.a < 0.1) {
discard; discard;
} }
fragColor = _linearFog(color, vertexDistance, u_FogColor, u_FogStart, u_FogEnd); // Clouds fade out over their own range instead of using terrain fog, like vanilla since 1.21.6
} color.a *= 1.0 - clamp(vertexDistance / FogEnd, 0.0, 1.0);
// Faded out clouds must not write depth
if (color.a < 1.0 / 255.0) {
discard;
}
fragColor = color;
}
@@ -1,18 +1,67 @@
#version 150 #version 150
in vec3 Position; const int FLAG_MASK_DIR = 7;
in vec4 Color; const int FLAG_INSIDE_FACE = 1 << 4;
const int FLAG_USE_TOP_COLOR = 1 << 5;
const int FLAG_EXTRA_Z = 1 << 6;
const int FLAG_EXTRA_X = 1 << 7;
uniform mat4 ModelViewMat; uniform mat4 ModelViewMat;
uniform mat4 ProjMat; uniform mat4 ProjMat;
uniform vec4 ColorModulator;
uniform vec3 CloudOffset;
uniform vec3 CellSize;
uniform int CenterCellX;
uniform int CenterCellZ;
uniform isamplerBuffer CloudFaces;
uniform sampler2D CloudColors;
out float vertexDistance; out float vertexDistance;
out vec4 vertexColor; out vec4 vertexColor;
// Custom cloud fog algorithm by Balint, for use in Sodium const vec3[] vertices = vec3[](
// Bottom face
vec3(1, 0, 0), vec3(1, 0, 1), vec3(0, 0, 1), vec3(0, 0, 0),
// Top face
vec3(0, 1, 0), vec3(0, 1, 1), vec3(1, 1, 1), vec3(1, 1, 0),
// North face
vec3(0, 0, 0), vec3(0, 1, 0), vec3(1, 1, 0), vec3(1, 0, 0),
// South face
vec3(1, 0, 1), vec3(1, 1, 1), vec3(0, 1, 1), vec3(0, 0, 1),
// West face
vec3(0, 0, 1), vec3(0, 1, 1), vec3(0, 1, 0), vec3(0, 0, 0),
// East face
vec3(1, 0, 0), vec3(1, 1, 0), vec3(1, 1, 1), vec3(1, 0, 1)
);
const float[] faceShades = float[](0.7, 1.0, 0.8, 0.8, 0.9, 0.9);
int wrap(int value, int size) {
return value - size * int(floor(float(value) / float(size)));
}
void main() { void main() {
gl_Position = ProjMat * ModelViewMat * vec4(Position, 1.0); int quadVertex = gl_VertexID % 4;
vec4 pos = ModelViewMat * vec4(Position.x, 0.0, Position.z, 1.0); int index = (gl_VertexID / 4) * 3;
vertexDistance = length(pos.xyz);
vertexColor = Color; int cellX = texelFetch(CloudFaces, index).r;
int cellZ = texelFetch(CloudFaces, index + 1).r;
int dirAndFlags = texelFetch(CloudFaces, index + 2).r;
int direction = dirAndFlags & FLAG_MASK_DIR;
bool isInsideFace = (dirAndFlags & FLAG_INSIDE_FACE) == FLAG_INSIDE_FACE;
bool useTopColor = (dirAndFlags & FLAG_USE_TOP_COLOR) == FLAG_USE_TOP_COLOR;
cellX = (cellX << 1) | ((dirAndFlags & FLAG_EXTRA_X) >> 7);
cellZ = (cellZ << 1) | ((dirAndFlags & FLAG_EXTRA_Z) >> 6);
vec3 faceVertex = vertices[(direction * 4) + (isInsideFace ? 3 - quadVertex : quadVertex)];
vec3 pos = (faceVertex * CellSize) + (vec3(cellX, 0, cellZ) * CellSize) + CloudOffset;
gl_Position = ProjMat * ModelViewMat * vec4(pos, 1.0);
ivec2 textureSize = textureSize(CloudColors, 0);
ivec2 texel = ivec2(wrap(CenterCellX + cellX, textureSize.x), wrap(CenterCellZ + cellZ, textureSize.y));
float shade = useTopColor ? faceShades[1] : faceShades[direction];
vertexDistance = length(pos);
vertexColor = texelFetch(CloudColors, texel, 0) * vec4(vec3(shade), 1.0) * ColorModulator;
} }
@@ -124,10 +124,6 @@ public class FogHelper implements FogService {
this.skyTexture.copy(target.width, target.height); this.skyTexture.copy(target.width, target.height);
} }
public void bindSkyTexture() {
this.skyTexture.bind();
}
public void invalidateSkyTexture() { public void invalidateSkyTexture() {
this.skyTexture.invalidate(); this.skyTexture.invalidate();
} }
@@ -5,7 +5,7 @@ import com.mojang.blaze3d.vertex.PoseStack;
import org.embeddedt.embeddium.api.math.JomlHelper; import org.embeddedt.embeddium.api.math.JomlHelper;
import org.embeddedt.embeddium.impl.Celeritas; import org.embeddedt.embeddium.impl.Celeritas;
import org.embeddedt.embeddium.impl.gui.SodiumGameOptions; import org.embeddedt.embeddium.impl.gui.SodiumGameOptions;
import org.embeddedt.embeddium.impl.render.immediate.CloudRenderer; import org.embeddedt.embeddium.impl.render.immediate.ModernCloudRenderer;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.renderer.LevelRenderer; import net.minecraft.client.renderer.LevelRenderer;
@@ -32,7 +32,7 @@ public class WorldRendererMixin {
private Minecraft minecraft; private Minecraft minecraft;
@Unique @Unique
private CloudRenderer cloudRenderer; private ModernCloudRenderer cloudRenderer;
/** /**
* @author jellysquid3 * @author jellysquid3
@@ -41,7 +41,7 @@ public class WorldRendererMixin {
@Inject(method = "renderClouds", at = @At(value = "INVOKE", target = "Ljava/lang/Float;isNaN(F)Z", ordinal = 0), cancellable = true) @Inject(method = "renderClouds", at = @At(value = "INVOKE", target = "Ljava/lang/Float;isNaN(F)Z", ordinal = 0), cancellable = true)
public void renderCloudsFast(PoseStack matrices, /*? if >=1.20.6 {*/ /*Matrix4f modelViewMatrix, *//*?}*/ Matrix4f projectionMatrix, float tickDelta, double x, double y, double z, CallbackInfo ci) { public void renderCloudsFast(PoseStack matrices, /*? if >=1.20.6 {*/ /*Matrix4f modelViewMatrix, *//*?}*/ Matrix4f projectionMatrix, float tickDelta, double x, double y, double z, CallbackInfo ci) {
if (this.cloudRenderer == null) { if (this.cloudRenderer == null) {
this.cloudRenderer = new CloudRenderer(this.minecraft.getResourceManager()); this.cloudRenderer = new ModernCloudRenderer(this.minecraft.getResourceManager());
} }
boolean renderFasterClouds = Celeritas.options().performance.useFasterClouds; boolean renderFasterClouds = Celeritas.options().performance.useFasterClouds;
@@ -1,501 +0,0 @@
package org.embeddedt.embeddium.impl.render.immediate;
//? if >=1.17 {
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*;
import net.minecraft.client.renderer.RenderType;
import org.embeddedt.embeddium.api.util.ColorABGR;
import org.embeddedt.embeddium.api.util.ColorARGB;
import org.embeddedt.embeddium.api.util.ColorMixer;
import org.embeddedt.embeddium.api.util.NormI8;
import org.embeddedt.embeddium.api.vertex.buffer.VertexBufferWriter;
import net.minecraft.client.CloudStatus;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.ResourceProvider;
import net.minecraft.util.Mth;
import net.minecraft.world.phys.Vec3;
import org.embeddedt.embeddium.api.render.clouds.ModifyCloudRenderingEvent;
import org.embeddedt.embeddium.api.vertex.format.common.LineVertex;
import org.embeddedt.embeddium.impl.render.ShaderModBridge;
import org.embeddedt.embeddium.impl.render.CeleritasWorldRenderer;
import org.embeddedt.embeddium.impl.util.ResourceLocationUtil;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.lwjgl.opengl.GL30C;
import org.lwjgl.system.MemoryStack;
import java.io.IOException;
import java.io.InputStream;
public class CloudRenderer {
private static final ResourceLocation CLOUDS_TEXTURE_ID = ResourceLocationUtil.make("textures/environment/clouds.png");
private static final int CLOUD_COLOR_NEG_Y = ColorABGR.pack(0.7F, 0.7F, 0.7F, 1.0f);
private static final int CLOUD_COLOR_POS_Y = ColorABGR.pack(1.0f, 1.0f, 1.0f, 1.0f);
private static final int CLOUD_COLOR_NEG_X = ColorABGR.pack(0.9F, 0.9F, 0.9F, 1.0f);
private static final int CLOUD_COLOR_POS_X = ColorABGR.pack(0.9F, 0.9F, 0.9F, 1.0f);
private static final int CLOUD_COLOR_NEG_Z = ColorABGR.pack(0.8F, 0.8F, 0.8F, 1.0f);
private static final int CLOUD_COLOR_POS_Z = ColorABGR.pack(0.8F, 0.8F, 0.8F, 1.0f);
private static final int DIR_NEG_Y = 1 << 0;
private static final int DIR_POS_Y = 1 << 1;
private static final int DIR_NEG_X = 1 << 2;
private static final int DIR_POS_X = 1 << 3;
private static final int DIR_NEG_Z = 1 << 4;
private static final int DIR_POS_Z = 1 << 5;
private static final int NORMAL_NEG_Y = NormI8.pack(0f, -1f, 0f);
private static final int NORMAL_POS_Y = NormI8.pack(0f, 1f, 0f);
private static final int NORMAL_NEG_Z = NormI8.pack(0f, 0f, -1f);
private static final int NORMAL_POS_Z = NormI8.pack(0f, 0f, 1f);
private static final int NORMAL_NEG_X = NormI8.pack(-1f, 0f, 0f);
private static final int NORMAL_POS_X = NormI8.pack(1f, 0f, 0f);
// 256x256 px cloud.png is 12x12 units
// 3072 / 256 = 12
// 3072 / 1024 = 3
private static final int MAX_SINGLE_CLOUD_SIZE = 3072;
// 256x256 px cloud.png starts fog 8x from cloud render distance
// 2048 / 256 = 8
// 2048 / 1024 = 2
private static final int CLOUD_PIXELS_TO_FOG_DISTANCE = 2048;
// 256x256 px cloud.png results in a minimum render distance of 32
// 256 / 8 = 32
// 1024 / 8 = 128
private static final float CLOUD_PIXELS_TO_MINIMUM_RENDER_DISTANCE = 0.125F;
// 256x256 px cloud.png results in render distance multiplier of 2
// 256 / 128 = 2
// 1024 / 128 = 8
private static final float CLOUD_PIXELS_TO_MAXIMUM_RENDER_DISTANCE = 0.0078125F;
private VertexBuffer vertexBuffer;
private CloudEdges edges;
private CloudShader shader;
private int prevCenterCellX, prevCenterCellY, cachedRenderDistance;
private float cloudSizeX, cloudSizeZ, fogDistanceMultiplier;
private int cloudDistanceMinimum, cloudDistanceMaximum;
private CloudStatus cloudRenderMode;
private boolean hasCloudGeometry;
public CloudRenderer(ResourceProvider factory) {
this.reloadTextures(factory);
}
private static int fireModifyCloudRenderDistanceEvent(int distance) {
var event = new ModifyCloudRenderingEvent(distance);
ModifyCloudRenderingEvent.BUS.post(event);
return event.getCloudRenderDistance();
}
private void drawVertexBuffer() {
//? if <1.19 {
/*BufferUploader.reset();
this.vertexBuffer.bindVertexArray();
this.vertexBuffer.bind();
this.vertexBuffer.getFormat().setupBufferState();
*///?}
this.vertexBuffer.draw();
//? if <1.19 {
/*this.vertexBuffer.getFormat().clearBufferState();
VertexBuffer.unbind();
VertexBuffer.unbindVertexArray();
*///?}
}
public void render(@Nullable ClientLevel world, LocalPlayer player, Matrix4f modelViewMatrix, Matrix4f projectionMatrix, float ticks, float tickDelta, double cameraX, double cameraY, double cameraZ) {
if (world == null) {
return;
}
float cloudHeight = world.effects().getCloudHeight();
// Vanilla uses NaN height as a way to disable cloud rendering
if (Float.isNaN(cloudHeight)) {
return;
}
Vec3 color = world.getCloudColor(tickDelta);
double cloudTime = (ticks + tickDelta) * 0.03F;
double cloudCenterX = (cameraX + cloudTime);
double cloudCenterZ = (cameraZ) + 3.96D;
int renderDistance = CeleritasWorldRenderer.instance().getEffectiveRenderDistance();
// This insanity (as opposed to just wrapping the call) is necessary to preserve the original assignment for mixin compat
renderDistance = fireModifyCloudRenderDistanceEvent(renderDistance);
int cloudDistance = Math.max(this.cloudDistanceMinimum, (renderDistance * this.cloudDistanceMaximum) + 9);
int centerCellX = (int) (Math.floor(cloudCenterX / this.cloudSizeX));
int centerCellZ = (int) (Math.floor(cloudCenterZ / this.cloudSizeZ));
if (this.vertexBuffer == null || this.prevCenterCellX != centerCellX || this.prevCenterCellY != centerCellZ || this.cachedRenderDistance != renderDistance || cloudRenderMode != Minecraft.getInstance().options.getCloudsType()) {
//? if <1.21 {
BufferBuilder bufferBuilder = Tesselator.getInstance().getBuilder();
bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR_NORMAL);
//?} else {
//BufferBuilder bufferBuilder = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR_NORMAL);
//?}
this.cloudRenderMode = Minecraft.getInstance().options.getCloudsType();
this.rebuildGeometry(bufferBuilder, cloudDistance, centerCellX, centerCellZ);
if (this.vertexBuffer == null) {
this.vertexBuffer = new VertexBuffer(/*? if >=1.20 {*/VertexBuffer.Usage.DYNAMIC /*?}*/);
}
this.vertexBuffer.bind();
//? if <1.21 {
//? if <1.19
//bufferBuilder.end();
this.vertexBuffer.upload(bufferBuilder /*? if >=1.19 {*/ .end() /*?}*/);
this.hasCloudGeometry = true;
//?} else {
/*MeshData meshData = bufferBuilder.build();
if(meshData != null) {
this.vertexBuffer.upload(meshData);
this.hasCloudGeometry = true;
} else {
this.hasCloudGeometry = false;
}
*///?}
VertexBuffer.unbind();
this.prevCenterCellX = centerCellX;
this.prevCenterCellY = centerCellZ;
this.cachedRenderDistance = renderDistance;
}
// Skip render path if there is no cloud geometry
if (!this.hasCloudGeometry) {
return;
}
float translateX = (float) (cloudCenterX - (centerCellX * this.cloudSizeX));
float translateZ = (float) (cloudCenterZ - (centerCellZ * this.cloudSizeZ));
RenderSystem.enableDepthTest();
this.vertexBuffer.bind();
boolean insideClouds = cameraY < cloudHeight + 4.5f && cameraY > cloudHeight - 0.5f;
boolean fastClouds = cloudRenderMode == CloudStatus.FAST;
if (insideClouds || fastClouds) {
RenderSystem.disableCull();
} else {
RenderSystem.enableCull();
}
modelViewMatrix = new Matrix4f(modelViewMatrix);
modelViewMatrix.translate(-translateX, cloudHeight - (float) cameraY + 0.33F, -translateZ);
// PASS 1: Set up depth buffer
//? if <1.21 {
RenderSystem.disableBlend();
RenderSystem.depthMask(true);
RenderSystem.colorMask(false, false, false, false);
//?} else {
//RenderType.cloudsDepthOnly().setupRenderState();
//?}
this.shader.prepareForDraw(modelViewMatrix, projectionMatrix, (float) color.x, (float) color.y, (float) color.z, 0.8f);
this.drawVertexBuffer();
this.shader.clear();
//? if >=1.21
//RenderType.cloudsDepthOnly().clearRenderState();
// PASS 2: Render geometry
//? if <1.21 {
RenderSystem.enableBlend();
RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
RenderSystem.depthMask(false);
RenderSystem.enableDepthTest();
RenderSystem.depthFunc(GL30C.GL_EQUAL);
RenderSystem.colorMask(true, true, true, true);
//?} else {
//RenderType.clouds().setupRenderState();
//?}
this.shader.prepareForDraw(modelViewMatrix, projectionMatrix, (float) color.x, (float) color.y, (float) color.z, 0.8f);
this.drawVertexBuffer();
this.shader.clear();
//? if >=1.21
//RenderType.clouds().clearRenderState();
VertexBuffer.unbind();
//? if <1.21 {
RenderSystem.disableBlend();
RenderSystem.depthFunc(GL30C.GL_LEQUAL);
RenderSystem.enableCull();
//?}
RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
}
private void rebuildGeometry(BufferBuilder bufferBuilder, int cloudDistance, int centerCellX, int centerCellZ) {
var writer = VertexBufferWriter.of(bufferBuilder);
boolean fastClouds = cloudRenderMode == CloudStatus.FAST;
for (int offsetX = -cloudDistance; offsetX < cloudDistance; offsetX++) {
for (int offsetZ = -cloudDistance; offsetZ < cloudDistance; offsetZ++) {
int connectedEdges = this.edges.getEdges(centerCellX + offsetX, centerCellZ + offsetZ);
if (connectedEdges == 0) {
continue;
}
int texel = this.edges.getColor(centerCellX + offsetX, centerCellZ + offsetZ);
float x = offsetX * this.cloudSizeX;
float z = offsetZ * this.cloudSizeZ;
try (MemoryStack stack = MemoryStack.stackPush()) {
final long buffer = stack.nmalloc((fastClouds ? 4 : (6 * 4)) * LineVertex.STRIDE);
long ptr = buffer;
int count = 0;
// -Y
if ((connectedEdges & DIR_NEG_Y) != 0) {
int mixedColor = ColorMixer.mul(texel, fastClouds ? CLOUD_COLOR_POS_Y : CLOUD_COLOR_NEG_Y);
ptr = writeVertex(ptr, x + this.cloudSizeX, 0.0f, z + this.cloudSizeZ, mixedColor, NORMAL_NEG_Y);
ptr = writeVertex(ptr, x + 0.0f, 0.0f, z + this.cloudSizeZ, mixedColor, NORMAL_NEG_Y);
ptr = writeVertex(ptr, x + 0.0f, 0.0f, z + 0.0f, mixedColor, NORMAL_NEG_Y);
ptr = writeVertex(ptr, x + this.cloudSizeX, 0.0f, z + 0.0f, mixedColor, NORMAL_NEG_Y);
count += 4;
}
// Only emit -Y geometry to emulate vanilla fast clouds
if (fastClouds) {
writer.push(stack, buffer, count, LineVertex.FORMAT);
continue;
}
// +Y
if ((connectedEdges & DIR_POS_Y) != 0) {
int mixedColor = ColorMixer.mul(texel, CLOUD_COLOR_POS_Y);
ptr = writeVertex(ptr, x + 0.0f, 4.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_Y);
ptr = writeVertex(ptr, x + this.cloudSizeX, 4.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_Y);
ptr = writeVertex(ptr, x + this.cloudSizeX, 4.0f, z + 0.0f, mixedColor, NORMAL_POS_Y);
ptr = writeVertex(ptr, x + 0.0f, 4.0f, z + 0.0f, mixedColor, NORMAL_POS_Y);
count += 4;
}
// -X
if ((connectedEdges & DIR_NEG_X) != 0) {
int mixedColor = ColorMixer.mul(texel, CLOUD_COLOR_NEG_X);
ptr = writeVertex(ptr, x + 0.0f, 0.0f, z + this.cloudSizeZ, mixedColor, NORMAL_NEG_X);
ptr = writeVertex(ptr, x + 0.0f, 4.0f, z + this.cloudSizeZ, mixedColor, NORMAL_NEG_X);
ptr = writeVertex(ptr, x + 0.0f, 4.0f, z + 0.0f, mixedColor, NORMAL_NEG_X);
ptr = writeVertex(ptr, x + 0.0f, 0.0f, z + 0.0f, mixedColor, NORMAL_NEG_X);
count += 4;
}
// +X
if ((connectedEdges & DIR_POS_X) != 0) {
int mixedColor = ColorMixer.mul(texel, CLOUD_COLOR_POS_X);
ptr = writeVertex(ptr, x + this.cloudSizeX, 4.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_X);
ptr = writeVertex(ptr, x + this.cloudSizeX, 0.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_X);
ptr = writeVertex(ptr, x + this.cloudSizeX, 0.0f, z + 0.0f, mixedColor, NORMAL_POS_X);
ptr = writeVertex(ptr, x + this.cloudSizeX, 4.0f, z + 0.0f, mixedColor, NORMAL_POS_X);
count += 4;
}
// -Z
if ((connectedEdges & DIR_NEG_Z) != 0) {
int mixedColor = ColorMixer.mul(texel, CLOUD_COLOR_NEG_Z);
ptr = writeVertex(ptr, x + this.cloudSizeX, 4.0f, z + 0.0f, mixedColor, NORMAL_NEG_Z);
ptr = writeVertex(ptr, x + this.cloudSizeX, 0.0f, z + 0.0f, mixedColor, NORMAL_NEG_Z);
ptr = writeVertex(ptr, x + 0.0f, 0.0f, z + 0.0f, mixedColor, NORMAL_NEG_Z);
ptr = writeVertex(ptr, x + 0.0f, 4.0f, z + 0.0f, mixedColor, NORMAL_NEG_Z);
count += 4;
}
// +Z
if ((connectedEdges & DIR_POS_Z) != 0) {
int mixedColor = ColorMixer.mul(texel, CLOUD_COLOR_POS_Z);
ptr = writeVertex(ptr, x + this.cloudSizeX, 0.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_Z);
ptr = writeVertex(ptr, x + this.cloudSizeX, 4.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_Z);
ptr = writeVertex(ptr, x + 0.0f, 4.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_Z);
ptr = writeVertex(ptr, x + 0.0f, 0.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_Z);
count += 4;
}
if (count > 0) {
writer.push(stack, buffer, count, LineVertex.FORMAT);
}
}
}
}
}
private static long writeVertex(long buffer, float x, float y, float z, int color, int normal) {
LineVertex.put(buffer, x, y, z, color, normal);
return buffer + LineVertex.STRIDE;
}
public void reloadTextures(ResourceProvider factory) {
this.destroy();
this.edges = createCloudEdges();
// FIXME this ugly code is needed because Iris, as usual, duplicates the original code and assumes the old sizes
// If shaders are on we assume the vanilla size so that the hardcoded values will actually match up with our code.
// This will be removed when Iris support is dropped.
boolean shaderMod = ShaderModBridge.areShadersEnabled();
float width = shaderMod ? 256 : this.edges.width;
float height = shaderMod ? 256 : this.edges.height;
this.cloudSizeX = MAX_SINGLE_CLOUD_SIZE / width;
this.cloudSizeZ = MAX_SINGLE_CLOUD_SIZE / height;
this.fogDistanceMultiplier = CLOUD_PIXELS_TO_FOG_DISTANCE / width;
this.cloudDistanceMinimum = (int) (width * CLOUD_PIXELS_TO_MINIMUM_RENDER_DISTANCE);
this.cloudDistanceMaximum = (int) (width * CLOUD_PIXELS_TO_MAXIMUM_RENDER_DISTANCE);
this.shader = new CloudShader();
}
public void destroy() {
if (this.shader != null) {
this.shader.close();
this.shader = null;
}
if (this.vertexBuffer != null) {
this.vertexBuffer.close();
this.vertexBuffer = null;
}
}
private static CloudEdges createCloudEdges() {
ResourceManager resourceManager = Minecraft.getInstance().getResourceManager();
try {
//? if >=1.19 {
Resource resource = resourceManager.getResource(CLOUDS_TEXTURE_ID)
.orElseThrow();
try (InputStream inputStream = resource.open()){
//?} else {
/*Resource resource = resourceManager.getResource(CLOUDS_TEXTURE_ID);
try (InputStream inputStream = resource.getInputStream()){
*///?}
try (NativeImage nativeImage = NativeImage.read(inputStream)) {
return new CloudEdges(nativeImage);
}
}
} catch (IOException ex) {
throw new RuntimeException("Failed to load texture data", ex);
}
}
private static class CloudEdges {
private final byte[] edges;
private final int[] colors;
private final int width, height;
public CloudEdges(NativeImage texture) {
int width = texture.getWidth();
int height = texture.getHeight();
this.edges = new byte[width * height];
this.colors = new int[width * height];
this.width = width;
this.height = height;
for (int x = 0; x < width; x++) {
for (int z = 0; z < height; z++) {
int index = index(x, z, width, height);
int cell = texture.getPixelRGBA(x, z);
this.colors[index] = cell;
int edges = 0;
if (isOpaqueCell(cell)) {
edges |= DIR_NEG_Y | DIR_POS_Y;
int negX = texture.getPixelRGBA(wrap(x - 1, width), wrap(z, height));
if (cell != negX) {
edges |= DIR_NEG_X;
}
int posX = texture.getPixelRGBA(wrap(x + 1, width), wrap(z, height));
if (!isOpaqueCell(posX) && cell != posX) {
edges |= DIR_POS_X;
}
int negZ = texture.getPixelRGBA(wrap(x, width), wrap(z - 1, height));
if (cell != negZ) {
edges |= DIR_NEG_Z;
}
int posZ = texture.getPixelRGBA(wrap(x, width), wrap(z + 1, height));
if (!isOpaqueCell(posZ) && cell != posZ) {
edges |= DIR_POS_Z;
}
}
this.edges[index] = (byte) edges;
}
}
}
private static boolean isOpaqueCell(int color) {
return ColorARGB.unpackAlpha(color) > 1;
}
public int getEdges(int x, int z) {
return this.edges[index(x, z, this.width, this.height)];
}
public int getColor(int x, int z) {
return this.colors[index(x, z, this.width, this.height)];
}
private static int index(int posX, int posZ, int width, int height) {
return (wrap(posX, width) * height) + wrap(posZ, height);
}
private static int wrap(int pos, int dim) {
return Math.floorMod(pos, dim);
}
}
}
//?}
@@ -1,84 +0,0 @@
package org.embeddedt.embeddium.impl.render.immediate;
import org.embeddedt.embeddium.impl.gl.shader.*;
import org.embeddedt.embeddium.impl.gl.shader.uniform.*;
import org.embeddedt.embeddium.impl.gl.compat.FogHelper;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderComponent;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderEnvironment;
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
import org.joml.Matrix4f;
import java.util.IdentityHashMap;
import java.util.Map;
public class CloudShader implements AutoCloseable {
private static final int ATTRIBUTE_POSITION = 0;
private static final int ATTRIBUTE_COLOR = 1;
private static final int FRAG_COLOR = 0;
private static final ChunkShaderEnvironment ENVIRONMENT = new ChunkShaderEnvironment(FogHelper.INSTANCE);
private final Map<ChunkShaderComponent.Factory<?>, GlProgram<CloudShaderInterface>> programs = new IdentityHashMap<>();
private GlProgram<CloudShaderInterface> program;
private static GlProgram<CloudShaderInterface> createShader(ChunkShaderComponent.Factory<?> fog) {
ShaderConstants constants = ShaderConstants.builder().addAll(fog.getDefines()).build();
GlShader vertShader = ShaderLoader.loadShader(ShaderType.VERTEX, "sodium:clouds/clouds.vsh", constants);
GlShader fragShader = ShaderLoader.loadShader(ShaderType.FRAGMENT, "sodium:clouds/clouds.fsh", constants);
try {
return GlProgram.builder("celeritas:cloud_shader")
.attachShader(vertShader)
.attachShader(fragShader)
.bindAttribute("Position", ATTRIBUTE_POSITION)
.bindAttribute("Color", ATTRIBUTE_COLOR)
.bindFragmentData("fragColor", FRAG_COLOR)
.link(context -> new CloudShaderInterface(context, fog.create(context, ENVIRONMENT)));
} finally {
vertShader.delete();
fragShader.delete();
}
}
public void prepareForDraw(Matrix4f modelViewMatrix, Matrix4f projectionMatrix, float r, float g, float b, float a) {
this.program = this.programs.computeIfAbsent(FogHelper.INSTANCE.getFogMode(), CloudShader::createShader);
this.program.bind();
FogHelper.INSTANCE.bindSkyTexture();
this.program.getInterface().setupState(modelViewMatrix, projectionMatrix, r, g, b, a);
}
public void clear() {
this.program.unbind();
}
@Override
public void close() {
this.programs.values().forEach(GlProgram::delete);
this.programs.clear();
}
static class CloudShaderInterface {
private final GlUniformMatrix4f uniformModelViewMatrix;
private final GlUniformMatrix4f uniformProjectionMatrix;
private final GlUniformFloat4v uniformMainColor;
private final ChunkShaderComponent fog;
public CloudShaderInterface(ShaderBindingContext context, ChunkShaderComponent fog) {
this.uniformModelViewMatrix = context.bindUniform("ModelViewMat", GlUniformMatrix4f::new);
this.uniformProjectionMatrix = context.bindUniform("ProjMat", GlUniformMatrix4f::new);
this.uniformMainColor = context.bindUniform("ColorModulator", GlUniformFloat4v::new);
this.fog = fog;
}
public void setupState(Matrix4f modelViewMatrix, Matrix4f projectionMatrix, float r, float g, float b, float a) {
this.uniformModelViewMatrix.set(modelViewMatrix);
this.uniformProjectionMatrix.set(projectionMatrix);
this.uniformMainColor.set(new float[] { r, g, b, a });
this.fog.setup();
}
}
}
@@ -0,0 +1,200 @@
package org.embeddedt.embeddium.impl.render.immediate;
//? if >=1.17 {
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.CloudStatus;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.ResourceProvider;
import net.minecraft.world.phys.Vec3;
import org.embeddedt.embeddium.api.render.clouds.ModifyCloudRenderingEvent;
import org.embeddedt.embeddium.impl.gl.compat.FogHelper;
import org.embeddedt.embeddium.impl.gl.compat.ModernGlStateService;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkFogMode;
import org.embeddedt.embeddium.impl.render.clouds.CloudFrame;
import org.embeddedt.embeddium.impl.render.clouds.CloudRenderState;
import org.embeddedt.embeddium.impl.render.clouds.CloudRenderer;
import org.embeddedt.embeddium.impl.render.clouds.CloudTexture;
import org.embeddedt.embeddium.impl.util.ResourceLocationUtil;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL30C;
import java.io.IOException;
import java.io.InputStream;
public class ModernCloudRenderer {
private static final ResourceLocation CLOUDS_TEXTURE_ID = ResourceLocationUtil.make("textures/environment/clouds.png");
// Vanilla's default cloud range since 1.21.6
private static final int CLOUD_RANGE_CHUNKS = 128;
private static final CloudRenderState RENDER_STATE = new CloudRenderState() {
@Override
public void setup(boolean fancy) {
//? if <1.21 {
RenderSystem.enableBlend();
RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
RenderSystem.enableDepthTest();
RenderSystem.depthFunc(GL30C.GL_LEQUAL);
RenderSystem.depthMask(true);
RenderSystem.colorMask(true, true, true, true);
//?} else {
//RenderType.clouds().setupRenderState();
//?}
if (fancy) {
RenderSystem.enableCull();
} else {
RenderSystem.disableCull();
}
}
@Override
public void restore() {
//? if <1.21 {
RenderSystem.disableBlend();
//?} else
//RenderType.clouds().clearRenderState();
RenderSystem.enableCull();
}
};
private CloudTexture texture;
private @Nullable CloudRenderer renderer;
public ModernCloudRenderer(ResourceProvider factory) {
this.reloadTextures(factory);
}
private static int fireModifyCloudRenderDistanceEvent(int distance) {
var event = new ModifyCloudRenderingEvent(distance);
ModifyCloudRenderingEvent.BUS.post(event);
return event.getCloudRenderDistance();
}
public void render(@Nullable ClientLevel world, LocalPlayer player, Matrix4f modelViewMatrix, Matrix4f projectionMatrix, float ticks, float tickDelta, double cameraX, double cameraY, double cameraZ) {
if (world == null) {
return;
}
float cloudHeight = world.effects().getCloudHeight();
// Vanilla uses NaN height as a way to disable cloud rendering
if (Float.isNaN(cloudHeight)) {
return;
}
float range = fireModifyCloudRenderDistanceEvent(CLOUD_RANGE_CHUNKS) * 16.0f;
float fogEnd = getFogEnd(range);
if (fogEnd <= 0.0f) {
return;
}
Vec3 color = world.getCloudColor(tickDelta);
boolean fancy = Minecraft.getInstance().options.getCloudsType() == CloudStatus.FANCY;
CloudFrame frame = new CloudFrame(modelViewMatrix, projectionMatrix, cameraX, cameraY, cameraZ, cloudHeight,
ticks + tickDelta, (float) color.x, (float) color.y, (float) color.z, fancy, range, fogEnd);
RenderDevice.enterManagedCode();
try (CommandList commandList = RenderDevice.INSTANCE.createCommandList()) {
if (this.renderer == null) {
this.renderer = new CloudRenderer(commandList, ModernGlStateService.INSTANCE, this.texture);
}
if (this.renderer.prepare(commandList, frame)) {
this.draw(commandList, this.renderer, frame);
}
} finally {
exitManagedCode();
}
}
private void draw(CommandList commandList, CloudRenderer renderer, CloudFrame frame) {
renderer.render(commandList, RENDER_STATE, frame);
}
/**
* Like vanilla since 1.21.6, clouds fade out over their own range, unless environmental fog (water, blindness, etc.)
* is closer.
*/
private static float getFogEnd(float cloudRange) {
FogHelper fog = FogHelper.INSTANCE;
if (fog.getFogMode() != ChunkFogMode.NONE && fog.getFogEnd() < fog.getSkyFogEdgeEnd()) {
return Math.min(cloudRange, fog.getFogEnd());
}
return cloudRange;
}
public void reloadTextures(ResourceProvider factory) {
this.destroy();
this.texture = loadTexture();
}
public void destroy() {
if (this.renderer == null) {
return;
}
RenderDevice.enterManagedCode();
try (CommandList commandList = RenderDevice.INSTANCE.createCommandList()) {
this.renderer.delete(commandList);
} finally {
exitManagedCode();
}
this.renderer = null;
}
private static void exitManagedCode() {
RenderDevice.exitManagedCode();
com.mojang.blaze3d.vertex.BufferUploader.reset();
}
private static CloudTexture loadTexture() {
ResourceManager resourceManager = Minecraft.getInstance().getResourceManager();
try {
//? if >=1.19 {
Resource resource = resourceManager.getResource(CLOUDS_TEXTURE_ID)
.orElseThrow();
try (InputStream inputStream = resource.open()){
//?} else {
/*Resource resource = resourceManager.getResource(CLOUDS_TEXTURE_ID);
try (InputStream inputStream = resource.getInputStream()){
*///?}
try (NativeImage image = NativeImage.read(inputStream)) {
int width = image.getWidth();
int height = image.getHeight();
int[] pixels = new int[width * height];
for (int z = 0; z < height; z++) {
for (int x = 0; x < width; x++) {
pixels[x + z * width] = image.getPixelRGBA(x, z);
}
}
return new CloudTexture(width, height, pixels);
}
}
} catch (IOException ex) {
throw new RuntimeException("Failed to load texture data", ex);
}
}
}
//?}
@@ -692,18 +692,27 @@ public class IrisRenderingPipeline implements WorldRenderingPipeline, ShaderRend
private PendingGbufferProgram createShader(String name, Optional<ProgramSource> source, ShaderKey key) { private PendingGbufferProgram createShader(String name, Optional<ProgramSource> source, ShaderKey key) {
if (source.isEmpty()) { if (source.isEmpty()) {
//? if >=26.1 { // Synthesized programs can't generate clouds, so the clouds are drawn without the pack.
/*// Synthesized programs can't generate 26.1's clouds, so vanilla's draws them. if (generatesClouds(key)) {
if (key == ShaderKey.CLOUDS) {
return null; return null;
} }
*///?}
return createFallbackShader(name, key); return createFallbackShader(name, key);
} }
return createShader(name, source.get(), key.getProgram(), key.getAlphaTest(), key.getVertexFormat(), return createShader(name, source.get(), key.getProgram(), key.getAlphaTest(), key.getVertexFormat(),
key.isIntensity(), key.shouldIgnoreLightmap(), key.isGlint(), key.isText()); key.isIntensity(), key.shouldIgnoreLightmap(), key.isGlint(), key.isText(), generatesClouds(key));
}
/**
* Whether the key's program generates its vertices from cloud faces, as vanilla's clouds do on 26.1 and
* Celeritas's do before that.
*/
private static boolean generatesClouds(ShaderKey key) {
//? if >=26.1 {
/*return key.getProgram() == ProgramId.Clouds;
*///?} else
return key == ShaderKey.CLOUDS_SODIUM;
} }
@Override @Override
@@ -712,7 +721,8 @@ public class IrisRenderingPipeline implements WorldRenderingPipeline, ShaderRend
} }
private PendingGbufferProgram createShader(String name, ProgramSource source, ProgramId programId, AlphaTest fallbackAlpha, private PendingGbufferProgram createShader(String name, ProgramSource source, ProgramId programId, AlphaTest fallbackAlpha,
VertexFormat vertexFormat, boolean isIntensity, boolean isFullbright, boolean isGlint, boolean isText) { VertexFormat vertexFormat, boolean isIntensity, boolean isFullbright, boolean isGlint, boolean isText,
boolean generatesClouds) {
GlFramebuffer beforeTranslucent = renderTargets.createGbufferFramebuffer(flippedAfterPrepare, source.getDirectives().getDrawBuffers()); GlFramebuffer beforeTranslucent = renderTargets.createGbufferFramebuffer(flippedAfterPrepare, source.getDirectives().getDrawBuffers());
GlFramebuffer afterTranslucent = renderTargets.createGbufferFramebuffer(flippedAfterTranslucent, source.getDirectives().getDrawBuffers()); GlFramebuffer afterTranslucent = renderTargets.createGbufferFramebuffer(flippedAfterTranslucent, source.getDirectives().getDrawBuffers());
boolean isLines = programId == ProgramId.Line && resolver.has(ProgramId.Line); boolean isLines = programId == ProgramId.Line && resolver.has(ProgramId.Line);
@@ -723,7 +733,7 @@ public class IrisRenderingPipeline implements WorldRenderingPipeline, ShaderRend
() -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent; () -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent;
return ShaderCreator.create(this, name, source, programId, beforeTranslucent, afterTranslucent, return ShaderCreator.create(this, name, source, programId, beforeTranslucent, afterTranslucent,
fallbackAlpha, vertexFormat, inputs, flipped, isIntensity, false, isLines, programId == ProgramId.Clouds, customUniforms); fallbackAlpha, vertexFormat, inputs, flipped, isIntensity, false, isLines, generatesClouds, customUniforms);
} }
private PendingGbufferProgram createFallbackShader(String name, ShaderKey key) { private PendingGbufferProgram createFallbackShader(String name, ShaderKey key) {
@@ -3,10 +3,12 @@ package net.irisshaders.iris.pipeline.foss_transform;
import org.taumc.glsl.Transformer; import org.taumc.glsl.Transformer;
/** /**
* Generates the vertices of 26.1's clouds in a shader pack's vertex shader. Vanilla draws clouds without vertex data, * Generates the vertices of clouds in a shader pack's vertex shader. 26.1's vanilla clouds and Celeritas's clouds before
* building each vertex from {@code gl_VertexID}, the cloud cells in the {@code CloudFaces} texel buffer and the * that are drawn without vertex data, building each vertex from {@code gl_VertexID}, the cloud cells in the
* {@code CloudInfo} block, as its {@code rendertype_clouds} shader does. This feeds the results to the pack's shader in * {@code CloudFaces} texel buffer and the cloud info, as vanilla's {@code rendertype_clouds} shader does. This feeds the
* place of the position, color, normal and texture coordinate attributes. * results to the pack's shader in place of the position, color, normal and texture coordinate attributes.
* <p>
* Before 26.1, the cloud info is plain uniforms, and each cell is also tinted by its pixel in the clouds texture.
*/ */
public final class CloudVertices { public final class CloudVertices {
/** /**
@@ -14,6 +16,16 @@ public final class CloudVertices {
*/ */
public static final String CLOUD_FACES_SAMPLER = "iris_CloudFaces"; public static final String CLOUD_FACES_SAMPLER = "iris_CloudFaces";
//? if <26.1 {
/**
* The name of the clouds texture sampler, which must be bound to Celeritas's cloud colors texture.
*/
public static final String CLOUD_COLORS_SAMPLER = "iris_CloudColors";
private static final String CELL_COLOR = " * iris_cloudCellColor(cellX, cellZ)";
//?} else
//private static final String CELL_COLOR = "";
private CloudVertices() { private CloudVertices() {
} }
@@ -30,7 +42,22 @@ public final class CloudVertices {
translationUnit.rename(attribute[0], attribute[1]); translationUnit.rename(attribute[0], attribute[1]);
} }
translationUnit.injectVariable(VanillaUniformBlocks.CLOUD_INFO.getDeclaration()); //? if >=26.1 {
/*translationUnit.injectVariable(VanillaUniformBlocks.CLOUD_INFO.getDeclaration());
*///?} else {
translationUnit.injectVariable("uniform vec4 iris_CloudColor;");
translationUnit.injectVariable("uniform vec3 iris_CloudOffset;");
translationUnit.injectVariable("uniform vec3 iris_CloudCellSize;");
translationUnit.injectVariable("uniform ivec2 iris_CloudCenterCell;");
translationUnit.injectVariable("uniform sampler2D " + CLOUD_COLORS_SAMPLER + ";");
translationUnit.injectFunction("""
vec4 iris_cloudCellColor(int cellX, int cellZ) {
ivec2 size = textureSize(iris_CloudColors, 0);
ivec2 cell = iris_CloudCenterCell + ivec2(cellX, cellZ);
cell -= size * ivec2(floor(vec2(cell) / vec2(size)));
return texelFetch(iris_CloudColors, cell, 0);
}""");
//?}
translationUnit.injectVariable("uniform isamplerBuffer " + CLOUD_FACES_SAMPLER + ";"); translationUnit.injectVariable("uniform isamplerBuffer " + CLOUD_FACES_SAMPLER + ";");
translationUnit.injectVariable("vec3 iris_cloudPosition;"); translationUnit.injectVariable("vec3 iris_cloudPosition;");
translationUnit.injectVariable("vec4 iris_cloudColor;"); translationUnit.injectVariable("vec4 iris_cloudColor;");
@@ -68,7 +95,8 @@ public final class CloudVertices {
vec3 faceVertex = vertices[(direction * 4) + (isInsideFace ? 3 - quadVertex : quadVertex)]; vec3 faceVertex = vertices[(direction * 4) + (isInsideFace ? 3 - quadVertex : quadVertex)];
iris_cloudPosition = (faceVertex + vec3(cellX, 0, cellZ)) * iris_CloudCellSize + iris_CloudOffset; iris_cloudPosition = (faceVertex + vec3(cellX, 0, cellZ)) * iris_CloudCellSize + iris_CloudOffset;
iris_cloudNormal = isInsideFace ? -normals[direction] : normals[direction]; iris_cloudNormal = isInsideFace ? -normals[direction] : normals[direction];
iris_cloudColor = (useTopColor ? faceColors[1] : faceColors[direction]) * iris_CloudColor; iris_cloudColor = (useTopColor ? faceColors[1] : faceColors[direction]) * iris_CloudColor""" + CELL_COLOR + """
;
}"""); }""");
translationUnit.prependMain("iris_generateCloudVertex();"); translationUnit.prependMain("iris_generateCloudVertex();");
} }
@@ -209,8 +209,13 @@ public class VanillaTransformer {
translationUnit.injectVariable( translationUnit.injectVariable(
"uniform mat4 iris_ProjMat;"); "uniform mat4 iris_ProjMat;");
//? if >=26.1 //? if >=26.1 {
//patchVanillaBlocks(translationUnit, parameters); /*patchVanillaBlocks(translationUnit, parameters);
*///?} else {
if (parameters.isClouds() && parameters.type == ShaderType.VERTEX) {
CloudVertices.patch(translationUnit);
}
//?}
} }
public static void patchVanillaCore(Transformer translationUnit, VanillaParameters parameters) { public static void patchVanillaCore(Transformer translationUnit, VanillaParameters parameters) {
@@ -285,8 +290,13 @@ public class VanillaTransformer {
addIfNotExistsType(translationUnit, "iris_UV2", "in vec2"); addIfNotExistsType(translationUnit, "iris_UV2", "in vec2");
} }
//? if >=26.1 //? if >=26.1 {
//patchVanillaBlocks(translationUnit, parameters); /*patchVanillaBlocks(translationUnit, parameters);
*///?} else {
if (parameters.isClouds() && parameters.type == ShaderType.VERTEX) {
CloudVertices.patch(translationUnit);
}
//?}
} }
//? if >=26.1 { //? if >=26.1 {
@@ -71,6 +71,10 @@ public final class GbufferProgram {
private final int fogColorLocation; private final int fogColorLocation;
private final int light0DirectionLocation; private final int light0DirectionLocation;
private final int light1DirectionLocation; private final int light1DirectionLocation;
private final int cloudColorLocation;
private final int cloudOffsetLocation;
private final int cloudCellSizeLocation;
private final int cloudCenterCellLocation;
private final Matrix4f scratchMatrix = new Matrix4f(); private final Matrix4f scratchMatrix = new Matrix4f();
private final Matrix3f scratchNormalMatrix = new Matrix3f(); private final Matrix3f scratchNormalMatrix = new Matrix3f();
@@ -127,6 +131,10 @@ public final class GbufferProgram {
this.fogColorLocation = GlStateManager._glGetUniformLocation(id, "iris_FogColor"); this.fogColorLocation = GlStateManager._glGetUniformLocation(id, "iris_FogColor");
this.light0DirectionLocation = GlStateManager._glGetUniformLocation(id, "iris_Light0_Direction"); this.light0DirectionLocation = GlStateManager._glGetUniformLocation(id, "iris_Light0_Direction");
this.light1DirectionLocation = GlStateManager._glGetUniformLocation(id, "iris_Light1_Direction"); this.light1DirectionLocation = GlStateManager._glGetUniformLocation(id, "iris_Light1_Direction");
this.cloudColorLocation = GlStateManager._glGetUniformLocation(id, "iris_CloudColor");
this.cloudOffsetLocation = GlStateManager._glGetUniformLocation(id, "iris_CloudOffset");
this.cloudCellSizeLocation = GlStateManager._glGetUniformLocation(id, "iris_CloudCellSize");
this.cloudCenterCellLocation = GlStateManager._glGetUniformLocation(id, "iris_CloudCenterCell");
//?} else { //?} else {
/*for (VanillaUniformBlocks block : BLOCKS) { /*for (VanillaUniformBlocks block : BLOCKS) {
int index = IrisRenderSystem.getUniformBlockIndex(id, block.getBlockName()); int index = IrisRenderSystem.getUniformBlockIndex(id, block.getBlockName());
@@ -218,6 +226,13 @@ public final class GbufferProgram {
uploadFloat(glintAlphaLocation, state.glintAlpha); uploadFloat(glintAlphaLocation, state.glintAlpha);
uploadFloat(fogStartLocation, state.fogStart); uploadFloat(fogStartLocation, state.fogStart);
uploadFloat(fogEndLocation, state.fogEnd); uploadFloat(fogEndLocation, state.fogEnd);
uploadVector(cloudColorLocation, state.cloudColor);
uploadVector(cloudOffsetLocation, state.cloudOffset);
uploadVector(cloudCellSizeLocation, state.cloudCellSize);
if (cloudCenterCellLocation != -1) {
GL20C.glUniform2i(cloudCenterCellLocation, state.cloudCenterCellX, state.cloudCenterCellZ);
}
} }
private void uploadMatrix(int location, Matrix4f matrix) { private void uploadMatrix(int location, Matrix4f matrix) {
@@ -49,7 +49,7 @@ public class ShaderCreator {
GlFramebuffer writingToBeforeTranslucent, GlFramebuffer writingToAfterTranslucent, GlFramebuffer writingToBeforeTranslucent, GlFramebuffer writingToAfterTranslucent,
AlphaTest fallbackAlpha, VertexFormat vertexFormat, ShaderAttributeInputs inputs, AlphaTest fallbackAlpha, VertexFormat vertexFormat, ShaderAttributeInputs inputs,
Supplier<ImmutableSet<Integer>> flipped, boolean isIntensity, boolean isShadowPass, Supplier<ImmutableSet<Integer>> flipped, boolean isIntensity, boolean isShadowPass,
boolean isLines, boolean isClouds, CustomUniforms customUniforms) { boolean isLines, boolean generatesClouds, CustomUniforms customUniforms) {
AlphaTest alpha = source.getDirectives().getAlphaTestOverride().orElse(fallbackAlpha); AlphaTest alpha = source.getDirectives().getAlphaTestOverride().orElse(fallbackAlpha);
BlendModeOverride blendModeOverride = source.getDirectives().getBlendModeOverride().orElse(programId.getBlendModeOverride()); BlendModeOverride blendModeOverride = source.getDirectives().getBlendModeOverride().orElse(programId.getBlendModeOverride());
@@ -63,18 +63,16 @@ public class ShaderCreator {
CompletableFuture<Map<ShaderType, String>> transformed = CompletableFuture.supplyAsync(() -> { CompletableFuture<Map<ShaderType, String>> transformed = CompletableFuture.supplyAsync(() -> {
Preconditions.checkArgument(source.isValid()); Preconditions.checkArgument(source.isValid());
return TransformPatcherBridge.patchVanilla(name, source.getSourcesMap(), alpha, isLines, isClouds, true, inputs, parent.getTextureMap()); return TransformPatcherBridge.patchVanilla(name, source.getSourcesMap(), alpha, isLines, generatesClouds, true, inputs, parent.getTextureMap());
}, TransformPatcherBridge.EXECUTOR); }, TransformPatcherBridge.EXECUTOR);
//? if >=26.1 {
/*boolean generatesClouds = isClouds;
*///?} else
boolean generatesClouds = false;
ImmutableSet<Integer> reservedTextureUnits = generatesClouds ? IrisSamplers.CLOUDS_RESERVED_TEXTURE_UNITS : IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS; ImmutableSet<Integer> reservedTextureUnits = generatesClouds ? IrisSamplers.CLOUDS_RESERVED_TEXTURE_UNITS : IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS;
return new PendingGbufferProgram(name, attributeLocations(vertexFormat), reservedTextureUnits, transformed, (builder, sources) -> { return new PendingGbufferProgram(name, attributeLocations(vertexFormat), reservedTextureUnits, transformed, (builder, sources) -> {
if (generatesClouds) { if (generatesClouds) {
builder.addExternalSampler(IrisSamplers.CLOUD_FACES_TEXTURE_UNIT, CloudVertices.CLOUD_FACES_SAMPLER); builder.addExternalSampler(IrisSamplers.CLOUD_FACES_TEXTURE_UNIT, CloudVertices.CLOUD_FACES_SAMPLER);
//? if <26.1
builder.addExternalSampler(IrisSamplers.CLOUD_COLORS_TEXTURE_UNIT, CloudVertices.CLOUD_COLORS_SAMPLER);
} }
CommonUniforms.addDynamicUniforms(builder, FogMode.PER_VERTEX); CommonUniforms.addDynamicUniforms(builder, FogMode.PER_VERTEX);
@@ -28,6 +28,12 @@ public final class VanillaDrawState {
public float glintAlpha = 1.0F; public float glintAlpha = 1.0F;
public float fogStart; public float fogStart;
public float fogEnd = 1.0F; public float fogEnd = 1.0F;
// What clouds programs generate their vertices from, as the cloud info uniforms
public final Vector4f cloudColor = new Vector4f(1.0F);
public final Vector3f cloudOffset = new Vector3f();
public final Vector3f cloudCellSize = new Vector3f();
public int cloudCenterCellX;
public int cloudCenterCellZ;
//?} else { //?} else {
/*// The program vanilla set up the draw for, whose uniform block bindings hold vanilla's values. /*// The program vanilla set up the draw for, whose uniform block bindings hold vanilla's values.
public GlProgram vanillaProgram; public GlProgram vanillaProgram;
@@ -32,9 +32,15 @@ public class IrisSamplers {
public static final int LIGHTMAP_TEXTURE_UNIT = 2; public static final int LIGHTMAP_TEXTURE_UNIT = 2;
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);
// Holds the buffer of cloud faces 26.1 generates cloud vertices from, in clouds programs only. // Holds the buffer of cloud faces that clouds programs generate their vertices from.
public static final int CLOUD_FACES_TEXTURE_UNIT = 3; public static final int CLOUD_FACES_TEXTURE_UNIT = 3;
public static final ImmutableSet<Integer> CLOUDS_RESERVED_TEXTURE_UNITS = ImmutableSet.of(0, 1, 2, CLOUD_FACES_TEXTURE_UNIT); //? if >=26.1 {
/*public static final ImmutableSet<Integer> CLOUDS_RESERVED_TEXTURE_UNITS = ImmutableSet.of(0, 1, 2, CLOUD_FACES_TEXTURE_UNIT);
*///?} else {
// Celeritas's clouds also tint each cell by its pixel in the clouds texture
public static final int CLOUD_COLORS_TEXTURE_UNIT = 4;
public static final ImmutableSet<Integer> CLOUDS_RESERVED_TEXTURE_UNITS = ImmutableSet.of(0, 1, 2, CLOUD_FACES_TEXTURE_UNIT, CLOUD_COLORS_TEXTURE_UNIT);
//?}
/** /**
* Terrain programs that pull vertex data also reserve the unit Celeritas binds it to. * Terrain programs that pull vertex data also reserve the unit Celeritas binds it to.
@@ -1,52 +1,82 @@
package net.irisshaders.iris.compat.sodium.mixin.clouds; package net.irisshaders.iris.compat.sodium.mixin.clouds;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.mojang.blaze3d.systems.RenderSystem;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.mojang.blaze3d.vertex.VertexBuffer;
import org.embeddedt.embeddium.impl.render.immediate.CloudRenderer;
import net.irisshaders.iris.Iris; import net.irisshaders.iris.Iris;
import net.irisshaders.iris.pipeline.ShaderRenderingPipeline; import net.irisshaders.iris.pipeline.ShaderRenderingPipeline;
import net.irisshaders.iris.pipeline.WorldRenderingPipeline; import net.irisshaders.iris.pipeline.WorldRenderingPipeline;
import net.irisshaders.iris.pipeline.programs.GbufferProgram;
import net.irisshaders.iris.pipeline.programs.ShaderKey; import net.irisshaders.iris.pipeline.programs.ShaderKey;
import org.embeddedt.embeddium.impl.render.immediate.CloudShader; import net.irisshaders.iris.pipeline.programs.VanillaDrawState;
import org.joml.Matrix4f; import net.minecraft.client.Minecraft;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.render.clouds.CloudFrame;
import org.embeddedt.embeddium.impl.render.clouds.CloudRenderState;
import org.embeddedt.embeddium.impl.render.clouds.CloudRenderer;
import org.embeddedt.embeddium.impl.render.immediate.ModernCloudRenderer;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(CloudRenderer.class) @Mixin(ModernCloudRenderer.class)
public abstract class MixinCloudRenderer { public abstract class MixinCloudRenderer {
@Shadow private VertexBuffer vertexBuffer; @Shadow
@Final
private static CloudRenderState RENDER_STATE;
@Unique
private static final VanillaDrawState iris$drawState = new VanillaDrawState();
/** /**
* @author embeddedt * @author embeddedt
* @reason draw the clouds using the Iris shader if present * @reason draw the clouds with the shader pack's program, which generates the vertices from the same faces
*/ */
@WrapOperation(method = "render", at = @At(value = "INVOKE", target = "Lorg/embeddedt/embeddium/impl/render/immediate/CloudShader;prepareForDraw(Lorg/joml/Matrix4f;Lorg/joml/Matrix4f;FFFF)V")) @Inject(method = "draw", at = @At("HEAD"), cancellable = true)
private void drawWithIrisShader(CloudShader instance, Matrix4f modelViewMatrix, Matrix4f projectionMatrix, float r, float g, float b, float a, Operation<Void> original) { private void iris$drawWithShaderPack(CommandList commandList, CloudRenderer renderer, CloudFrame frame, CallbackInfo ci) {
WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline instanceof ShaderRenderingPipeline) { if (!(pipeline instanceof ShaderRenderingPipeline shaderPipeline)) {
var irisShader = ((ShaderRenderingPipeline) pipeline).getShaderMap().getShader(ShaderKey.CLOUDS_SODIUM); return;
this.vertexBuffer.drawWithShader(modelViewMatrix, projectionMatrix, irisShader);
} else {
original.call(instance, modelViewMatrix, projectionMatrix, r, g, b, a);
} }
}
/** GbufferProgram program = shaderPipeline.getShaderMap().getProgram(ShaderKey.CLOUDS_SODIUM);
* @author embeddedt
* @reason suppress the vanilla cloud rendering if Iris shader is active
*/
@Inject(method = "drawVertexBuffer", at = @At("HEAD"), cancellable = true)
private void drawWithIrisShader(CallbackInfo ci) {
WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline instanceof ShaderRenderingPipeline) { // Without a clouds program from the pack, our own draws them
ci.cancel(); if (program == null) {
return;
} }
VanillaDrawState state = iris$drawState;
state.modelView.set(frame.modelView());
state.projection.set(frame.projection());
state.textureMatrix.identity();
state.chunkOffset.zero();
// The cloud color is applied through the cloud info, so the pack mustn't apply it again
state.colorModulator.set(1.0F);
float[] fogColor = RenderSystem.getShaderFogColor();
state.fogColor.set(fogColor[0], fogColor[1], fogColor[2], fogColor[3]);
state.fogStart = RenderSystem.getShaderFogStart();
state.fogEnd = RenderSystem.getShaderFogEnd();
state.albedoTexture = RenderSystem.getShaderTexture(0);
state.overlayTexture = RenderSystem.getShaderTexture(1);
state.lightmapTexture = RenderSystem.getShaderTexture(2);
state.cloudColor.set(frame.red(), frame.green(), frame.blue(), CloudRenderer.getAlpha());
state.cloudOffset.set(renderer.getOffsetX(), renderer.getOffsetY(), renderer.getOffsetZ());
state.cloudCellSize.set(renderer.getCellSizeX(), renderer.getCellHeight(), renderer.getCellSizeZ());
state.cloudCenterCellX = renderer.getCenterCellX();
state.cloudCenterCellZ = renderer.getCenterCellZ();
RENDER_STATE.setup(frame.fancy());
program.bind(state);
renderer.bindTextures();
renderer.draw(commandList);
program.unbind();
Minecraft.getInstance().getMainRenderTarget().bindWrite(false);
RENDER_STATE.restore();
ci.cancel();
} }
} }