merge-stonecutter #16

Merged
embeddedt merged 9 commits from mitchej123/celeritas:merge-stonecutter into shader-refactor 2025-07-07 21:28:48 -04:00
50 changed files with 474 additions and 1299 deletions

No files matched your search

@@ -1,30 +0,0 @@
package net.irisshaders.iris.gl;
public abstract class GlResource {
private final int id;
private boolean isValid;
protected GlResource(int id) {
this.id = id;
isValid = true;
}
public final void destroy() {
destroyInternal();
isValid = false;
}
protected abstract void destroyInternal();
protected void assertValid() {
if (!isValid) {
throw new IllegalStateException("Tried to use a destroyed GlResource");
}
}
protected int getGlId() {
assertValid();
return id;
}
}
@@ -5,7 +5,6 @@ import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import net.irisshaders.iris.gl.IrisRenderSystem; import net.irisshaders.iris.gl.IrisRenderSystem;
import org.lwjgl.opengl.GL43C; import org.lwjgl.opengl.GL43C;
// Do not extend GlResource, this is immutable.
public class ShaderStorageBuffer { public class ShaderStorageBuffer {
protected final int index; protected final int index;
protected final ShaderStorageInfo info; protected final ShaderStorageInfo info;
@@ -4,20 +4,20 @@ import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import it.unimi.dsi.fastutil.ints.Int2IntArrayMap; import it.unimi.dsi.fastutil.ints.Int2IntArrayMap;
import it.unimi.dsi.fastutil.ints.Int2IntMap; import it.unimi.dsi.fastutil.ints.Int2IntMap;
import net.irisshaders.iris.gl.GlResource;
import net.irisshaders.iris.gl.IrisRenderSystem; import net.irisshaders.iris.gl.IrisRenderSystem;
import net.irisshaders.iris.gl.texture.DepthBufferFormat; import net.irisshaders.iris.gl.texture.DepthBufferFormat;
import net.irisshaders.iris.texture.TextureInfoCache; import net.irisshaders.iris.texture.TextureInfoCache;
import org.embeddedt.embeddium.impl.gl.GlObject;
import org.lwjgl.opengl.GL30C; import org.lwjgl.opengl.GL30C;
public class GlFramebuffer extends GlResource { public class GlFramebuffer extends GlObject {
private final Int2IntMap attachments; private final Int2IntMap attachments;
private final int maxDrawBuffers; private final int maxDrawBuffers;
private final int maxColorAttachments; private final int maxColorAttachments;
private boolean hasDepthAttachment; private boolean hasDepthAttachment;
public GlFramebuffer() { public GlFramebuffer() {
super(IrisRenderSystem.createFramebuffer()); this.setHandle(IrisRenderSystem.createFramebuffer());
this.attachments = new Int2IntArrayMap(); this.attachments = new Int2IntArrayMap();
this.maxDrawBuffers = GL_STATE_MANAGER.glGetInteger(GL30C.GL_MAX_DRAW_BUFFERS); this.maxDrawBuffers = GL_STATE_MANAGER.glGetInteger(GL30C.GL_MAX_DRAW_BUFFERS);
@@ -29,7 +29,7 @@ public class GlFramebuffer extends GlResource {
int internalFormat = TextureInfoCache.INSTANCE.getInfo(texture).getInternalFormat(); int internalFormat = TextureInfoCache.INSTANCE.getInfo(texture).getInternalFormat();
DepthBufferFormat depthBufferFormat = DepthBufferFormat.fromGlEnumOrDefault(internalFormat); DepthBufferFormat depthBufferFormat = DepthBufferFormat.fromGlEnumOrDefault(internalFormat);
int fb = getGlId(); int fb = handle();
if (depthBufferFormat.isCombinedStencil()) { if (depthBufferFormat.isCombinedStencil()) {
IrisRenderSystem.framebufferTexture2D(fb, GL30C.GL_FRAMEBUFFER, GL30C.GL_DEPTH_STENCIL_ATTACHMENT, GL30C.GL_TEXTURE_2D, texture, 0); IrisRenderSystem.framebufferTexture2D(fb, GL30C.GL_FRAMEBUFFER, GL30C.GL_DEPTH_STENCIL_ATTACHMENT, GL30C.GL_TEXTURE_2D, texture, 0);
@@ -41,14 +41,14 @@ public class GlFramebuffer extends GlResource {
} }
public void addColorAttachment(int index, int texture) { public void addColorAttachment(int index, int texture) {
int fb = getGlId(); int fb = handle();
IrisRenderSystem.framebufferTexture2D(fb, GL30C.GL_FRAMEBUFFER, GL30C.GL_COLOR_ATTACHMENT0 + index, GL30C.GL_TEXTURE_2D, texture, 0); IrisRenderSystem.framebufferTexture2D(fb, GL30C.GL_FRAMEBUFFER, GL30C.GL_COLOR_ATTACHMENT0 + index, GL30C.GL_TEXTURE_2D, texture, 0);
attachments.put(index, texture); attachments.put(index, texture);
} }
public void noDrawBuffers() { public void noDrawBuffers() {
IrisRenderSystem.drawBuffers(getGlId(), new int[]{GL30C.GL_NONE}); IrisRenderSystem.drawBuffers(handle(), new int[]{GL30C.GL_NONE});
} }
public void drawBuffers(int[] buffers) { public void drawBuffers(int[] buffers) {
@@ -67,11 +67,11 @@ public class GlFramebuffer extends GlResource {
glBuffers[index++] = GL30C.GL_COLOR_ATTACHMENT0 + buffer; glBuffers[index++] = GL30C.GL_COLOR_ATTACHMENT0 + buffer;
} }
IrisRenderSystem.drawBuffers(getGlId(), glBuffers); IrisRenderSystem.drawBuffers(handle(), glBuffers);
} }
public void readBuffer(int buffer) { public void readBuffer(int buffer) {
IrisRenderSystem.readBuffer(getGlId(), GL30C.GL_COLOR_ATTACHMENT0 + buffer); IrisRenderSystem.readBuffer(handle(), GL30C.GL_COLOR_ATTACHMENT0 + buffer);
} }
public int getColorAttachment(int index) { public int getColorAttachment(int index) {
@@ -83,19 +83,19 @@ public class GlFramebuffer extends GlResource {
} }
public void bind() { public void bind() {
GL_STATE_MANAGER.glBindFramebuffer(GL30C.GL_FRAMEBUFFER, getGlId()); GL_STATE_MANAGER.glBindFramebuffer(GL30C.GL_FRAMEBUFFER, handle());
} }
public void bindAsReadBuffer() { public void bindAsReadBuffer() {
GL_STATE_MANAGER.glBindFramebuffer(GL30C.GL_READ_FRAMEBUFFER, getGlId()); GL_STATE_MANAGER.glBindFramebuffer(GL30C.GL_READ_FRAMEBUFFER, handle());
} }
public void bindAsDrawBuffer() { public void bindAsDrawBuffer() {
GL_STATE_MANAGER.glBindFramebuffer(GL30C.GL_DRAW_FRAMEBUFFER, getGlId()); GL_STATE_MANAGER.glBindFramebuffer(GL30C.GL_DRAW_FRAMEBUFFER, handle());
} }
protected void destroyInternal() { protected void destroyInternal() {
GL_STATE_MANAGER.glDeleteFramebuffers(getGlId()); GL_STATE_MANAGER.glDeleteFramebuffers(handle());
} }
public int getStatus() { public int getStatus() {
@@ -105,6 +105,6 @@ public class GlFramebuffer extends GlResource {
} }
public int getId() { public int getId() {
return getGlId(); return handle();
} }
} }
@@ -2,15 +2,21 @@ package net.irisshaders.iris.gl.image;
import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER; import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import net.irisshaders.iris.gl.GlResource;
import net.irisshaders.iris.gl.IrisRenderSystem; import net.irisshaders.iris.gl.IrisRenderSystem;
import net.irisshaders.iris.gl.texture.InternalTextureFormat; import net.irisshaders.iris.gl.texture.InternalTextureFormat;
import net.irisshaders.iris.gl.texture.PixelFormat; import net.irisshaders.iris.gl.texture.PixelFormat;
import net.irisshaders.iris.gl.texture.PixelType; import net.irisshaders.iris.gl.texture.PixelType;
import net.irisshaders.iris.gl.texture.TextureType; import net.irisshaders.iris.gl.texture.TextureType;
import org.lwjgl.opengl.*; import org.embeddedt.embeddium.impl.gl.GlObject;
import org.embeddedt.embeddium.impl.gl.debug.GLDebug;
import org.lwjgl.opengl.ARBClearTexture;
import org.lwjgl.opengl.GL11C;
import org.lwjgl.opengl.GL13C;
import org.lwjgl.opengl.GL20C;
import org.lwjgl.opengl.GL30C;
import org.lwjgl.opengl.GL43C;
public class GlImage extends GlResource { public class GlImage extends GlObject {
protected final String name; protected final String name;
protected final String samplerName; protected final String samplerName;
protected final TextureType target; protected final TextureType target;
@@ -20,7 +26,7 @@ public class GlImage extends GlResource {
private final boolean clear; private final boolean clear;
public GlImage(String name, String samplerName, TextureType target, PixelFormat format, InternalTextureFormat internalFormat, PixelType pixelType, boolean clear, int width, int height, int depth) { public GlImage(String name, String samplerName, TextureType target, PixelFormat format, InternalTextureFormat internalFormat, PixelType pixelType, boolean clear, int width, int height, int depth) {
super(IrisRenderSystem.createTexture(target.getGlType())); this.setHandle(IrisRenderSystem.createTexture(target.getGlType()));
this.name = name; this.name = name;
this.samplerName = samplerName; this.samplerName = samplerName;
@@ -30,12 +36,12 @@ public class GlImage extends GlResource {
this.pixelType = pixelType; this.pixelType = pixelType;
this.clear = clear; this.clear = clear;
// GLDebug.nameObject(GL43C.GL_TEXTURE, getGlId(), name); GLDebug.nameObject(GL43C.GL_TEXTURE, handle(), name);
IrisRenderSystem.bindTextureForSetup(target.getGlType(), getGlId()); IrisRenderSystem.bindTextureForSetup(target.getGlType(), handle());
target.apply(getGlId(), width, height, depth, internalFormat.getGlFormat(), format.getGlFormat(), pixelType.getGlFormat(), null); target.apply(handle(), width, height, depth, internalFormat.getGlFormat(), format.getGlFormat(), pixelType.getGlFormat(), null);
int texture = getGlId(); int texture = handle();
setup(texture, width, height, depth); setup(texture, width, height, depth);
@@ -81,7 +87,7 @@ public class GlImage extends GlResource {
} }
public int getId() { public int getId() {
return getGlId(); return handle();
} }
/** /**
@@ -96,7 +102,7 @@ public class GlImage extends GlResource {
@Override @Override
protected void destroyInternal() { protected void destroyInternal() {
GL_STATE_MANAGER.glDeleteTextures(getGlId()); GL_STATE_MANAGER.glDeleteTextures(handle());
} }
public InternalTextureFormat getInternalFormat() { public InternalTextureFormat getInternalFormat() {
@@ -130,10 +136,10 @@ public class GlImage extends GlResource {
@Override @Override
public void updateNewSize(int width, int height) { public void updateNewSize(int width, int height) {
IrisRenderSystem.bindTextureForSetup(target.getGlType(), getGlId()); IrisRenderSystem.bindTextureForSetup(target.getGlType(), handle());
target.apply(getGlId(), (int) (width * relativeWidth), (int) (height * relativeHeight), 0, internalTextureFormat.getGlFormat(), format.getGlFormat(), pixelType.getGlFormat(), null); target.apply(handle(), (int) (width * relativeWidth), (int) (height * relativeHeight), 0, internalTextureFormat.getGlFormat(), format.getGlFormat(), pixelType.getGlFormat(), null);
int texture = getGlId(); int texture = handle();
setup(texture, width, height, 0); setup(texture, width, height, 0);
@@ -3,16 +3,16 @@ package net.irisshaders.iris.gl.program;
import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER; import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM; import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM;
import net.irisshaders.iris.gl.GlResource;
import net.irisshaders.iris.gl.IrisRenderSystem; import net.irisshaders.iris.gl.IrisRenderSystem;
import net.irisshaders.iris.shaderpack.FilledIndirectPointer; import net.irisshaders.iris.shaderpack.FilledIndirectPointer;
import org.embeddedt.embeddium.impl.gl.GlObject;
import org.joml.Vector2f; import org.joml.Vector2f;
import org.joml.Vector3i; import org.joml.Vector3i;
import org.lwjgl.opengl.GL43C; import org.lwjgl.opengl.GL43C;
import org.lwjgl.opengl.GL46C; import org.lwjgl.opengl.GL46C;
import org.taumc.celeritas.CeleritasShaderVersionService; import org.taumc.celeritas.CeleritasShaderVersionService;
public final class ComputeProgram extends GlResource { public final class ComputeProgram extends GlObject {
private final ProgramUniforms uniforms; private final ProgramUniforms uniforms;
private final ProgramSamplers samplers; private final ProgramSamplers samplers;
private final ProgramImages images; private final ProgramImages images;
@@ -25,7 +25,7 @@ public final class ComputeProgram extends GlResource {
private FilledIndirectPointer indirectPointer; private FilledIndirectPointer indirectPointer;
ComputeProgram(int program, ProgramUniforms uniforms, ProgramSamplers samplers, ProgramImages images) { ComputeProgram(int program, ProgramUniforms uniforms, ProgramSamplers samplers, ProgramImages images) {
super(program); this.setHandle(program);
localSize = new int[3]; localSize = new int[3];
IrisRenderSystem.getProgramiv(program, GL43C.GL_COMPUTE_WORK_GROUP_SIZE, localSize); IrisRenderSystem.getProgramiv(program, GL43C.GL_COMPUTE_WORK_GROUP_SIZE, localSize);
@@ -65,7 +65,7 @@ public final class ComputeProgram extends GlResource {
} }
public void use() { public void use() {
GL_STATE_MANAGER.glUseProgram(getGlId()); GL_STATE_MANAGER.glUseProgram(handle());
uniforms.update(); uniforms.update();
samplers.update(); samplers.update();
@@ -86,7 +86,7 @@ public final class ComputeProgram extends GlResource {
} }
public void destroyInternal() { public void destroyInternal() {
GL_STATE_MANAGER.glDeleteProgram(getGlId()); GL_STATE_MANAGER.glDeleteProgram(handle());
} }
/** /**
@@ -95,7 +95,7 @@ public final class ComputeProgram extends GlResource {
*/ */
@Deprecated @Deprecated
public int getProgramId() { public int getProgramId() {
return getGlId(); return handle();
} }
public int getActiveImages() { public int getActiveImages() {
@@ -2,17 +2,17 @@ package net.irisshaders.iris.gl.program;
import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER; import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import net.irisshaders.iris.gl.GlResource;
import net.irisshaders.iris.gl.IrisRenderSystem; import net.irisshaders.iris.gl.IrisRenderSystem;
import org.embeddedt.embeddium.impl.gl.GlObject;
import org.lwjgl.opengl.GL43C; import org.lwjgl.opengl.GL43C;
public final class Program extends GlResource { public final class Program extends GlObject {
private final ProgramUniforms uniforms; private final ProgramUniforms uniforms;
private final ProgramSamplers samplers; private final ProgramSamplers samplers;
private final ProgramImages images; private final ProgramImages images;
Program(int program, ProgramUniforms uniforms, ProgramSamplers samplers, ProgramImages images) { Program(int program, ProgramUniforms uniforms, ProgramSamplers samplers, ProgramImages images) {
super(program); this.setHandle(program);
this.uniforms = uniforms; this.uniforms = uniforms;
this.samplers = samplers; this.samplers = samplers;
@@ -27,7 +27,7 @@ public final class Program extends GlResource {
public void use() { public void use() {
IrisRenderSystem.memoryBarrier(GL43C.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL43C.GL_TEXTURE_FETCH_BARRIER_BIT | GL43C.GL_SHADER_STORAGE_BARRIER_BIT); IrisRenderSystem.memoryBarrier(GL43C.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL43C.GL_TEXTURE_FETCH_BARRIER_BIT | GL43C.GL_SHADER_STORAGE_BARRIER_BIT);
GL_STATE_MANAGER.glUseProgram(getGlId()); GL_STATE_MANAGER.glUseProgram(handle());
uniforms.update(); uniforms.update();
samplers.update(); samplers.update();
@@ -35,7 +35,7 @@ public final class Program extends GlResource {
} }
public void destroyInternal() { public void destroyInternal() {
GL_STATE_MANAGER.glDeleteProgram(getGlId()); GL_STATE_MANAGER.glDeleteProgram(handle());
} }
/** /**
@@ -44,7 +44,7 @@ public final class Program extends GlResource {
*/ */
@Deprecated @Deprecated
public int getProgramId() { public int getProgramId() {
return getGlId(); return handle();
} }
public int getActiveImages() { public int getActiveImages() {
@@ -9,13 +9,13 @@ import net.irisshaders.iris.gl.IrisRenderSystem;
import net.irisshaders.iris.gl.image.ImageHolder; import net.irisshaders.iris.gl.image.ImageHolder;
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.shader.GlShader;
import net.irisshaders.iris.gl.shader.ProgramCreator; import net.irisshaders.iris.gl.shader.ProgramCreator;
import net.irisshaders.iris.gl.shader.ShaderCompileException; import net.irisshaders.iris.gl.shader.ShaderCompileException;
import net.irisshaders.iris.gl.shader.ShaderType;
import net.irisshaders.iris.gl.state.ValueUpdateNotifier; import net.irisshaders.iris.gl.state.ValueUpdateNotifier;
import net.irisshaders.iris.gl.texture.InternalTextureFormat; import net.irisshaders.iris.gl.texture.InternalTextureFormat;
import net.irisshaders.iris.gl.texture.TextureType; import net.irisshaders.iris.gl.texture.TextureType;
import org.embeddedt.embeddium.impl.gl.shader.GlShader;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public class ProgramBuilder extends ProgramUniforms.Builder implements SamplerHolder, ImageHolder { public class ProgramBuilder extends ProgramUniforms.Builder implements SamplerHolder, ImageHolder {
@@ -1,15 +1,15 @@
package net.irisshaders.iris.gl.sampler; package net.irisshaders.iris.gl.sampler;
import net.irisshaders.iris.gl.GlResource;
import net.irisshaders.iris.gl.IrisRenderSystem; import net.irisshaders.iris.gl.IrisRenderSystem;
import org.embeddedt.embeddium.impl.gl.GlObject;
import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL11C;
import org.lwjgl.opengl.GL13C; import org.lwjgl.opengl.GL13C;
import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL20C;
import org.lwjgl.opengl.GL30C; import org.lwjgl.opengl.GL30C;
public class GlSampler extends GlResource { public class GlSampler extends GlObject {
public GlSampler(boolean linear, boolean mipmapped, boolean shadow, boolean hardwareShadow) { public GlSampler(boolean linear, boolean mipmapped, boolean shadow, boolean hardwareShadow) {
super(IrisRenderSystem.genSampler()); this.setHandle(IrisRenderSystem.genSampler());
IrisRenderSystem.samplerParameteri(getId(), GL11C.GL_TEXTURE_MIN_FILTER, linear ? GL11C.GL_LINEAR : GL11C.GL_NEAREST); IrisRenderSystem.samplerParameteri(getId(), GL11C.GL_TEXTURE_MIN_FILTER, linear ? GL11C.GL_LINEAR : GL11C.GL_NEAREST);
IrisRenderSystem.samplerParameteri(getId(), GL11C.GL_TEXTURE_MAG_FILTER, linear ? GL11C.GL_LINEAR : GL11C.GL_NEAREST); IrisRenderSystem.samplerParameteri(getId(), GL11C.GL_TEXTURE_MAG_FILTER, linear ? GL11C.GL_LINEAR : GL11C.GL_NEAREST);
@@ -27,10 +27,10 @@ public class GlSampler extends GlResource {
@Override @Override
protected void destroyInternal() { protected void destroyInternal() {
IrisRenderSystem.destroySampler(getGlId()); IrisRenderSystem.destroySampler(handle());
} }
public int getId() { public int getId() {
return getGlId(); return handle();
} }
} }
@@ -1,65 +0,0 @@
// This file is based on code from Sodium by JellySquid, licensed under the LGPLv3 license.
package net.irisshaders.iris.gl.shader;
import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import net.irisshaders.iris.gl.GlResource;
import net.irisshaders.iris.gl.IrisRenderSystem;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.embeddedt.embeddium.impl.gl.debug.GLDebug;
import org.lwjgl.opengl.GL20C;
import org.lwjgl.opengl.KHRDebug;
import java.util.Locale;
/**
* A compiled OpenGL shader object.
*/
public class GlShader extends GlResource {
private static final Logger LOGGER = LogManager.getLogger(GlShader.class);
private final String name;
public GlShader(ShaderType type, String name, String src) {
super(createShader(type, name, src));
this.name = name;
}
private static int createShader(ShaderType type, String name, String src) {
int handle = GL_STATE_MANAGER.glCreateShader(type.id);
ShaderWorkarounds.safeShaderSource(handle, src);
GL_STATE_MANAGER.glCompileShader(handle);
GLDebug.nameObject(KHRDebug.GL_SHADER, handle, name + "(" + type.name().toLowerCase(Locale.ROOT) + ")");
String log = IrisRenderSystem.getShaderInfoLog(handle);
if (!log.isEmpty()) {
LOGGER.warn("Shader compilation log for " + name + ": " + log);
}
int result = GL_STATE_MANAGER.glGetShaderi(handle, GL20C.GL_COMPILE_STATUS);
if (result != GL20C.GL_TRUE) {
throw new ShaderCompileException(name, log);
}
return handle;
}
public String getName() {
return this.name;
}
public int getHandle() {
return this.getGlId();
}
@Override
protected void destroyInternal() {
GL_STATE_MANAGER.glDeleteShader(this.getGlId());
}
}
@@ -7,7 +7,10 @@ import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import net.irisshaders.iris.gl.IrisRenderSystem; import net.irisshaders.iris.gl.IrisRenderSystem;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.embeddedt.embeddium.impl.gl.debug.GLDebug;
import org.embeddedt.embeddium.impl.gl.shader.GlShader;
import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL20C;
import org.lwjgl.opengl.KHRDebug;
public class ProgramCreator { public class ProgramCreator {
private static final Logger LOGGER = LogManager.getLogger(ProgramCreator.class); private static final Logger LOGGER = LogManager.getLogger(ProgramCreator.class);
@@ -25,9 +28,9 @@ public class ProgramCreator {
GL_STATE_MANAGER.glBindAttribLocation(program, 1, "UV0"); GL_STATE_MANAGER.glBindAttribLocation(program, 1, "UV0");
for (GlShader shader : shaders) { for (GlShader shader : shaders) {
// GLDebug.nameObject(KHRDebug.GL_SHADER, shader.getHandle(), shader.getName()); GLDebug.nameObject(KHRDebug.GL_SHADER, shader.handle(), shader.getName());
GL_STATE_MANAGER.glAttachShader(program, shader.getHandle()); GL_STATE_MANAGER.glAttachShader(program, shader.handle());
} }
GL_STATE_MANAGER.glLinkProgram(program); GL_STATE_MANAGER.glLinkProgram(program);
@@ -36,7 +39,7 @@ public class ProgramCreator {
//Always detach shaders according to https://www.khronos.org/opengl/wiki/Shader_Compilation#Cleanup //Always detach shaders according to https://www.khronos.org/opengl/wiki/Shader_Compilation#Cleanup
for (GlShader shader : shaders) { for (GlShader shader : shaders) {
IrisRenderSystem.detachShader(program, shader.getHandle()); IrisRenderSystem.detachShader(program, shader.handle());
} }
String log = IrisRenderSystem.getProgramInfoLog(program); String log = IrisRenderSystem.getProgramInfoLog(program);
@@ -1,25 +0,0 @@
// This file is based on code from Sodium by JellySquid, licensed under the LGPLv3 license.
package net.irisshaders.iris.gl.shader;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL32C;
import org.lwjgl.opengl.GL43C;
/**
* An enumeration over the supported OpenGL shader types.
*/
public enum ShaderType {
VERTEX(GL20.GL_VERTEX_SHADER),
GEOMETRY(GL32C.GL_GEOMETRY_SHADER),
FRAGMENT(GL20.GL_FRAGMENT_SHADER),
COMPUTE(GL43C.GL_COMPUTE_SHADER),
TESSELATION_CONTROL(GL43C.GL_TESS_CONTROL_SHADER),
TESSELATION_EVAL(GL43C.GL_TESS_EVALUATION_SHADER);
public final int id;
ShaderType(int id) {
this.id = id;
}
}
@@ -5,31 +5,31 @@ import java.util.function.IntSupplier;
import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER; import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import net.irisshaders.iris.gl.GlResource;
import net.irisshaders.iris.gl.IrisRenderSystem; import net.irisshaders.iris.gl.IrisRenderSystem;
import net.irisshaders.iris.shaderpack.texture.TextureFilteringData; import net.irisshaders.iris.shaderpack.texture.TextureFilteringData;
import org.embeddedt.embeddium.impl.gl.GlObject;
import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL11C;
import org.lwjgl.opengl.GL13C; import org.lwjgl.opengl.GL13C;
import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL20C;
import org.lwjgl.opengl.GL30C; import org.lwjgl.opengl.GL30C;
import org.lwjgl.system.MemoryUtil; import org.lwjgl.system.MemoryUtil;
public class GlTexture extends GlResource implements TextureAccess { public class GlTexture extends GlObject implements TextureAccess {
private final TextureType target; private final TextureType target;
public GlTexture(TextureType target, int sizeX, int sizeY, int sizeZ, int internalFormat, int format, int pixelType, byte[] pixels, TextureFilteringData filteringData) { public GlTexture(TextureType target, int sizeX, int sizeY, int sizeZ, int internalFormat, int format, int pixelType, byte[] pixels, TextureFilteringData filteringData) {
super(GL_STATE_MANAGER.glGenTextures()); this.setHandle(GL_STATE_MANAGER.glGenTextures());
IrisRenderSystem.bindTextureForSetup(target.getGlType(), getGlId()); IrisRenderSystem.bindTextureForSetup(target.getGlType(), handle());
TextureUploadHelper.resetTextureUploadState(); TextureUploadHelper.resetTextureUploadState();
ByteBuffer buffer = MemoryUtil.memAlloc(pixels.length); ByteBuffer buffer = MemoryUtil.memAlloc(pixels.length);
buffer.put(pixels); buffer.put(pixels);
buffer.flip(); buffer.flip();
target.apply(this.getGlId(), sizeX, sizeY, sizeZ, internalFormat, format, pixelType, buffer); target.apply(this.handle(), sizeX, sizeY, sizeZ, internalFormat, format, pixelType, buffer);
MemoryUtil.memFree(buffer); MemoryUtil.memFree(buffer);
int texture = this.getGlId(); int texture = this.handle();
IrisRenderSystem.texParameteri(texture, target.getGlType(), GL11C.GL_TEXTURE_MIN_FILTER, filteringData.shouldBlur() ? GL11C.GL_LINEAR : GL11C.GL_NEAREST); IrisRenderSystem.texParameteri(texture, target.getGlType(), GL11C.GL_TEXTURE_MIN_FILTER, filteringData.shouldBlur() ? GL11C.GL_LINEAR : GL11C.GL_NEAREST);
IrisRenderSystem.texParameteri(texture, target.getGlType(), GL11C.GL_TEXTURE_MAG_FILTER, filteringData.shouldBlur() ? GL11C.GL_LINEAR : GL11C.GL_NEAREST); IrisRenderSystem.texParameteri(texture, target.getGlType(), GL11C.GL_TEXTURE_MAG_FILTER, filteringData.shouldBlur() ? GL11C.GL_LINEAR : GL11C.GL_NEAREST);
@@ -58,7 +58,7 @@ public class GlTexture extends GlResource implements TextureAccess {
} }
public void bind(int unit) { public void bind(int unit) {
IrisRenderSystem.bindTextureToUnit(target.getGlType(), unit, getGlId()); IrisRenderSystem.bindTextureToUnit(target.getGlType(), unit, handle());
} }
@Override @Override
@@ -68,11 +68,11 @@ public class GlTexture extends GlResource implements TextureAccess {
@Override @Override
public IntSupplier getTextureId() { public IntSupplier getTextureId() {
return this::getGlId; return this::handle;
} }
@Override @Override
protected void destroyInternal() { protected void destroyInternal() {
GL_STATE_MANAGER.glDeleteTextures(getGlId()); GL_STATE_MANAGER.glDeleteTextures(handle());
} }
} }
@@ -33,7 +33,6 @@ import net.irisshaders.iris.pathways.colorspace.ColorSpaceFragmentConverter;
import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge; import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge;
import net.irisshaders.iris.pipeline.programs.ShaderKey; import net.irisshaders.iris.pipeline.programs.ShaderKey;
import net.irisshaders.iris.pipeline.programs.ShaderMap; import net.irisshaders.iris.pipeline.programs.ShaderMap;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.ShaderPrinter; import net.irisshaders.iris.pipeline.transform.ShaderPrinter;
import net.irisshaders.iris.samplers.IrisImages; import net.irisshaders.iris.samplers.IrisImages;
import net.irisshaders.iris.samplers.IrisSamplers; import net.irisshaders.iris.samplers.IrisSamplers;
@@ -79,6 +78,7 @@ import org.embeddedt.embeddium.compat.mc.MCLevelRenderer;
import org.embeddedt.embeddium.compat.mc.MCShaderInstance; import org.embeddedt.embeddium.compat.mc.MCShaderInstance;
import org.embeddedt.embeddium.compat.mc.MCVertexFormat; import org.embeddedt.embeddium.compat.mc.MCVertexFormat;
import org.embeddedt.embeddium.impl.gl.debug.GLDebug; import org.embeddedt.embeddium.impl.gl.debug.GLDebug;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.joml.Vector3d; import org.joml.Vector3d;
import org.joml.Vector4f; import org.joml.Vector4f;
@@ -1190,7 +1190,8 @@ public abstract class CommonIrisRenderingPipeline implements WorldRenderingPipel
renderTargets.destroy(); renderTargets.destroy();
dhCompat.clearPipeline(); dhCompat.clearPipeline();
customImages.forEach(GlImage::destroy); customImages.forEach(GlImage::delete);
if (shadowRenderer != null) { if (shadowRenderer != null) {
shadowRenderer.destroy(); shadowRenderer.destroy();
@@ -1301,7 +1302,7 @@ public abstract class CommonIrisRenderingPipeline implements WorldRenderingPipel
try { try {
String transformed = TransformPatcherBridge.patchCompute(source.getName(), source.getSource().orElse(null), stage, getTextureMap()); String transformed = TransformPatcherBridge.patchCompute(source.getName(), source.getSource().orElse(null), stage, getTextureMap());
ShaderPrinter.printProgram(source.getName()).addSource(PatchShaderType.COMPUTE, transformed).print(); ShaderPrinter.printProgram(source.getName()).addSource(ShaderType.COMPUTE, transformed).print();
builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
} catch (RuntimeException e) { } catch (RuntimeException e) {
@@ -1373,7 +1374,7 @@ public abstract class CommonIrisRenderingPipeline implements WorldRenderingPipel
TextureStage.GBUFFERS_AND_SHADOW, TextureStage.GBUFFERS_AND_SHADOW,
getTextureMap()); getTextureMap());
ShaderPrinter.printProgram(source.getName()).addSource(PatchShaderType.COMPUTE, transformed).print(); ShaderPrinter.printProgram(source.getName()).addSource(ShaderType.COMPUTE, transformed).print();
builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS); builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS);
} catch (ShaderCompileException e) { } catch (ShaderCompileException e) {
@@ -10,6 +10,7 @@ import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import static com.mitchej123.glsm.RenderSystemService.RENDER_SYSTEM; import static com.mitchej123.glsm.RenderSystemService.RENDER_SYSTEM;
import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM; import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@@ -29,7 +30,6 @@ import net.irisshaders.iris.gl.texture.TextureAccess;
import net.irisshaders.iris.pathways.CenterDepthSampler; import net.irisshaders.iris.pathways.CenterDepthSampler;
import net.irisshaders.iris.pathways.FullScreenQuadRenderer; import net.irisshaders.iris.pathways.FullScreenQuadRenderer;
import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge; import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.ShaderPrinter; import net.irisshaders.iris.pipeline.transform.ShaderPrinter;
import net.irisshaders.iris.samplers.IrisImages; import net.irisshaders.iris.samplers.IrisImages;
import net.irisshaders.iris.samplers.IrisSamplers; import net.irisshaders.iris.samplers.IrisSamplers;
@@ -47,6 +47,7 @@ import net.irisshaders.iris.targets.RenderTargets;
import net.irisshaders.iris.uniforms.CommonUniforms; import net.irisshaders.iris.uniforms.CommonUniforms;
import net.irisshaders.iris.uniforms.FrameUpdateNotifier; import net.irisshaders.iris.uniforms.FrameUpdateNotifier;
import net.irisshaders.iris.uniforms.custom.CustomUniforms; import net.irisshaders.iris.uniforms.custom.CustomUniforms;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.lwjgl.opengl.GL15C; import org.lwjgl.opengl.GL15C;
import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL20C;
import org.lwjgl.opengl.GL30C; import org.lwjgl.opengl.GL30C;
@@ -305,14 +306,13 @@ public class CompositeRenderer {
private Program createProgram(ProgramSource source, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot, private Program createProgram(ProgramSource source, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot,
Supplier<ShadowRenderTargets> shadowTargetsSupplier) { Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
// TODO: Properly handle empty shaders // TODO: Properly handle empty shaders
Map<PatchShaderType, String> transformed = TransformPatcherBridge.patchComposite( Preconditions.checkArgument(source.isValid());
Map<ShaderType, String> transformed = TransformPatcherBridge.patchComposite(
source.getName(), source.getName(),
source.getVertexSource().orElseThrow(NullPointerException::new), source.getSourcesMap(), textureStage, pipeline.getTextureMap());
source.getGeometrySource().orElse(null), String vertex = transformed.get(ShaderType.VERTEX);
source.getFragmentSource().orElseThrow(NullPointerException::new), textureStage, pipeline.getTextureMap()); String geometry = transformed.get(ShaderType.GEOMETRY);
String vertex = transformed.get(PatchShaderType.VERTEX); String fragment = transformed.get(ShaderType.FRAGMENT);
String geometry = transformed.get(PatchShaderType.GEOMETRY);
String fragment = transformed.get(PatchShaderType.FRAGMENT);
ShaderPrinter.printProgram(source.getName()).addSources(transformed).print(); ShaderPrinter.printProgram(source.getName()).addSources(transformed).print();
@@ -376,7 +376,7 @@ public class CompositeRenderer {
try { try {
String transformed = TransformPatcherBridge.patchCompute(source.getName(), source.getSource().orElse(null), textureStage, pipeline.getTextureMap()); String transformed = TransformPatcherBridge.patchCompute(source.getName(), source.getSource().orElse(null), textureStage, pipeline.getTextureMap());
ShaderPrinter.printProgram(source.getName()).addSource(PatchShaderType.COMPUTE, transformed).print(); ShaderPrinter.printProgram(source.getName()).addSource(ShaderType.COMPUTE, transformed).print();
builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
} catch (ShaderCompileException e) { } catch (ShaderCompileException e) {
@@ -9,6 +9,7 @@ import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import static com.mitchej123.glsm.RenderSystemService.RENDER_SYSTEM; import static com.mitchej123.glsm.RenderSystemService.RENDER_SYSTEM;
import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM; import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM;
import com.google.common.base.Preconditions;
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 it.unimi.dsi.fastutil.ints.IntList; import it.unimi.dsi.fastutil.ints.IntList;
@@ -26,7 +27,6 @@ import net.irisshaders.iris.gl.texture.TextureAccess;
import net.irisshaders.iris.pathways.CenterDepthSampler; import net.irisshaders.iris.pathways.CenterDepthSampler;
import net.irisshaders.iris.pathways.FullScreenQuadRenderer; import net.irisshaders.iris.pathways.FullScreenQuadRenderer;
import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge; import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.ShaderPrinter; import net.irisshaders.iris.pipeline.transform.ShaderPrinter;
import net.irisshaders.iris.samplers.IrisImages; import net.irisshaders.iris.samplers.IrisImages;
import net.irisshaders.iris.samplers.IrisSamplers; import net.irisshaders.iris.samplers.IrisSamplers;
@@ -44,6 +44,7 @@ import net.irisshaders.iris.uniforms.CommonUniforms;
import net.irisshaders.iris.uniforms.FrameUpdateNotifier; import net.irisshaders.iris.uniforms.FrameUpdateNotifier;
import net.irisshaders.iris.uniforms.custom.CustomUniforms; import net.irisshaders.iris.uniforms.custom.CustomUniforms;
import org.embeddedt.embeddium.impl.gl.debug.GLDebug; import org.embeddedt.embeddium.impl.gl.debug.GLDebug;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.*; import org.lwjgl.opengl.*;
@@ -317,14 +318,13 @@ public class FinalPassRenderer {
private Program createProgram(ProgramSource source, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot, private Program createProgram(ProgramSource source, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot,
Supplier<ShadowRenderTargets> shadowTargetsSupplier) { Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
// TODO: Properly handle empty shaders // TODO: Properly handle empty shaders
Map<PatchShaderType, String> transformed = TransformPatcherBridge.patchComposite( Preconditions.checkArgument(source.isValid());
Map<ShaderType, String> transformed = TransformPatcherBridge.patchComposite(
source.getName(), source.getName(),
source.getVertexSource().orElseThrow(NullPointerException::new), source.getSourcesMap(), TextureStage.COMPOSITE_AND_FINAL, pipeline.getTextureMap());
source.getGeometrySource().orElse(null), String vertex = transformed.get(ShaderType.VERTEX);
source.getFragmentSource().orElseThrow(NullPointerException::new), TextureStage.COMPOSITE_AND_FINAL, pipeline.getTextureMap()); String geometry = transformed.get(ShaderType.GEOMETRY);
String vertex = transformed.get(PatchShaderType.VERTEX); String fragment = transformed.get(ShaderType.FRAGMENT);
String geometry = transformed.get(PatchShaderType.GEOMETRY);
String fragment = transformed.get(PatchShaderType.FRAGMENT);
ShaderPrinter.printProgram(source.getName()).addSources(transformed).print(); ShaderPrinter.printProgram(source.getName()).addSources(transformed).print();
@@ -387,7 +387,7 @@ public class FinalPassRenderer {
try { try {
String transformed = TransformPatcherBridge.patchCompute(source.getName(), source.getSource().orElse(null), TextureStage.COMPOSITE_AND_FINAL, pipeline.getTextureMap()); String transformed = TransformPatcherBridge.patchCompute(source.getName(), source.getSource().orElse(null), TextureStage.COMPOSITE_AND_FINAL, pipeline.getTextureMap());
ShaderPrinter.printProgram(source.getName()).addSource(PatchShaderType.COMPUTE, transformed).print(); ShaderPrinter.printProgram(source.getName()).addSource(ShaderType.COMPUTE, transformed).print();
builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
} catch (ShaderCompileException e) { } catch (ShaderCompileException e) {
@@ -2,7 +2,10 @@ package net.irisshaders.iris.pipeline;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Ints; import com.google.common.primitives.Ints;
import org.embeddedt.embeddium.compat.mc.MCResourceLocation; import lombok.Getter;
import lombok.experimental.Accessors;
import net.irisshaders.iris.compat.sodium.impl.shader_overrides.IrisTerrainPass;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration; import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
import net.irisshaders.iris.gl.blending.AlphaTest; import net.irisshaders.iris.gl.blending.AlphaTest;
import net.irisshaders.iris.gl.blending.AlphaTests; import net.irisshaders.iris.gl.blending.AlphaTests;
@@ -15,7 +18,6 @@ import net.irisshaders.iris.gl.program.ProgramUniforms;
import net.irisshaders.iris.gl.state.FogMode; import net.irisshaders.iris.gl.state.FogMode;
import net.irisshaders.iris.gl.state.ShaderAttributeInputs; import net.irisshaders.iris.gl.state.ShaderAttributeInputs;
import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge; import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.ShaderPrinter; import net.irisshaders.iris.pipeline.transform.ShaderPrinter;
import net.irisshaders.iris.shaderpack.loading.ProgramId; import net.irisshaders.iris.shaderpack.loading.ProgramId;
import net.irisshaders.iris.shaderpack.programs.ProgramSet; import net.irisshaders.iris.shaderpack.programs.ProgramSet;
@@ -25,210 +27,39 @@ import net.irisshaders.iris.uniforms.CommonUniforms;
import net.irisshaders.iris.uniforms.builtin.BuiltinReplacementUniforms; import net.irisshaders.iris.uniforms.builtin.BuiltinReplacementUniforms;
import net.irisshaders.iris.uniforms.custom.CustomUniforms; import net.irisshaders.iris.uniforms.custom.CustomUniforms;
import java.util.ArrayList; import java.util.*;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.IntFunction; import java.util.function.IntFunction;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM; import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM;
public class SodiumTerrainPipeline { public class SodiumTerrainPipeline {
private static final Supplier<Optional<AlphaTest>> terrainCutoutDefault = () -> Optional.of(AlphaTests.ONE_TENTH_ALPHA);
private static final Supplier<Optional<AlphaTest>> translucentDefault = () -> Optional.of(AlphaTest.ALWAYS);
private static final Supplier<Optional<AlphaTest>> shadowDefault = () -> Optional.of(AlphaTests.ONE_TENTH_ALPHA);
private static final String defaultVertex = """
#version 330 core
in ivec2 a_LightCoord;
in vec4 a_Color;
in vec2 a_TexCoord;
in uvec4 a_PosId;
uniform mat4 iris_ProjectionMatrix;
uniform int fogShape;
uniform mat4 iris_ModelViewMatrix;
uniform vec3 u_RegionOffset;
vec3 _vert_position;
vec2 _vert_tex_diffuse_coord;
ivec2 _vert_tex_light_coord;
vec4 _vert_color;
uint _draw_id;
uint _material_params;
out float v_FragDistance;
const int FOG_SHAPE_SPHERICAL = 0;
const int FOG_SHAPE_CYLINDRICAL = 1;
vec4 _linearFog(vec4 fragColor, float fragDistance, vec4 fogColor, float fogStart, float fogEnd) {
float factor = smoothstep(fogStart, fogEnd, fragDistance * fogColor.a); // alpha value of fog is used as a weight
vec3 blended = mix(fragColor.rgb, fogColor.rgb, factor);
return vec4(blended, fragColor.a); // alpha value of fragment cannot be modified
}
float getFragDistance(int fogShape, vec3 position) {
// Use the maximum of the horizontal and vertical distance to get cylindrical fog if fog shape is cylindrical
switch (fogShape) {
case FOG_SHAPE_SPHERICAL: return length(position);
case FOG_SHAPE_CYLINDRICAL: return max(length(position.xz), abs(position.y));
default: return length(position); // This shouldn't be possible to get, but return a sane value just in case
}
}
out vec4 v_ColorModulator;
out vec2 v_TexCoord;
out float v_MaterialMipBias;
out float v_MaterialAlphaCutoff;
const uint MATERIAL_USE_MIP_OFFSET = 0u;
const uint MATERIAL_ALPHA_CUTOFF_OFFSET = 1u;
float _material_mip_bias(uint material) {
return ((material >> MATERIAL_USE_MIP_OFFSET) & 1u) != 0u ? 0.0f : -4.0f;
}
const float[4] ALPHA_CUTOFF = float[4](0.0, 0.1, 0.5, 1.0);
float _material_alpha_cutoff(uint material) {
return ALPHA_CUTOFF[(material >> MATERIAL_ALPHA_CUTOFF_OFFSET) & 3u];
}
void _vert_init() {
_vert_position = (vec3(a_PosId.xyz) * 4.8828125E-4f + -8.0f);
""" +
"_vert_tex_diffuse_coord = (a_TexCoord * " + (1.0f / 32768.0f) + ");" +
"""
_vert_tex_light_coord = a_LightCoord;
_vert_color = a_Color;
_draw_id = (a_PosId.w >> 8u) & 0xffu;
_material_params = (a_PosId.w >> 0u) & 0xFFu;
}
uvec3 _get_relative_chunk_coord(uint pos) {
return uvec3(pos) >> uvec3(5u, 0u, 2u) & uvec3(7u, 3u, 7u);
}
vec3 _get_draw_translation(uint pos) {
return _get_relative_chunk_coord(pos) * vec3(16.0f);
}
vec4 getVertexPosition() {
return vec4(_vert_position + u_RegionOffset + _get_draw_translation(_draw_id), 1.0f);
}
uniform sampler2D lightmap; // The light map texture
vec3 _sample_lightmap(ivec2 uv) {
return texture(lightmap, clamp(uv / 256.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0))).rgb;
}
void main() {
_vert_init();
// Transform the chunk-local vertex position into world model space
vec3 translation = u_RegionOffset + _get_draw_translation(_draw_id);
vec3 position = _vert_position + translation;
v_FragDistance = getFragDistance(fogShape, position);
// Transform the vertex position into model-view-projection space
gl_Position = iris_ProjectionMatrix * iris_ModelViewMatrix * vec4(position, 1.0);
v_ColorModulator = vec4((_vert_color.rgb * _vert_color.a), 1) * vec4(_sample_lightmap(_vert_tex_light_coord), 1.0);
v_TexCoord = _vert_tex_diffuse_coord;
v_MaterialMipBias = _material_mip_bias(_material_params);
v_MaterialAlphaCutoff = _material_alpha_cutoff(_material_params);
}
""";
private static final String defaultFragment = """
#version 330 core
const int FOG_SHAPE_SPHERICAL = 0;
const int FOG_SHAPE_CYLINDRICAL = 1;
vec4 _linearFog(vec4 fragColor, float fragDistance, vec4 fogColor, float fogStart, float fogEnd) {
float factor = smoothstep(fogStart, fogEnd, fragDistance * fogColor.a); // alpha value of fog is used as a weight
vec3 blended = mix(fragColor.rgb, fogColor.rgb, factor);
return vec4(blended, fragColor.a); // alpha value of fragment cannot be modified
}
in vec4 v_ColorModulator; // The interpolated vertex color
in vec2 v_TexCoord; // The interpolated block texture coordinates
in float v_FragDistance; // The fragment's distance from the camera
in float v_MaterialMipBias;
in float v_MaterialAlphaCutoff;
uniform sampler2D gtexture; // The block atlas texture
uniform vec4 iris_FogColor; // The color of the shader fog
uniform float iris_FogStart; // The starting position of the shader fog
uniform float iris_FogEnd; // The ending position of the shader fog
out vec4 out_FragColor; // The output fragment for the color framebuffer
void main() {
vec4 diffuseColor = texture(gtexture, v_TexCoord, v_MaterialMipBias);
if (diffuseColor.a < 0.1) {
discard;
}
// Modulate the color (used by ambient occlusion and per-vertex colouring)
diffuseColor.rgb *= v_ColorModulator.rgb;
out_FragColor = _linearFog(diffuseColor, v_FragDistance, iris_FogColor, iris_FogStart, iris_FogEnd);
}
""";
private final WorldRenderingPipeline parent; private final WorldRenderingPipeline parent;
private final CustomUniforms customUniforms; private final CustomUniforms customUniforms;
private final IntFunction<ProgramSamplers> createTerrainSamplers; private final IntFunction<ProgramSamplers> createTerrainSamplers;
private final IntFunction<ProgramSamplers> createShadowSamplers; private final IntFunction<ProgramSamplers> createShadowSamplers;
private final IntFunction<ProgramImages> createTerrainImages; private final IntFunction<ProgramImages> createTerrainImages;
private final IntFunction<ProgramImages> createShadowImages; private final IntFunction<ProgramImages> createShadowImages;
Optional<String> terrainSolidVertex;
Optional<String> terrainSolidGeometry; @Getter
Optional<String> terrainSolidTessControl; @Accessors(fluent = true)
Optional<String> terrainSolidTessEval; public static final class PassInfo {
Optional<String> terrainSolidFragment; private final Map<ShaderType, Optional<String>> sources = new EnumMap<>(ShaderType.class);
GlFramebuffer terrainSolidFramebuffer; private GlFramebuffer framebuffer;
BlendModeOverride terrainSolidBlendOverride; private BlendModeOverride blendModeOverride;
List<BufferBlendOverride> terrainSolidBufferOverrides; private List<BufferBlendOverride> bufferOverrides;
Optional<String> terrainCutoutVertex; private Optional<AlphaTest> alphaTest;
Optional<String> terrainCutoutGeometry;
Optional<String> terrainCutoutTessControl; private PassInfo() {
Optional<String> terrainCutoutTessEval; for (var shaderType : ShaderType.values()) {
Optional<String> terrainCutoutFragment; sources.put(shaderType, Optional.empty());
GlFramebuffer terrainCutoutFramebuffer; }
BlendModeOverride terrainCutoutBlendOverride; }
List<BufferBlendOverride> terrainCutoutBufferOverrides; }
Optional<AlphaTest> terrainCutoutAlpha;
Optional<String> translucentVertex; private final Map<IrisTerrainPass, PassInfo> passInfoMap;
Optional<String> translucentGeometry; private final Map<IrisTerrainPass, Optional<ProgramSource>> gbufferProgramSource;
Optional<String> translucentTessControl;
Optional<String> translucentTessEval;
Optional<String> translucentFragment;
GlFramebuffer translucentFramebuffer;
BlendModeOverride translucentBlendOverride;
List<BufferBlendOverride> translucentBufferOverrides;
Optional<AlphaTest> translucentAlpha;
Optional<String> shadowVertex;
Optional<String> shadowGeometry;
Optional<String> shadowTessControl;
Optional<String> shadowTessEval;
Optional<String> shadowFragment;
Optional<String> shadowCutoutFragment;
GlFramebuffer shadowFramebuffer;
BlendModeOverride shadowBlendOverride = BlendModeOverride.OFF;
List<BufferBlendOverride> shadowBufferOverrides;
Optional<AlphaTest> shadowAlpha;
ProgramSet programSet; ProgramSet programSet;
public SodiumTerrainPipeline(WorldRenderingPipeline parent, ProgramSet programSet, IntFunction<ProgramSamplers> createTerrainSamplers, public SodiumTerrainPipeline(WorldRenderingPipeline parent, ProgramSet programSet, IntFunction<ProgramSamplers> createTerrainSamplers,
@@ -239,32 +70,32 @@ public class SodiumTerrainPipeline {
this.parent = Objects.requireNonNull(parent); this.parent = Objects.requireNonNull(parent);
this.customUniforms = customUniforms; this.customUniforms = customUniforms;
Optional<ProgramSource> terrainSolidSource = first(programSet.getGbuffersTerrainSolid(), programSet.getGbuffersTerrain(), programSet.getGbuffersTexturedLit(), programSet.getGbuffersTextured(), programSet.getGbuffersBasic()); this.gbufferProgramSource = new EnumMap<>(IrisTerrainPass.class);
Optional<ProgramSource> terrainCutoutSource = first(programSet.getGbuffersTerrainCutout(), programSet.getGbuffersTerrain(), programSet.getGbuffersTexturedLit(), programSet.getGbuffersTextured(), programSet.getGbuffersBasic()); gbufferProgramSource.put(IrisTerrainPass.GBUFFER_SOLID, first(programSet.getGbuffersTerrainSolid(), programSet.getGbuffersTerrain(), programSet.getGbuffersTexturedLit(), programSet.getGbuffersTextured(), programSet.getGbuffersBasic()));
Optional<ProgramSource> translucentSource = first(programSet.getGbuffersWater(), terrainCutoutSource); gbufferProgramSource.put(IrisTerrainPass.GBUFFER_CUTOUT, first(programSet.getGbuffersTerrainCutout(), programSet.getGbuffersTerrain(), programSet.getGbuffersTexturedLit(), programSet.getGbuffersTextured(), programSet.getGbuffersBasic()));
gbufferProgramSource.put(IrisTerrainPass.GBUFFER_TRANSLUCENT, first(programSet.getGbuffersWater(), gbufferProgramSource.get(IrisTerrainPass.GBUFFER_CUTOUT)));
gbufferProgramSource.put(IrisTerrainPass.SHADOW, programSet.getShadow());
this.programSet = programSet; this.programSet = programSet;
this.shadowFramebuffer = shadowFramebuffer; this.passInfoMap = new EnumMap<>(IrisTerrainPass.class);
terrainSolidSource.ifPresent(sources -> terrainSolidFramebuffer = targets.createGbufferFramebuffer(flippedAfterPrepare, for (var pass : IrisTerrainPass.values()) {
sources.getDirectives().getDrawBuffers())); var passInfo = new PassInfo();
this.passInfoMap.put(pass, passInfo);
terrainCutoutSource.ifPresent(sources -> terrainCutoutFramebuffer = targets.createGbufferFramebuffer(flippedAfterPrepare, if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) {
sources.getDirectives().getDrawBuffers())); passInfo.framebuffer = shadowFramebuffer;
} else {
var programSource = gbufferProgramSource.get(pass);
translucentSource.ifPresent(sources -> translucentFramebuffer = targets.createGbufferFramebuffer(flippedAfterTranslucent, if (programSource != null) {
sources.getDirectives().getDrawBuffers())); // embeddedt - buffers to use, I think?
ImmutableSet<Integer> flipped = pass == IrisTerrainPass.GBUFFER_TRANSLUCENT ? flippedAfterTranslucent : flippedAfterPrepare;
if (terrainSolidFramebuffer == null) { programSource.ifPresentOrElse(
terrainSolidFramebuffer = targets.createGbufferFramebuffer(flippedAfterPrepare, new int[]{0}); sources -> passInfo.framebuffer = targets.createGbufferFramebuffer(flipped, sources.getDirectives().getDrawBuffers()),
() -> passInfo.framebuffer = targets.createGbufferFramebuffer(flipped, new int[] {0}));
} }
if (terrainCutoutFramebuffer == null) {
terrainCutoutFramebuffer = targets.createGbufferFramebuffer(flippedAfterPrepare, new int[]{0});
} }
if (translucentFramebuffer == null) {
translucentFramebuffer = targets.createGbufferFramebuffer(flippedAfterTranslucent, new int[]{0});
} }
this.createTerrainSamplers = createTerrainSamplers; this.createTerrainSamplers = createTerrainSamplers;
@@ -284,333 +115,57 @@ public class SodiumTerrainPipeline {
return Optional.empty(); return Optional.empty();
} }
public static String parseSodiumImport(String shader) { public void patchShaders(RenderPassConfiguration<?> configuration) {
Pattern IMPORT_PATTERN = Pattern.compile("#import <(?<namespace>.*):(?<path>.*)>");
Matcher matcher = IMPORT_PATTERN.matcher(shader);
if (!matcher.matches()) {
throw new IllegalArgumentException("Malformed import statement (expected format: " + IMPORT_PATTERN + ")");
}
String namespace = matcher.group("namespace");
String path = matcher.group("path");
MCResourceLocation identifier = MINECRAFT_SHIM.makeResourceLocation(namespace, path);
return "";
}
public void patchShaders(RenderPassConfiguration configuration) {
ShaderAttributeInputs inputs = new ShaderAttributeInputs(true, true, false, true, true); ShaderAttributeInputs inputs = new ShaderAttributeInputs(true, true, false, true, true);
Optional<ProgramSource> terrainSolidSource = first(programSet.getGbuffersTerrainSolid(), programSet.getGbuffersTerrain(), programSet.getGbuffersTexturedLit(), programSet.getGbuffersTextured(), programSet.getGbuffersBasic()); for (var pass : IrisTerrainPass.values()) {
Optional<ProgramSource> terrainCutoutSource = first(programSet.getGbuffersTerrainCutout(), programSet.getGbuffersTerrain(), programSet.getGbuffersTexturedLit(), programSet.getGbuffersTextured(), programSet.getGbuffersBasic()); var passInfo = passInfoMap.get(pass);
Optional<ProgramSource> translucentSource = first(programSet.getGbuffersWater(), terrainCutoutSource); var programId = switch (pass) {
case GBUFFER_TRANSLUCENT -> ProgramId.Water;
case SHADOW -> ProgramId.Shadow;
terrainSolidSource.ifPresentOrElse(sources -> { default -> ProgramId.Terrain;
terrainSolidBlendOverride = sources.getDirectives().getBlendModeOverride().orElse(ProgramId.Terrain.getBlendModeOverride()); };
terrainSolidBufferOverrides = new ArrayList<>(); var programSource = gbufferProgramSource.get(pass == IrisTerrainPass.SHADOW_CUTOUT ? IrisTerrainPass.SHADOW : pass);
if (programSource == null) {
IRIS_LOGGER.warn("Missing program source for pass {}", pass.name());
continue;
}
programSource.ifPresentOrElse(sources -> {
passInfo.blendModeOverride = sources.getDirectives().getBlendModeOverride().orElse(programId.getBlendModeOverride());
passInfo.bufferOverrides = new ArrayList<>();
sources.getDirectives().getBufferBlendOverrides().forEach(information -> { sources.getDirectives().getBufferBlendOverrides().forEach(information -> {
int index = Ints.indexOf(sources.getDirectives().getDrawBuffers(), information.index()); int index = Ints.indexOf(sources.getDirectives().getDrawBuffers(), information.index());
if (index > -1) { if (index > -1) {
terrainSolidBufferOverrides.add(new BufferBlendOverride(index, information.blendMode())); passInfo.bufferOverrides.add(new BufferBlendOverride(index, information.blendMode()));
} }
}); });
Map<PatchShaderType, String> transformed = TransformPatcherBridge.patchSodium( AlphaTest defaultPassAlpha = switch (pass) {
case SHADOW_CUTOUT, GBUFFER_CUTOUT -> AlphaTests.ONE_TENTH_ALPHA;
default -> AlphaTest.ALWAYS;
};
passInfo.alphaTest = sources.getDirectives().getAlphaTestOverride().or(() -> Optional.of(defaultPassAlpha));
Map<ShaderType, String> transformed = TransformPatcherBridge.patchSodium(
sources.getName(), sources.getName(),
sources.getVertexSource().orElse(null), sources.getSourcesMap(),
sources.getGeometrySource().orElse(null), passInfo.alphaTest.orElseThrow(), inputs, parent.getTextureMap());
sources.getTessControlSource().orElse(null),
sources.getTessEvalSource().orElse(null), for (var type : ShaderType.values()) {
sources.getFragmentSource().orElse(null), passInfo.sources.put(type, Optional.ofNullable(transformed.get(type)));
AlphaTest.ALWAYS, inputs, parent.getTextureMap()); }
terrainSolidVertex = Optional.ofNullable(transformed.get(PatchShaderType.VERTEX));
terrainSolidGeometry = Optional.ofNullable(transformed.get(PatchShaderType.GEOMETRY)); ShaderPrinter.printProgram(sources.getName() + "_sodium_" + pass.getName()).addSources(transformed).print();
terrainSolidTessControl = Optional.ofNullable(transformed.get(PatchShaderType.TESS_CONTROL));
terrainSolidTessEval = Optional.ofNullable(transformed.get(PatchShaderType.TESS_EVAL));
terrainSolidFragment = Optional.ofNullable(transformed.get(PatchShaderType.FRAGMENT));
ShaderPrinter.printProgram(sources.getName() + "_sodium_solid").addSources(transformed).print();
}, () -> { }, () -> {
terrainSolidBlendOverride = null; passInfo.blendModeOverride = null;
terrainSolidBufferOverrides = Collections.emptyList(); passInfo.bufferOverrides = Collections.emptyList();
terrainSolidVertex = Optional.of(defaultVertex); if (pass != IrisTerrainPass.SHADOW && pass != IrisTerrainPass.SHADOW_CUTOUT) {
terrainSolidGeometry = Optional.empty(); throw new UnsupportedOperationException("Fallback vertex/fragment shaders are no longer implemented, but are needed by pass " + pass.name());
terrainSolidTessControl = Optional.empty();
terrainSolidTessEval = Optional.empty();
terrainSolidFragment = Optional.of(defaultFragment);
});
terrainCutoutSource.ifPresentOrElse(sources -> {
terrainCutoutBlendOverride = sources.getDirectives().getBlendModeOverride().orElse(ProgramId.Terrain.getBlendModeOverride());
terrainCutoutBufferOverrides = new ArrayList<>();
sources.getDirectives().getBufferBlendOverrides().forEach(information -> {
int index = Ints.indexOf(sources.getDirectives().getDrawBuffers(), information.index());
if (index > -1) {
terrainCutoutBufferOverrides.add(new BufferBlendOverride(index, information.blendMode()));
} }
}); });
terrainCutoutAlpha = sources.getDirectives().getAlphaTestOverride().or(terrainCutoutDefault);
Map<PatchShaderType, String> transformed = TransformPatcherBridge.patchSodium(
sources.getName(),
sources.getVertexSource().orElse(null),
sources.getGeometrySource().orElse(null),
sources.getTessControlSource().orElse(null),
sources.getTessEvalSource().orElse(null),
sources.getFragmentSource().orElse(null),
terrainCutoutAlpha.orElse(AlphaTests.ONE_TENTH_ALPHA), inputs, parent.getTextureMap());
terrainCutoutVertex = Optional.ofNullable(transformed.get(PatchShaderType.VERTEX));
terrainCutoutGeometry = Optional.ofNullable(transformed.get(PatchShaderType.GEOMETRY));
terrainCutoutTessControl = Optional.ofNullable(transformed.get(PatchShaderType.TESS_CONTROL));
terrainCutoutTessEval = Optional.ofNullable(transformed.get(PatchShaderType.TESS_EVAL));
terrainCutoutFragment = Optional.ofNullable(transformed.get(PatchShaderType.FRAGMENT));
ShaderPrinter.printProgram(sources.getName() + "_sodium_cutout").addSources(transformed).print();
}, () -> {
terrainCutoutBlendOverride = null;
terrainCutoutBufferOverrides = Collections.emptyList();
terrainCutoutAlpha = terrainCutoutDefault.get();
terrainCutoutVertex = Optional.of(defaultVertex);
terrainCutoutGeometry = Optional.empty();
terrainCutoutTessControl = Optional.empty();
terrainCutoutTessEval = Optional.empty();
terrainCutoutFragment = Optional.of(defaultFragment);
});
translucentSource.ifPresentOrElse(sources -> {
translucentBlendOverride = sources.getDirectives().getBlendModeOverride().orElse(ProgramId.Water.getBlendModeOverride());
translucentBufferOverrides = new ArrayList<>();
sources.getDirectives().getBufferBlendOverrides().forEach(information -> {
int index = Ints.indexOf(sources.getDirectives().getDrawBuffers(), information.index());
if (index > -1) {
translucentBufferOverrides.add(new BufferBlendOverride(index, information.blendMode()));
} }
});
translucentAlpha = sources.getDirectives().getAlphaTestOverride().or(translucentDefault);
Map<PatchShaderType, String> transformed = TransformPatcherBridge.patchSodium(
sources.getName(),
sources.getVertexSource().orElse(null),
sources.getGeometrySource().orElse(null),
sources.getTessControlSource().orElse(null),
sources.getTessEvalSource().orElse(null),
sources.getFragmentSource().orElse(null),
translucentAlpha.orElse(AlphaTest.ALWAYS), inputs, parent.getTextureMap());
translucentVertex = Optional.ofNullable(transformed.get(PatchShaderType.VERTEX));
translucentGeometry = Optional.ofNullable(transformed.get(PatchShaderType.GEOMETRY));
translucentTessControl = Optional.ofNullable(transformed.get(PatchShaderType.TESS_CONTROL));
translucentTessEval = Optional.ofNullable(transformed.get(PatchShaderType.TESS_EVAL));
translucentFragment = Optional.ofNullable(transformed.get(PatchShaderType.FRAGMENT));
ShaderPrinter.printProgram(sources.getName() + "_sodium").addSources(transformed).print();
}, () -> {
translucentBlendOverride = null;
translucentBufferOverrides = Collections.emptyList();
translucentAlpha = translucentDefault.get();
translucentVertex = Optional.of(defaultVertex);
translucentGeometry = Optional.empty();
translucentTessControl = Optional.empty();
translucentTessEval = Optional.empty();
translucentFragment = Optional.of(defaultFragment);
});
programSet.getShadow().ifPresentOrElse(sources -> {
shadowBlendOverride = sources.getDirectives().getBlendModeOverride().orElse(ProgramId.Shadow.getBlendModeOverride());
shadowBufferOverrides = new ArrayList<>();
sources.getDirectives().getBufferBlendOverrides().forEach(information -> {
int index = Ints.indexOf(sources.getDirectives().getDrawBuffers(), information.index());
if (index > -1) {
shadowBufferOverrides.add(new BufferBlendOverride(index, information.blendMode()));
}
});
shadowAlpha = sources.getDirectives().getAlphaTestOverride().or(shadowDefault);
Map<PatchShaderType, String> transformed = TransformPatcherBridge.patchSodium(
sources.getName(),
sources.getVertexSource().orElse(null),
sources.getGeometrySource().orElse(null),
sources.getTessControlSource().orElse(null),
sources.getTessEvalSource().orElse(null),
sources.getFragmentSource().orElse(null),
AlphaTest.ALWAYS, inputs, parent.getTextureMap());
Map<PatchShaderType, String> transformedCutout = TransformPatcherBridge.patchSodium(
sources.getName(),
sources.getVertexSource().orElse(null),
sources.getGeometrySource().orElse(null),
sources.getTessControlSource().orElse(null),
sources.getTessEvalSource().orElse(null),
sources.getFragmentSource().orElse(null),
shadowAlpha.get(), inputs, parent.getTextureMap());
shadowVertex = Optional.ofNullable(transformed.get(PatchShaderType.VERTEX));
shadowGeometry = Optional.ofNullable(transformed.get(PatchShaderType.GEOMETRY));
shadowTessControl = Optional.ofNullable(transformed.get(PatchShaderType.TESS_CONTROL));
shadowTessEval = Optional.ofNullable(transformed.get(PatchShaderType.TESS_EVAL));
shadowCutoutFragment = Optional.ofNullable(transformedCutout.get(PatchShaderType.FRAGMENT));
shadowFragment = Optional.ofNullable(transformed.get(PatchShaderType.FRAGMENT));
ShaderPrinter.printProgram(sources.getName() + "_sodium")
.addSources(transformed)
.setName(sources.getName() + "_sodium_cutout")
.addSource(PatchShaderType.FRAGMENT, shadowCutoutFragment.orElse(null))
.print();
}, () -> {
shadowBlendOverride = null;
shadowBufferOverrides = Collections.emptyList();
shadowAlpha = shadowDefault.get();
shadowVertex = Optional.empty();
shadowGeometry = Optional.empty();
shadowTessControl = Optional.empty();
shadowTessEval = Optional.empty();
shadowCutoutFragment = Optional.empty();
shadowFragment = Optional.empty();
});
}
public Optional<String> getTerrainSolidVertexShaderSource() {
return terrainSolidVertex;
}
public Optional<String> getTerrainSolidGeometryShaderSource() {
return terrainSolidGeometry;
}
public Optional<String> getTerrainSolidTessControlShaderSource() {
return terrainSolidTessControl;
}
public Optional<String> getTerrainSolidTessEvalShaderSource() {
return terrainSolidTessEval;
}
public Optional<String> getTerrainSolidFragmentShaderSource() {
return terrainSolidFragment;
}
public Optional<String> getTerrainCutoutVertexShaderSource() {
return terrainCutoutVertex;
}
public Optional<String> getTerrainCutoutGeometryShaderSource() {
return terrainCutoutGeometry;
}
public Optional<String> getTerrainCutoutTessControlShaderSource() {
return terrainCutoutTessControl;
}
public Optional<String> getTerrainCutoutTessEvalShaderSource() {
return terrainCutoutTessEval;
}
public Optional<String> getTerrainCutoutFragmentShaderSource() {
return terrainCutoutFragment;
}
public GlFramebuffer getTerrainSolidFramebuffer() {
return terrainSolidFramebuffer;
}
public GlFramebuffer getTerrainCutoutFramebuffer() {
return terrainCutoutFramebuffer;
}
public BlendModeOverride getTerrainSolidBlendOverride() {
return terrainSolidBlendOverride;
}
public List<BufferBlendOverride> getTerrainSolidBufferOverrides() {
return terrainSolidBufferOverrides;
}
public BlendModeOverride getTerrainCutoutBlendOverride() {
return terrainCutoutBlendOverride;
}
public List<BufferBlendOverride> getTerrainCutoutBufferOverrides() {
return terrainCutoutBufferOverrides;
}
public Optional<AlphaTest> getTerrainCutoutAlpha() {
return terrainCutoutAlpha;
}
public Optional<String> getTranslucentVertexShaderSource() {
return translucentVertex;
}
public Optional<String> getTranslucentGeometryShaderSource() {
return translucentGeometry;
}
public Optional<String> getTranslucentTessControlShaderSource() {
return translucentTessControl;
}
public Optional<String> getTranslucentTessEvalShaderSource() {
return translucentTessEval;
}
public Optional<String> getTranslucentFragmentShaderSource() {
return translucentFragment;
}
public GlFramebuffer getTranslucentFramebuffer() {
return translucentFramebuffer;
}
public BlendModeOverride getTranslucentBlendOverride() {
return translucentBlendOverride;
}
public List<BufferBlendOverride> getTranslucentBufferOverrides() {
return translucentBufferOverrides;
}
public Optional<AlphaTest> getTranslucentAlpha() {
return translucentAlpha;
}
public Optional<String> getShadowVertexShaderSource() {
return shadowVertex;
}
public Optional<String> getShadowGeometryShaderSource() {
return shadowGeometry;
}
public Optional<String> getShadowTessControlShaderSource() {
return shadowTessControl;
}
public Optional<String> getShadowTessEvalShaderSource() {
return shadowTessEval;
}
public Optional<String> getShadowFragmentShaderSource() {
return shadowFragment;
}
public Optional<String> getShadowCutoutFragmentShaderSource() {
return shadowCutoutFragment;
}
public GlFramebuffer getShadowFramebuffer() {
return shadowFramebuffer;
}
public BlendModeOverride getShadowBlendOverride() {
return shadowBlendOverride;
}
public List<BufferBlendOverride> getShadowBufferOverrides() {
return shadowBufferOverrides;
}
public Optional<AlphaTest> getShadowAlpha() {
return shadowAlpha;
} }
public ProgramUniforms.Builder initUniforms(int programId) { public ProgramUniforms.Builder initUniforms(int programId) {
@@ -628,6 +183,14 @@ public class SodiumTerrainPipeline {
return createShadowSamplers != null; return createShadowSamplers != null;
} }
public PassInfo getPassInfo(IrisTerrainPass pass) {
var info = this.passInfoMap.get(pass);
if (info == null) {
throw new IllegalArgumentException("Unknown pass type " + pass);
}
return info;
}
public ProgramSamplers initTerrainSamplers(int programId) { public ProgramSamplers initTerrainSamplers(int programId) {
return createTerrainSamplers.apply(programId); return createTerrainSamplers.apply(programId);
} }
@@ -1,8 +1,7 @@
package net.irisshaders.iris.pipeline.foss_transform; package net.irisshaders.iris.pipeline.foss_transform;
import net.irisshaders.iris.gl.shader.ShaderType;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.parameter.Parameters; import net.irisshaders.iris.pipeline.transform.parameter.Parameters;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.taumc.glsl.Transformer; import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLLexer; import org.taumc.glsl.grammar.GLSLLexer;
import org.taumc.glsl.grammar.GLSLParser; import org.taumc.glsl.grammar.GLSLParser;
@@ -14,7 +13,7 @@ public class CompTransformer {
private static final ShaderType[] pipeline = {ShaderType.VERTEX, ShaderType.TESSELATION_CONTROL, ShaderType.TESSELATION_EVAL, ShaderType.GEOMETRY, ShaderType.FRAGMENT}; private static final ShaderType[] pipeline = {ShaderType.VERTEX, ShaderType.TESSELATION_CONTROL, ShaderType.TESSELATION_EVAL, ShaderType.GEOMETRY, ShaderType.FRAGMENT};
public static void transformEach(Transformer root, Parameters parameters) { public static void transformEach(Transformer root, Parameters parameters) {
if (parameters.type == PatchShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
if ( root.containsCall("fract(worldpos.y + 0.001)")) { if ( root.containsCall("fract(worldpos.y + 0.001)")) {
root.replaceExpression("fract(worldpos.y + 0.001)", "fract(worldpos.y + 0.01)"); root.replaceExpression("fract(worldpos.y + 0.001)", "fract(worldpos.y + 0.01)");
} }
@@ -43,7 +42,7 @@ public class CompTransformer {
} }
// does transformations that require cross-shader type data // does transformations that require cross-shader type data
public static void transformGrouped(Map<PatchShaderType, Transformer> trees, Parameters parameters) { public static void transformGrouped(Map<ShaderType, Transformer> trees, Parameters parameters) {
/* /*
find attributes that are declared as "in" in geometry or fragment but not find attributes that are declared as "in" in geometry or fragment but not
declared as "out" in the previous stage. The missing "out" declarations for declared as "out" in the previous stage. The missing "out" declarations for
@@ -62,16 +61,7 @@ public class CompTransformer {
ShaderType prevType = null; ShaderType prevType = null;
for (ShaderType type : pipeline) { for (ShaderType type : pipeline) {
PatchShaderType[] patchTypes = PatchShaderType.fromGlShaderType(type); if (trees.get(type) == null) {
// check if the patch types have sources and continue if not
boolean hasAny = false;
for (PatchShaderType currentType : patchTypes) {
if (trees.get(currentType) != null) {
hasAny = true;
}
}
if (!hasAny) {
continue; continue;
} }
@@ -82,12 +72,12 @@ public class CompTransformer {
continue; continue;
} }
PatchShaderType prevPatchTypes = PatchShaderType.fromGlShaderType(prevType)[0]; ShaderType prevPatchTypes = prevType;
var prevTree = trees.get(prevPatchTypes); var prevTree = trees.get(prevPatchTypes);
Map<String, GLSLParser.Single_declarationContext> outDec = prevTree.findQualifiers(GLSLLexer.OUT); Map<String, GLSLParser.Single_declarationContext> outDec = prevTree.findQualifiers(GLSLLexer.OUT);
for (PatchShaderType currentType : patchTypes) {
var currentTree = trees.get(currentType); var currentTree = trees.get(type);
if (currentTree == null) { if (currentTree == null) {
continue; continue;
@@ -129,7 +119,6 @@ public class CompTransformer {
} }
} }
}
prevType = type; prevType = type;
} }
@@ -1,8 +1,7 @@
package net.irisshaders.iris.pipeline.foss_transform; package net.irisshaders.iris.pipeline.foss_transform;
import net.irisshaders.iris.gl.shader.ShaderType;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.parameter.Parameters; import net.irisshaders.iris.pipeline.transform.parameter.Parameters;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.taumc.glsl.Transformer; import org.taumc.glsl.Transformer;
import static net.irisshaders.iris.pipeline.foss_transform.ShaderTransformer.*; import static net.irisshaders.iris.pipeline.foss_transform.ShaderTransformer.*;
@@ -22,7 +21,7 @@ public class CompositeTransformer {
public static void patchCompositeCore(Transformer translationUnit, Parameters parameters) { public static void patchCompositeCore(Transformer translationUnit, Parameters parameters) {
patchCompositeDepth(translationUnit, parameters); patchCompositeDepth(translationUnit, parameters);
if (parameters.type == PatchShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
translationUnit.rename("vaPosition", "Position"); translationUnit.rename("vaPosition", "Position");
translationUnit.rename("vaUV0", "UV0"); translationUnit.rename("vaUV0", "UV0");
translationUnit.replaceExpression("modelViewMatrix", "mat4(1.0)"); translationUnit.replaceExpression("modelViewMatrix", "mat4(1.0)");
@@ -44,7 +43,7 @@ public class CompositeTransformer {
translationUnit.replaceExpression("gl_TextureMatrix[" + i + "]", "mat4(1.0f)"); translationUnit.replaceExpression("gl_TextureMatrix[" + i + "]", "mat4(1.0f)");
} }
if (parameters.type.glShaderType == ShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
translationUnit.replaceExpression("gl_MultiTexCoord0","vec4(UV0, 0.0, 1.0)"); translationUnit.replaceExpression("gl_MultiTexCoord0","vec4(UV0, 0.0, 1.0)");
translationUnit.injectVariable("in vec2 UV0;"); translationUnit.injectVariable("in vec2 UV0;");
@@ -54,7 +53,7 @@ public class CompositeTransformer {
// No color attributes, the color is always solid white. // No color attributes, the color is always solid white.
translationUnit.replaceExpression("gl_Color", "vec4(1.0, 1.0, 1.0, 1.0)"); translationUnit.replaceExpression("gl_Color", "vec4(1.0, 1.0, 1.0, 1.0)");
if (parameters.type.glShaderType == ShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
// https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glNormal.xml // https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glNormal.xml
// The initial value of the current normal is the unit vector, (0, 0, 1). // The initial value of the current normal is the unit vector, (0, 0, 1).
translationUnit.replaceExpression("gl_Normal", "vec3(0.0, 0.0, 1.0)"); translationUnit.replaceExpression("gl_Normal", "vec3(0.0, 0.0, 1.0)");
@@ -62,7 +61,7 @@ public class CompositeTransformer {
translationUnit.replaceExpression("gl_NormalMatrix", "mat3(1.0)"); translationUnit.replaceExpression("gl_NormalMatrix", "mat3(1.0)");
if (parameters.type.glShaderType == ShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
translationUnit.injectVariable("in vec3 Position;"); translationUnit.injectVariable("in vec3 Position;");
if (translationUnit.containsCall("ftransform")) { if (translationUnit.containsCall("ftransform")) {
translationUnit.injectFunction( translationUnit.injectFunction(
@@ -1,7 +1,7 @@
package net.irisshaders.iris.pipeline.foss_transform; package net.irisshaders.iris.pipeline.foss_transform;
import net.irisshaders.iris.gl.shader.ShaderType;
import net.irisshaders.iris.pipeline.transform.parameter.VanillaParameters; import net.irisshaders.iris.pipeline.transform.parameter.VanillaParameters;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.taumc.glsl.Transformer; import org.taumc.glsl.Transformer;
public class EntityPatcherNew { public class EntityPatcherNew {
@@ -11,7 +11,7 @@ public class EntityPatcherNew {
translationUnit.removeVariable("entityColor"); translationUnit.removeVariable("entityColor");
} }
if (parameters.type.glShaderType == ShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
// add our own declarations // add our own declarations
// TODO: We're exposing entityColor to this stage even if it isn't declared in // TODO: We're exposing entityColor to this stage even if it isn't declared in
// this stage. But this is needed for the pass-through behavior. // this stage. But this is needed for the pass-through behavior.
@@ -35,7 +35,7 @@ public class EntityPatcherNew {
translationUnit.prependMain("iris_vertexColor = iris_Color;"); translationUnit.prependMain("iris_vertexColor = iris_Color;");
translationUnit.prependMain("entityColor = vec4(overlayColor.rgb, 1.0 - overlayColor.a);"); translationUnit.prependMain("entityColor = vec4(overlayColor.rgb, 1.0 - overlayColor.a);");
translationUnit.prependMain("vec4 overlayColor = texelFetch(iris_overlay, iris_UV1, 0);"); translationUnit.prependMain("vec4 overlayColor = texelFetch(iris_overlay, iris_UV1, 0);");
} else if (parameters.type.glShaderType == ShaderType.TESSELATION_CONTROL) { } else if (parameters.type == ShaderType.TESSELATION_CONTROL) {
// replace read references to grab the color from the first vertex. // replace read references to grab the color from the first vertex.
translationUnit.replaceExpression("entityColor", "entityColor[gl_InvocationID]"); translationUnit.replaceExpression("entityColor", "entityColor[gl_InvocationID]");
@@ -48,7 +48,7 @@ public class EntityPatcherNew {
translationUnit.prependMain( translationUnit.prependMain(
"entityColorTCS = entityColor[gl_InvocationID];\n" + "entityColorTCS = entityColor[gl_InvocationID];\n" +
"iris_vertexColorTCS[gl_InvocationID] = iris_vertexColor[gl_InvocationID];"); "iris_vertexColorTCS[gl_InvocationID] = iris_vertexColor[gl_InvocationID];");
} else if (parameters.type.glShaderType == ShaderType.TESSELATION_EVAL) { } else if (parameters.type == ShaderType.TESSELATION_EVAL) {
// replace read references to grab the color from the first vertex. // replace read references to grab the color from the first vertex.
translationUnit.replaceExpression("entityColor", "entityColorTCS"); translationUnit.replaceExpression("entityColor", "entityColorTCS");
@@ -60,7 +60,7 @@ public class EntityPatcherNew {
translationUnit.prependMain( translationUnit.prependMain(
"entityColorTES = entityColorTCS;\n" + "entityColorTES = entityColorTCS;\n" +
"iris_vertexColorTES = iris_vertexColorTCS[0];"); "iris_vertexColorTES = iris_vertexColorTCS[0];");
} else if (parameters.type.glShaderType == ShaderType.GEOMETRY) { } else if (parameters.type == ShaderType.GEOMETRY) {
// replace read references to grab the color from the first vertex. // replace read references to grab the color from the first vertex.
translationUnit.replaceExpression("entityColor", "entityColor[0]"); translationUnit.replaceExpression("entityColor", "entityColor[0]");
@@ -77,7 +77,7 @@ public class EntityPatcherNew {
translationUnit.rename("iris_vertexColor", "iris_vertexColorTES"); translationUnit.rename("iris_vertexColor", "iris_vertexColorTES");
translationUnit.rename("entityColor", "entityColorTES"); translationUnit.rename("entityColor", "entityColorTES");
} }
} else if (parameters.type.glShaderType == ShaderType.FRAGMENT) { } else if (parameters.type == ShaderType.FRAGMENT) {
translationUnit.injectVariable( translationUnit.injectVariable(
"in vec4 entityColor;"); "in vec4 entityColor;");
translationUnit.injectVariable("in vec4 iris_vertexColor;"); translationUnit.injectVariable("in vec4 iris_vertexColor;");
@@ -109,7 +109,7 @@ public class EntityPatcherNew {
translationUnit.removeVariable("currentRenderedItemId"); translationUnit.removeVariable("currentRenderedItemId");
} }
if (parameters.type.glShaderType == ShaderType.GEOMETRY) { if (parameters.type == ShaderType.GEOMETRY) {
translationUnit.replaceExpression("entityId", translationUnit.replaceExpression("entityId",
"iris_entityInfo[0].x"); "iris_entityInfo[0].x");
@@ -129,7 +129,7 @@ public class EntityPatcherNew {
"iris_entityInfo.z"); "iris_entityInfo.z");
} }
if (parameters.type.glShaderType == ShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
// add our own declarations // add our own declarations
// TODO: We're exposing entityColor to this stage even if it isn't declared in // TODO: We're exposing entityColor to this stage even if it isn't declared in
// this stage. But this is needed for the pass-through behavior. // this stage. But this is needed for the pass-through behavior.
@@ -142,7 +142,7 @@ public class EntityPatcherNew {
// stage. // stage.
translationUnit.prependMain( translationUnit.prependMain(
"iris_entityInfo = iris_Entity;"); "iris_entityInfo = iris_Entity;");
} else if (parameters.type.glShaderType == ShaderType.TESSELATION_CONTROL) { } else if (parameters.type == ShaderType.TESSELATION_CONTROL) {
// TODO: this is passthrough behavior // TODO: this is passthrough behavior
translationUnit.injectVariable( translationUnit.injectVariable(
"flat out ivec3 iris_entityInfoTCS[];"); "flat out ivec3 iris_entityInfoTCS[];");
@@ -151,7 +151,7 @@ public class EntityPatcherNew {
translationUnit.prependMain( translationUnit.prependMain(
"iris_entityInfoTCS[gl_InvocationID] = iris_entityInfo[gl_InvocationID];"); "iris_entityInfoTCS[gl_InvocationID] = iris_entityInfo[gl_InvocationID];");
} else if (parameters.type.glShaderType == ShaderType.TESSELATION_EVAL) { } else if (parameters.type == ShaderType.TESSELATION_EVAL) {
// TODO: this is passthrough behavior // TODO: this is passthrough behavior
translationUnit.injectVariable("flat out ivec3 iris_entityInfoTES;"); translationUnit.injectVariable("flat out ivec3 iris_entityInfoTES;");
translationUnit.injectVariable("flat in ivec3 iris_entityInfoTCS[];"); translationUnit.injectVariable("flat in ivec3 iris_entityInfoTCS[];");
@@ -160,14 +160,14 @@ public class EntityPatcherNew {
translationUnit.replaceExpression("iris_entityInfo", "iris_EntityInfoTCS[0]"); translationUnit.replaceExpression("iris_entityInfo", "iris_EntityInfoTCS[0]");
} else if (parameters.type.glShaderType == ShaderType.GEOMETRY) { } else if (parameters.type == ShaderType.GEOMETRY) {
// TODO: this is passthrough behavior // TODO: this is passthrough behavior
translationUnit.injectVariable( translationUnit.injectVariable(
"flat out ivec3 iris_entityInfoGS;"); "flat out ivec3 iris_entityInfoGS;");
translationUnit.injectVariable("flat in ivec3 iris_entityInfo" + (parameters.hasTesselation ? "TES" : "") + "[];"); translationUnit.injectVariable("flat in ivec3 iris_entityInfo" + (parameters.hasTesselation ? "TES" : "") + "[];");
translationUnit.prependMain( translationUnit.prependMain(
"iris_entityInfoGS = iris_entityInfo" + (parameters.hasTesselation ? "TES" : "") + "[0];"); "iris_entityInfoGS = iris_entityInfo" + (parameters.hasTesselation ? "TES" : "") + "[0];");
} else if (parameters.type.glShaderType == ShaderType.FRAGMENT) { } else if (parameters.type == ShaderType.FRAGMENT) {
translationUnit.injectVariable( translationUnit.injectVariable(
"flat in ivec3 iris_entityInfo;"); "flat in ivec3 iris_entityInfo;");
@@ -2,8 +2,8 @@ package net.irisshaders.iris.pipeline.foss_transform;
import com.google.common.reflect.TypeToken; import com.google.common.reflect.TypeToken;
import com.google.gson.Gson; import com.google.gson.Gson;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.binary.Hex;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.BufferedWriter; import java.io.BufferedWriter;
@@ -31,7 +31,7 @@ public class ShaderTransformationDiskCache {
/** /**
* This value must be incremented whenever a new version of Cornea is published with updated transformers. * This value must be incremented whenever a new version of Cornea is published with updated transformers.
*/ */
private static final int TRANSFORMER_VERSION = 1; private static final int TRANSFORMER_VERSION = 2;
private static final Path SHADER_CACHE_PATH = PLATFORM_UTIL.getGameDir().resolve("cornea_transform_cache"); private static final Path SHADER_CACHE_PATH = PLATFORM_UTIL.getGameDir().resolve("cornea_transform_cache");
@@ -45,7 +45,7 @@ public class ShaderTransformationDiskCache {
} }
} }
public static Map<PatchShaderType, String> transformIfAbsent(ShaderTransformer.TransformKey<?> tKey, Supplier<Map<PatchShaderType, String>> transformFn) { public static Map<ShaderType, String> transformIfAbsent(ShaderTransformer.TransformKey<?> tKey, Supplier<Map<ShaderType, String>> transformFn) {
// TODO - this will be hard to remember to invalidate, disabling disk caching for now // TODO - this will be hard to remember to invalidate, disabling disk caching for now
if (true || !ShaderTransformer.useCache) { if (true || !ShaderTransformer.useCache) {
return transformFn.get(); return transformFn.get();
@@ -55,9 +55,9 @@ public class ShaderTransformationDiskCache {
byte[] hash = DIGEST.digest(data.getBytes(StandardCharsets.UTF_8)); byte[] hash = DIGEST.digest(data.getBytes(StandardCharsets.UTF_8));
String hashFileName = Hex.encodeHexString(hash) + ".dat"; String hashFileName = Hex.encodeHexString(hash) + ".dat";
Path path = SHADER_CACHE_PATH.resolve(hashFileName); Path path = SHADER_CACHE_PATH.resolve(hashFileName);
TypeToken<Map<PatchShaderType, String>> typeToken = new TypeToken<>() {}; TypeToken<Map<ShaderType, String>> typeToken = new TypeToken<>() {};
try (Reader reader = new BufferedReader(new InputStreamReader(new InflaterInputStream(Files.newInputStream(path))))) { try (Reader reader = new BufferedReader(new InputStreamReader(new InflaterInputStream(Files.newInputStream(path))))) {
Map<PatchShaderType, String> map = new Gson().fromJson(reader, typeToken.getType()); Map<ShaderType, String> map = new Gson().fromJson(reader, typeToken.getType());
if(map != null && !map.isEmpty()) { if(map != null && !map.isEmpty()) {
return map; return map;
} else { } else {
@@ -69,7 +69,7 @@ public class ShaderTransformationDiskCache {
IRIS_LOGGER.error("Error loading transformed shader, will re-transform now", e); IRIS_LOGGER.error("Error loading transformed shader, will re-transform now", e);
} }
Map<PatchShaderType, String> results = transformFn.get(); Map<ShaderType, String> results = transformFn.get();
try { try {
Files.createDirectories(SHADER_CACHE_PATH); Files.createDirectories(SHADER_CACHE_PATH);
@@ -2,13 +2,12 @@ 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.gl.blending.AlphaTest; import net.irisshaders.iris.gl.blending.AlphaTest;
import net.irisshaders.iris.gl.shader.ShaderType;
import net.irisshaders.iris.pipeline.transform.Patch; import net.irisshaders.iris.pipeline.transform.Patch;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.parameter.Parameters; import net.irisshaders.iris.pipeline.transform.parameter.Parameters;
import net.irisshaders.iris.pipeline.transform.parameter.SodiumParameters; import net.irisshaders.iris.pipeline.transform.parameter.SodiumParameters;
import net.irisshaders.iris.pipeline.transform.parameter.VanillaParameters; import net.irisshaders.iris.pipeline.transform.parameter.VanillaParameters;
import org.apache.commons.lang3.mutable.MutableObject; import org.apache.commons.lang3.mutable.MutableObject;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.taumc.glsl.ShaderParser; import org.taumc.glsl.ShaderParser;
import org.taumc.glsl.StorageCollector; import org.taumc.glsl.StorageCollector;
import org.taumc.glsl.Transformer; import org.taumc.glsl.Transformer;
@@ -26,34 +25,27 @@ import java.util.regex.Pattern;
public class ShaderTransformer { public class ShaderTransformer {
private static final int CACHE_SIZE = 100; private static final int CACHE_SIZE = 100;
private static final Object2ObjectLinkedOpenHashMap<TransformKey, Map<PatchShaderType, String>> shaderTransformationCache = new Object2ObjectLinkedOpenHashMap<>(); private static final Object2ObjectLinkedOpenHashMap<TransformKey, Map<ShaderType, String>> shaderTransformationCache = new Object2ObjectLinkedOpenHashMap<>();
public static final boolean useCache = true; public static final boolean useCache = true;
public record TransformKey<P extends Parameters>(Patch patchType, EnumMap<PatchShaderType, String> inputs, P params) {} public record TransformKey<P extends Parameters>(Patch patchType, Map<ShaderType, String> inputs, P params) {}
public static <P extends Parameters> Map<PatchShaderType, String> transform(String name, String vertex, String geometry, String tessControl, String tessEval, String fragment, P parameters) { public static <P extends Parameters> Map<ShaderType, String> transform(String name, Map<ShaderType, String> sources, P parameters) {
if (vertex == null && geometry == null && tessControl == null && tessEval == null && fragment == null) { if (sources.isEmpty()) {
return null; return null;
} else { } else {
Map<PatchShaderType, String> result; Map<ShaderType, String> result;
var patchType = parameters.patch; var patchType = parameters.patch;
EnumMap<PatchShaderType, String> inputs = new EnumMap<>(PatchShaderType.class); var key = new TransformKey(patchType, Map.copyOf(sources), parameters);
inputs.put(PatchShaderType.VERTEX, vertex);
inputs.put(PatchShaderType.GEOMETRY, geometry);
inputs.put(PatchShaderType.TESS_CONTROL, tessControl);
inputs.put(PatchShaderType.TESS_EVAL, tessEval);
inputs.put(PatchShaderType.FRAGMENT, fragment);
var key = new TransformKey(patchType, inputs, parameters);
synchronized (shaderTransformationCache) { synchronized (shaderTransformationCache) {
result = shaderTransformationCache.getAndMoveToFirst(key); result = shaderTransformationCache.getAndMoveToFirst(key);
} }
if(result == null || !useCache) { if(result == null || !useCache) {
result = ShaderTransformationDiskCache.transformIfAbsent(key, () -> transformInternal(name, inputs, patchType, parameters)); result = ShaderTransformationDiskCache.transformIfAbsent(key, () -> transformInternal(name, sources, patchType, parameters));
// Clear this, we don't want whatever random type was last transformed being considered for the key // Clear this, we don't want whatever random type was last transformed being considered for the key
parameters.type = null; parameters.type = null;
synchronized (shaderTransformationCache) { synchronized (shaderTransformationCache) {
@@ -68,16 +60,16 @@ public class ShaderTransformer {
} }
} }
public static <P extends Parameters> Map<PatchShaderType, String> transformCompute(String name, String compute, P parameters) { public static <P extends Parameters> Map<ShaderType, String> transformCompute(String name, String compute, P parameters) {
if (compute == null) { if (compute == null) {
return null; return null;
} else { } else {
Map<PatchShaderType, String> result; Map<ShaderType, String> result;
var patchType = parameters.patch; var patchType = parameters.patch;
EnumMap<PatchShaderType, String> inputs = new EnumMap<>(PatchShaderType.class); EnumMap<ShaderType, String> inputs = new EnumMap<>(ShaderType.class);
inputs.put(PatchShaderType.COMPUTE, compute); inputs.put(ShaderType.COMPUTE, compute);
var key = new TransformKey(patchType, inputs, parameters); var key = new TransformKey(patchType, inputs, parameters);
@@ -123,12 +115,12 @@ public class ShaderTransformer {
return builder.toString(); return builder.toString();
} }
private static <P extends Parameters> Map<PatchShaderType, String> transformInternal(String name, EnumMap<PatchShaderType, String> inputs, Patch patchType, P parameters) { private static <P extends Parameters> Map<ShaderType, String> transformInternal(String name, Map<ShaderType, String> inputs, Patch patchType, P parameters) {
EnumMap<PatchShaderType, String> result = new EnumMap<>(PatchShaderType.class); EnumMap<ShaderType, String> result = new EnumMap<>(ShaderType.class);
EnumMap<PatchShaderType, Transformer> types = new EnumMap<>(PatchShaderType.class); EnumMap<ShaderType, Transformer> types = new EnumMap<>(ShaderType.class);
EnumMap<PatchShaderType, String> prepatched = new EnumMap<>(PatchShaderType.class); EnumMap<ShaderType, String> prepatched = new EnumMap<>(ShaderType.class);
for (PatchShaderType type : PatchShaderType.values()) { for (ShaderType type : ShaderType.values()) {
parameters.type = type; parameters.type = type;
if (inputs.get(type) == null) { if (inputs.get(type) == null) {
continue; continue;
@@ -258,7 +250,7 @@ public class ShaderTransformer {
} }
public static void patchMultiTexCoord3(Transformer translationUnit, Parameters parameters) { public static void patchMultiTexCoord3(Transformer translationUnit, Parameters parameters) {
if (parameters.type.glShaderType == ShaderType.VERTEX && translationUnit.hasVariable("gl_MultiTexCoord3") && !translationUnit.hasVariable("mc_midTexCoord")) { if (parameters.type == ShaderType.VERTEX && translationUnit.hasVariable("gl_MultiTexCoord3") && !translationUnit.hasVariable("mc_midTexCoord")) {
translationUnit.rename("gl_MultiTexCoord3", "mc_midTexCoord"); translationUnit.rename("gl_MultiTexCoord3", "mc_midTexCoord");
translationUnit.injectVariable("attribute vec4 mc_midTexCoord;"); translationUnit.injectVariable("attribute vec4 mc_midTexCoord;");
} }
@@ -323,19 +315,19 @@ public class ShaderTransformer {
public static void commonPatch(Transformer root, Parameters parameters, boolean core) { public static void commonPatch(Transformer root, Parameters parameters, boolean core) {
root.rename("gl_FogFragCoord", "iris_FogFragCoord"); root.rename("gl_FogFragCoord", "iris_FogFragCoord");
if (parameters.type.glShaderType == ShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
root.injectVariable("out float iris_FogFragCoord;"); root.injectVariable("out float iris_FogFragCoord;");
root.prependMain("iris_FogFragCoord = 0.0f;"); root.prependMain("iris_FogFragCoord = 0.0f;");
} else if (parameters.type.glShaderType == ShaderType.FRAGMENT) { } else if (parameters.type == ShaderType.FRAGMENT) {
root.injectVariable("in float iris_FogFragCoord;"); root.injectVariable("in float iris_FogFragCoord;");
} }
if (parameters.type.glShaderType == ShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
root.injectVariable("vec4 iris_FrontColor;"); root.injectVariable("vec4 iris_FrontColor;");
root.rename("gl_FrontColor", "iris_FrontColor"); root.rename("gl_FrontColor", "iris_FrontColor");
} }
if (parameters.type.glShaderType == ShaderType.FRAGMENT) { if (parameters.type == ShaderType.FRAGMENT) {
if (root.containsCall("gl_FragColor")) { if (root.containsCall("gl_FragColor")) {
root.replaceExpression("gl_FragColor", "gl_FragData[0]", GLSLParser::unary_expression); root.replaceExpression("gl_FragColor", "gl_FragData[0]", GLSLParser::unary_expression);
} }
@@ -364,7 +356,7 @@ public class ShaderTransformer {
} }
if (parameters.type.glShaderType == ShaderType.VERTEX || parameters.type.glShaderType == ShaderType.FRAGMENT) { if (parameters.type == ShaderType.VERTEX || parameters.type == ShaderType.FRAGMENT) {
upgradeStorageQualifiers(root, parameters); upgradeStorageQualifiers(root, parameters);
} }
@@ -406,7 +398,7 @@ public class ShaderTransformer {
token.setText(GLSLParser.VOCABULARY.getLiteralName(GLSLParser.IN).replace("'", "")); token.setText(GLSLParser.VOCABULARY.getLiteralName(GLSLParser.IN).replace("'", ""));
} }
else if (token.getType() == GLSLParser.VARYING) { else if (token.getType() == GLSLParser.VARYING) {
if (parameters.type.glShaderType == ShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
token.setType(GLSLParser.OUT); token.setType(GLSLParser.OUT);
token.setText(GLSLParser.VOCABULARY.getLiteralName(GLSLParser.OUT).replace("'", "")); token.setText(GLSLParser.VOCABULARY.getLiteralName(GLSLParser.OUT).replace("'", ""));
} else { } else {
@@ -1,9 +1,8 @@
package net.irisshaders.iris.pipeline.foss_transform; package net.irisshaders.iris.pipeline.foss_transform;
import net.irisshaders.iris.gl.shader.ShaderType;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.parameter.SodiumParameters; import net.irisshaders.iris.pipeline.transform.parameter.SodiumParameters;
import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.taumc.glsl.Transformer; import org.taumc.glsl.Transformer;
import static net.irisshaders.iris.pipeline.foss_transform.ShaderTransformer.*; import static net.irisshaders.iris.pipeline.foss_transform.ShaderTransformer.*;
@@ -19,7 +18,7 @@ public class SodiumTransformer {
translationUnit.rename("chunkOffset", "u_RegionOffset"); translationUnit.rename("chunkOffset", "u_RegionOffset");
translationUnit.injectVariable("uniform mat4 iris_LightmapTextureMatrix;"); translationUnit.injectVariable("uniform mat4 iris_LightmapTextureMatrix;");
if (parameters.type == PatchShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
// _draw_translation replaced with Chunks[_draw_id].offset.xyz // _draw_translation replaced with Chunks[_draw_id].offset.xyz
translationUnit.replaceExpression("vaPosition", "_vert_position + _get_draw_translation(_draw_id)"); translationUnit.replaceExpression("vaPosition", "_vert_position + _get_draw_translation(_draw_id)");
translationUnit.replaceExpression("vaColor", "_vert_color"); translationUnit.replaceExpression("vaColor", "_vert_color");
@@ -45,7 +44,7 @@ public class SodiumTransformer {
translationUnit.injectFunction("uniform mat4 iris_LightmapTextureMatrix;"); translationUnit.injectFunction("uniform mat4 iris_LightmapTextureMatrix;");
translationUnit.rename("gl_ProjectionMatrix", "iris_ProjectionMatrix"); translationUnit.rename("gl_ProjectionMatrix", "iris_ProjectionMatrix");
if (parameters.type.glShaderType == ShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
translationUnit.rename("gl_MultiTexCoord2", "gl_MultiTexCoord1"); translationUnit.rename("gl_MultiTexCoord2", "gl_MultiTexCoord1");
translationUnit.replaceExpression("gl_MultiTexCoord0", "vec4(_vert_tex_diffuse_coord, 0.0f, 1.0f)"); translationUnit.replaceExpression("gl_MultiTexCoord0", "vec4(_vert_tex_diffuse_coord, 0.0f, 1.0f)");
@@ -61,7 +60,7 @@ public class SodiumTransformer {
translationUnit.rename("gl_Color", "_vert_color"); translationUnit.rename("gl_Color", "_vert_color");
if (parameters.type.glShaderType == ShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
translationUnit.rename("gl_Normal", "iris_Normal"); translationUnit.rename("gl_Normal", "iris_Normal");
translationUnit.injectVariable("in vec3 iris_Normal;"); translationUnit.injectVariable("in vec3 iris_Normal;");
} }
@@ -82,7 +81,7 @@ public class SodiumTransformer {
translationUnit.rename("gl_ModelViewMatrixInverse", "iris_ModelViewMatrixInverse"); translationUnit.rename("gl_ModelViewMatrixInverse", "iris_ModelViewMatrixInverse");
translationUnit.rename("gl_ProjectionMatrixInverse", "iris_ProjectionMatrixInverse"); translationUnit.rename("gl_ProjectionMatrixInverse", "iris_ProjectionMatrixInverse");
if (parameters.type.glShaderType == ShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
// TODO: Vaporwave-Shaderpack expects that vertex positions will be aligned to // TODO: Vaporwave-Shaderpack expects that vertex positions will be aligned to
// chunks. // chunks.
if (translationUnit.containsCall("ftransform")) { if (translationUnit.containsCall("ftransform")) {
@@ -6,7 +6,6 @@ import net.irisshaders.iris.gl.state.ShaderAttributeInputs;
import net.irisshaders.iris.gl.texture.TextureType; import net.irisshaders.iris.gl.texture.TextureType;
import net.irisshaders.iris.helpers.Tri; import net.irisshaders.iris.helpers.Tri;
import net.irisshaders.iris.pipeline.transform.Patch; import net.irisshaders.iris.pipeline.transform.Patch;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.parameter.ComputeParameters; import net.irisshaders.iris.pipeline.transform.parameter.ComputeParameters;
import net.irisshaders.iris.pipeline.transform.parameter.DHParameters; import net.irisshaders.iris.pipeline.transform.parameter.DHParameters;
import net.irisshaders.iris.pipeline.transform.parameter.Parameters; import net.irisshaders.iris.pipeline.transform.parameter.Parameters;
@@ -14,101 +13,62 @@ import net.irisshaders.iris.pipeline.transform.parameter.SodiumParameters;
import net.irisshaders.iris.pipeline.transform.parameter.TextureStageParameters; import net.irisshaders.iris.pipeline.transform.parameter.TextureStageParameters;
import net.irisshaders.iris.pipeline.transform.parameter.VanillaParameters; import net.irisshaders.iris.pipeline.transform.parameter.VanillaParameters;
import net.irisshaders.iris.shaderpack.texture.TextureStage; import net.irisshaders.iris.shaderpack.texture.TextureStage;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import java.lang.reflect.Method;
import java.util.Map; import java.util.Map;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER; import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
public class TransformPatcherBridge { public class TransformPatcherBridge {
private static final boolean USE_GLSL_TRANSFORMER;
private static final Method transformPatcherTransform, transformPatcherTransformCompute; private static Map<ShaderType, String> transform(String name, Map<ShaderType, String> sources,
static {
boolean useGlslTransformer = Boolean.getBoolean("cornea.use_glsl_transformer");
Method transform = null, transformCompute = null;
try {
Class<?> transformPatcher = Class.forName("net.irisshaders.iris.pipeline.transform.TransformPatcher");
transform = transformPatcher.getDeclaredMethod("transform", String.class, String.class, String.class, String.class, String.class, String.class, Parameters.class);
transformCompute = transformPatcher.getDeclaredMethod("transformCompute", String.class, String.class, Parameters.class);
} catch(ReflectiveOperationException e) {
}
if(useGlslTransformer && transform == null) {
IRIS_LOGGER.warn("glsl-transformer is requested, but is not available in this jar");
useGlslTransformer = false;
}
transformPatcherTransform = transform;
transformPatcherTransformCompute = transformCompute;
USE_GLSL_TRANSFORMER = useGlslTransformer;
}
private static Map<PatchShaderType, String> transform(String name, String vertex, String geometry, String tessControl, String tessEval, String fragment,
Parameters parameters) { Parameters parameters) {
if (USE_GLSL_TRANSFORMER) { return ShaderTransformer.transform(name, sources, parameters);
try {
return (Map<PatchShaderType, String>)transformPatcherTransform.invoke(null, name, vertex, geometry, tessControl, tessEval, fragment, parameters);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
} else {
return ShaderTransformer.transform(name, vertex, geometry, tessControl, tessEval, fragment, parameters);
}
} }
private static Map<PatchShaderType, String> transformCompute(String name, String compute, private static Map<ShaderType, String> transformCompute(String name, String compute,
Parameters parameters) { Parameters parameters) {
if (USE_GLSL_TRANSFORMER) {
try {
return (Map<PatchShaderType, String>)transformPatcherTransformCompute.invoke(null, name, compute, parameters);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
} else {
return ShaderTransformer.transformCompute(name, compute, parameters); return ShaderTransformer.transformCompute(name, compute, parameters);
} }
}
public static Map<PatchShaderType, String> patchVanilla( public static Map<ShaderType, String> patchVanilla(
String name, String vertex, String geometry, String tessControl, String tessEval, String fragment, String name, Map<ShaderType, String> sources,
AlphaTest alpha, boolean isLines, AlphaTest alpha, boolean isLines,
boolean hasChunkOffset, boolean hasChunkOffset,
ShaderAttributeInputs inputs, ShaderAttributeInputs inputs,
Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) { Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
return transform(name, vertex, geometry, tessControl, tessEval, fragment, return transform(name,sources,
new VanillaParameters(Patch.VANILLA, textureMap, alpha, isLines, hasChunkOffset, inputs, geometry != null, tessControl != null || tessEval != null)); new VanillaParameters(Patch.VANILLA, textureMap, alpha, isLines, hasChunkOffset, inputs, sources.containsKey(ShaderType.GEOM), sources.containsKey(ShaderType.TESS_CTRL) || sources.containsKey(ShaderType.TESS_EVALUATE)));
} }
public static Map<PatchShaderType, String> patchDHTerrain( public static Map<ShaderType, String> patchDHTerrain(
String name, String vertex, String tessControl, String tessEval, String geometry, String fragment, String name, Map<ShaderType, String> sources,
Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) { Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
return transform(name, vertex, geometry, tessControl, tessEval, fragment, return transform(name, sources,
new DHParameters(Patch.DH_TERRAIN, textureMap)); new DHParameters(Patch.DH_TERRAIN, textureMap));
} }
public static Map<PatchShaderType, String> patchDHGeneric( public static Map<ShaderType, String> patchDHGeneric(
String name, String vertex, String tessControl, String tessEval, String geometry, String fragment, String name, Map<ShaderType, String> sources,
Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) { Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
return transform(name, vertex, geometry, tessControl, tessEval, fragment, return transform(name, sources,
new DHParameters(Patch.DH_GENERIC, textureMap)); new DHParameters(Patch.DH_GENERIC, textureMap));
} }
public static Map<PatchShaderType, String> patchSodium(String name, String vertex, String geometry, String tessControl, String tessEval, String fragment, public static Map<ShaderType, String> patchSodium(String name, Map<ShaderType, String> sources,
AlphaTest alpha, ShaderAttributeInputs inputs, AlphaTest alpha, ShaderAttributeInputs inputs,
Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) { Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
return transform(name, vertex, geometry, tessControl, tessEval, fragment, return transform(name, sources,
new SodiumParameters(Patch.SODIUM, textureMap, alpha, inputs)); new SodiumParameters(Patch.SODIUM, textureMap, alpha, inputs));
} }
public static Map<PatchShaderType, String> patchComposite( public static Map<ShaderType, String> patchComposite(
String name, String vertex, String geometry, String fragment, String name, Map<ShaderType, String> sources,
TextureStage stage, TextureStage stage,
Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) { Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
return transform(name, vertex, geometry, null, null, fragment, new TextureStageParameters(Patch.COMPOSITE, stage, textureMap)); return transform(name, sources, new TextureStageParameters(Patch.COMPOSITE, stage, textureMap));
} }
public static String patchCompute( public static String patchCompute(
@@ -116,6 +76,6 @@ public class TransformPatcherBridge {
TextureStage stage, TextureStage stage,
Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) { Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
return transformCompute(name, compute, new ComputeParameters(Patch.COMPUTE, stage, textureMap)) return transformCompute(name, compute, new ComputeParameters(Patch.COMPUTE, stage, textureMap))
.getOrDefault(PatchShaderType.COMPUTE, null); .getOrDefault(ShaderType.COMPUTE, null);
} }
} }
@@ -1,9 +1,8 @@
package net.irisshaders.iris.pipeline.foss_transform; package net.irisshaders.iris.pipeline.foss_transform;
import net.irisshaders.iris.gl.blending.AlphaTests; import net.irisshaders.iris.gl.blending.AlphaTests;
import net.irisshaders.iris.gl.shader.ShaderType;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.parameter.VanillaParameters; import net.irisshaders.iris.pipeline.transform.parameter.VanillaParameters;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.taumc.glsl.Transformer; import org.taumc.glsl.Transformer;
import static net.irisshaders.iris.pipeline.foss_transform.ShaderTransformer.addIfNotExistsType; import static net.irisshaders.iris.pipeline.foss_transform.ShaderTransformer.addIfNotExistsType;
@@ -22,7 +21,7 @@ public class VanillaTransformer {
ShaderTransformer.commonPatch(translationUnit, parameters, false); ShaderTransformer.commonPatch(translationUnit, parameters, false);
if (parameters.type.glShaderType == ShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
// Alias of gl_MultiTexCoord1 on 1.15+ for OptiFine // Alias of gl_MultiTexCoord1 on 1.15+ for OptiFine
// See https://github.com/IrisShaders/Iris/issues/1149 // See https://github.com/IrisShaders/Iris/issues/1149
translationUnit.rename("gl_MultiTexCoord2", "gl_MultiTexCoord1"); translationUnit.rename("gl_MultiTexCoord2", "gl_MultiTexCoord1");
@@ -58,7 +57,7 @@ public class VanillaTransformer {
translationUnit.injectVariable( translationUnit.injectVariable(
"uniform vec4 iris_ColorModulator;"); "uniform vec4 iris_ColorModulator;");
if (parameters.inputs.hasColor() && parameters.type == PatchShaderType.VERTEX) { if (parameters.inputs.hasColor() && parameters.type == ShaderType.VERTEX) {
// TODO: Handle the fragment / geometry shader here // TODO: Handle the fragment / geometry shader here
if (parameters.alpha == AlphaTests.VERTEX_ALPHA) { if (parameters.alpha == AlphaTests.VERTEX_ALPHA) {
translationUnit.replaceExpression("gl_Color", translationUnit.replaceExpression("gl_Color",
@@ -68,7 +67,7 @@ public class VanillaTransformer {
"(iris_Color * iris_ColorModulator)"); "(iris_Color * iris_ColorModulator)");
} }
if (parameters.type.glShaderType == ShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
translationUnit.injectVariable( translationUnit.injectVariable(
"in vec4 iris_Color;"); "in vec4 iris_Color;");
} }
@@ -82,7 +81,7 @@ public class VanillaTransformer {
translationUnit.rename("gl_Color", "iris_ColorModulator"); translationUnit.rename("gl_Color", "iris_ColorModulator");
} }
if (parameters.type.glShaderType == ShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
if (parameters.inputs.hasNormal()) { if (parameters.inputs.hasNormal()) {
if (!parameters.inputs.isNewLines()) { if (!parameters.inputs.isNewLines()) {
translationUnit.rename("gl_Normal", "iris_Normal"); translationUnit.rename("gl_Normal", "iris_Normal");
@@ -121,7 +120,7 @@ public class VanillaTransformer {
translationUnit.injectVariable("uniform mat4 iris_ProjMatInverse;"); translationUnit.injectVariable("uniform mat4 iris_ProjMatInverse;");
translationUnit.injectVariable("uniform mat4 iris_ModelViewMatInverse;"); translationUnit.injectVariable("uniform mat4 iris_ModelViewMatInverse;");
if (parameters.type.glShaderType == ShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
translationUnit.injectVariable( translationUnit.injectVariable(
"in vec3 iris_Position;"); "in vec3 iris_Position;");
if (translationUnit.containsCall("ftransform")) { if (translationUnit.containsCall("ftransform")) {
@@ -249,7 +248,7 @@ public class VanillaTransformer {
upgradeStorageQualifiers(translationUnit, parameters); upgradeStorageQualifiers(translationUnit, parameters);
if (parameters.type == PatchShaderType.VERTEX) { if (parameters.type == ShaderType.VERTEX) {
translationUnit.replaceExpression("gl_Vertex", "vec4(iris_Position, 1.0)"); translationUnit.replaceExpression("gl_Vertex", "vec4(iris_Position, 1.0)");
translationUnit.rename("vaPosition", "iris_Position"); translationUnit.rename("vaPosition", "iris_Position");
if (parameters.inputs.hasColor()) { if (parameters.inputs.hasColor()) {
@@ -1,32 +0,0 @@
package net.irisshaders.iris.pipeline.transform;
import net.irisshaders.iris.gl.shader.ShaderType;
public enum PatchShaderType {
VERTEX(ShaderType.VERTEX, ".vsh"),
GEOMETRY(ShaderType.GEOMETRY, ".gsh"),
TESS_CONTROL(ShaderType.TESSELATION_CONTROL, ".tcs"),
TESS_EVAL(ShaderType.TESSELATION_EVAL, ".tes"),
FRAGMENT(ShaderType.FRAGMENT, ".fsh"),
COMPUTE(ShaderType.COMPUTE, ".csh");
public final ShaderType glShaderType;
public final String extension;
PatchShaderType(ShaderType glShaderType, String extension) {
this.glShaderType = glShaderType;
this.extension = extension;
}
public static PatchShaderType[] fromGlShaderType(ShaderType glShaderType) {
return switch (glShaderType) {
case VERTEX -> new PatchShaderType[]{VERTEX};
case GEOMETRY -> new PatchShaderType[]{GEOMETRY};
case TESSELATION_CONTROL -> new PatchShaderType[]{TESS_CONTROL};
case TESSELATION_EVAL -> new PatchShaderType[]{TESS_EVAL};
case COMPUTE -> new PatchShaderType[]{COMPUTE};
case FRAGMENT -> new PatchShaderType[]{FRAGMENT};
default -> throw new IllegalArgumentException("Unknown shader type: " + glShaderType);
};
}
}
@@ -1,6 +1,7 @@
package net.irisshaders.iris.pipeline.transform; package net.irisshaders.iris.pipeline.transform;
import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FilenameUtils;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.taumc.celeritas.api.v0.CeleritasShadersApi; import org.taumc.celeritas.api.v0.CeleritasShadersApi;
import java.io.IOException; import java.io.IOException;
@@ -64,7 +65,7 @@ public class ShaderPrinter {
private final String prefix = isActive ? String.format("%03d_", ++programCounter) : null; private final String prefix = isActive ? String.format("%03d_", ++programCounter) : null;
// the prefix and the sources list aren't created if debug is disabled // the prefix and the sources list aren't created if debug is disabled
private final List<String> sources = isActive ? new ArrayList<>(PatchShaderType.values().length * 2) : null; private final List<String> sources = isActive ? new ArrayList<>(ShaderType.values().length * 2) : null;
private String name; private String name;
private boolean done = false; // makes the print function idempotent private boolean done = false; // makes the print function idempotent
@@ -85,19 +86,19 @@ public class ShaderPrinter {
} }
} }
public ProgramPrintBuilder addSource(PatchShaderType type, String source) { public ProgramPrintBuilder addSource(ShaderType type, String source) {
if (sources == null) { if (sources == null) {
return this; return this;
} }
addItem(type.extension, source); addItem("." + type.fileExtension, source);
return this; return this;
} }
public ProgramPrintBuilder addSources(Map<PatchShaderType, String> sources) { public ProgramPrintBuilder addSources(Map<ShaderType, String> sources) {
if (sources == null) { if (sources == null) {
return this; return this;
} }
for (Map.Entry<PatchShaderType, String> entry : sources.entrySet()) { for (Map.Entry<ShaderType, String> entry : sources.entrySet()) {
addSource(entry.getKey(), entry.getValue()); addSource(entry.getKey(), entry.getValue());
} }
return this; return this;
@@ -5,13 +5,13 @@ import net.irisshaders.iris.gl.blending.AlphaTest;
import net.irisshaders.iris.gl.texture.TextureType; import net.irisshaders.iris.gl.texture.TextureType;
import net.irisshaders.iris.helpers.Tri; import net.irisshaders.iris.helpers.Tri;
import net.irisshaders.iris.pipeline.transform.Patch; import net.irisshaders.iris.pipeline.transform.Patch;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.shaderpack.texture.TextureStage; import net.irisshaders.iris.shaderpack.texture.TextureStage;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
public abstract class Parameters { public abstract class Parameters {
public final Patch patch; public final Patch patch;
private final Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap; private final Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap;
public PatchShaderType type; // may only be set by TransformPatcher public ShaderType type; // may only be set by TransformPatcher
// WARNING: adding new fields requires updating hashCode and equals methods! // WARNING: adding new fields requires updating hashCode and equals methods!
public Parameters(Patch patch, Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) { public Parameters(Patch patch, Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
@@ -11,12 +11,9 @@ import net.irisshaders.iris.shaderpack.parsing.DispatchingDirectiveHolder;
import net.irisshaders.iris.shaderpack.properties.PackDirectives; import net.irisshaders.iris.shaderpack.properties.PackDirectives;
import net.irisshaders.iris.shaderpack.properties.PackRenderTargetDirectives; import net.irisshaders.iris.shaderpack.properties.PackRenderTargetDirectives;
import net.irisshaders.iris.shaderpack.properties.ShaderProperties; import net.irisshaders.iris.shaderpack.properties.ShaderProperties;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Function; import java.util.function.Function;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER; import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
@@ -181,30 +178,27 @@ public class ProgramSet implements ProgramSetInterface {
Function<AbsolutePackPath, String> sourceProvider, String program, Function<AbsolutePackPath, String> sourceProvider, String program,
ProgramSet programSet, ShaderProperties properties, ProgramSet programSet, ShaderProperties properties,
BlendModeOverride defaultBlendModeOverride, boolean readTesselation) { BlendModeOverride defaultBlendModeOverride, boolean readTesselation) {
AbsolutePackPath vertexPath = directory.resolve(program + ".vsh"); Map<ShaderType, String> sources = new EnumMap<>(ShaderType.class);
String vertexSource = sourceProvider.apply(vertexPath);
AbsolutePackPath geometryPath = directory.resolve(program + ".gsh"); for (var shaderType : ShaderType.values()) {
String geometrySource = sourceProvider.apply(geometryPath); if (shaderType == ShaderType.COMPUTE) {
continue;
String tessControlSource = null; }
String tessEvalSource = null; if (!readTesselation && (shaderType == ShaderType.TESS_CTRL || shaderType == ShaderType.TESS_EVALUATE)) {
continue;
if (readTesselation) {
AbsolutePackPath tessControlPath = directory.resolve(program + ".tcs");
tessControlSource = sourceProvider.apply(tessControlPath);
AbsolutePackPath tessEvalPath = directory.resolve(program + ".tes");
tessEvalSource = sourceProvider.apply(tessEvalPath);
} }
AbsolutePackPath fragmentPath = directory.resolve(program + ".fsh"); AbsolutePackPath vertexPath = directory.resolve(program + "." + shaderType.fileExtension);
String fragmentSource = sourceProvider.apply(fragmentPath); String source = sourceProvider.apply(vertexPath);
if (source != null) {
sources.put(shaderType, source);
}
}
if (vertexSource == null && fragmentSource != null) { if (!sources.containsKey(ShaderType.VERTEX) && sources.containsKey(ShaderType.FRAGMENT)) {
// This is for really old packs that do not use a vertex shader. // This is for really old packs that do not use a vertex shader.
IRIS_LOGGER.warn("Found a program (" + program + ") that has a fragment shader but no vertex shader? This is very legacy behavior and might not work right."); IRIS_LOGGER.warn("Found a program (" + program + ") that has a fragment shader but no vertex shader? This is very legacy behavior and might not work right.");
vertexSource = """ sources.put(ShaderType.VERTEX, """
#version 120 #version 120
varying vec4 irs_texCoords[3]; varying vec4 irs_texCoords[3];
@@ -217,10 +211,10 @@ public class ProgramSet implements ProgramSetInterface {
irs_texCoords[2] = gl_TextureMatrix[1] * gl_MultiTexCoord2; irs_texCoords[2] = gl_TextureMatrix[1] * gl_MultiTexCoord2;
irs_Color = gl_Color; irs_Color = gl_Color;
} }
"""; """);
} }
return new ProgramSource(program, vertexSource, geometrySource, tessControlSource, tessEvalSource, fragmentSource, programSet, properties, return new ProgramSource(program, sources, programSet, properties,
defaultBlendModeOverride); defaultBlendModeOverride);
} }
@@ -357,7 +351,7 @@ public class ProgramSet implements ProgramSetInterface {
continue; continue;
} }
source.getFragmentSource().map(ConstDirectiveParser::findDirectives).ifPresent(directives -> { source.getSource(ShaderType.FRAGMENT).map(ConstDirectiveParser::findDirectives).ifPresent(directives -> {
for (ConstDirectiveParser.ConstDirective directive : directives) { for (ConstDirectiveParser.ConstDirective directive : directives) {
packDirectiveHolder.processDirective(directive); packDirectiveHolder.processDirective(directive);
} }
@@ -4,70 +4,47 @@ import net.irisshaders.iris.gl.blending.BlendModeOverride;
import net.irisshaders.iris.shaderpack.properties.PackRenderTargetDirectives; import net.irisshaders.iris.shaderpack.properties.PackRenderTargetDirectives;
import net.irisshaders.iris.shaderpack.properties.ProgramDirectives; import net.irisshaders.iris.shaderpack.properties.ProgramDirectives;
import net.irisshaders.iris.shaderpack.properties.ShaderProperties; import net.irisshaders.iris.shaderpack.properties.ShaderProperties;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
public class ProgramSource { public class ProgramSource {
private final String name; private final String name;
private final String vertexSource; private final Map<ShaderType, String> sources = new EnumMap<>(ShaderType.class);
private final String geometrySource; private final Map<ShaderType, String> sourcesView = Collections.unmodifiableMap(sources);
private final String tessControlSource;
private final String tessEvalSource;
private final String fragmentSource;
private final ProgramDirectives directives; private final ProgramDirectives directives;
private final ProgramSet parent; private final ProgramSet parent;
private ProgramSource(String name, String vertexSource, String geometrySource, String tessControlSource, String tessEvalSource, String fragmentSource, public ProgramSource(String name, Map<ShaderType, String> sources,
ProgramDirectives directives, ProgramSet parent) {
this.name = name;
this.vertexSource = vertexSource;
this.geometrySource = geometrySource;
this.tessControlSource = tessControlSource;
this.tessEvalSource = tessEvalSource;
this.fragmentSource = fragmentSource;
this.directives = directives;
this.parent = parent;
}
public ProgramSource(String name, String vertexSource, String geometrySource, String tessControlSource, String tessEvalSource, String fragmentSource,
ProgramSet parent, ShaderProperties properties, BlendModeOverride defaultBlendModeOverride) { ProgramSet parent, ShaderProperties properties, BlendModeOverride defaultBlendModeOverride) {
this.name = name; this.name = name;
this.vertexSource = vertexSource; for (var entry : sources.entrySet()) {
this.geometrySource = geometrySource; if (entry.getValue() != null) {
this.tessControlSource = tessControlSource; this.sources.put(entry.getKey(), entry.getValue());
this.tessEvalSource = tessEvalSource; }
this.fragmentSource = fragmentSource; }
this.parent = parent; this.parent = parent;
this.directives = new ProgramDirectives(this, properties, this.directives = new ProgramDirectives(this, properties,
PackRenderTargetDirectives.BASELINE_SUPPORTED_RENDER_TARGETS, defaultBlendModeOverride); PackRenderTargetDirectives.BASELINE_SUPPORTED_RENDER_TARGETS, defaultBlendModeOverride);
} }
public ProgramSource withDirectiveOverride(ProgramDirectives overrideDirectives) {
return new ProgramSource(name, vertexSource, geometrySource, tessControlSource, tessEvalSource, fragmentSource, overrideDirectives, parent);
}
public String getName() { public String getName() {
return name; return name;
} }
public Optional<String> getVertexSource() { public Optional<String> getSource(ShaderType type) {
return Optional.ofNullable(vertexSource); return Optional.ofNullable(getSourceNullable(type));
} }
public Optional<String> getGeometrySource() { public String getSourceNullable(ShaderType type) {
return Optional.ofNullable(geometrySource); return sources.get(type);
} }
public Optional<String> getTessControlSource() { public Map<ShaderType, String> getSourcesMap() {
return Optional.ofNullable(tessControlSource); return sourcesView;
}
public Optional<String> getTessEvalSource() {
return Optional.ofNullable(tessEvalSource);
}
public Optional<String> getFragmentSource() {
return Optional.ofNullable(fragmentSource);
} }
public ProgramDirectives getDirectives() { public ProgramDirectives getDirectives() {
@@ -79,7 +56,7 @@ public class ProgramSource {
} }
public boolean isValid() { public boolean isValid() {
return vertexSource != null && fragmentSource != null; return sources.containsKey(ShaderType.VERTEX) && sources.containsKey(ShaderType.FRAGMENT);
} }
public Optional<ProgramSource> requireValid() { public Optional<ProgramSource> requireValid() {
@@ -13,6 +13,7 @@ import net.irisshaders.iris.shaderpack.parsing.CommentDirectiveParser;
import net.irisshaders.iris.shaderpack.parsing.ConstDirectiveParser; import net.irisshaders.iris.shaderpack.parsing.ConstDirectiveParser;
import net.irisshaders.iris.shaderpack.parsing.DispatchingDirectiveHolder; import net.irisshaders.iris.shaderpack.parsing.DispatchingDirectiveHolder;
import net.irisshaders.iris.shaderpack.programs.ProgramSource; import net.irisshaders.iris.shaderpack.programs.ProgramSource;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.Arrays; import java.util.Arrays;
@@ -58,8 +59,8 @@ public class ProgramDirectives {
// undefined data to be written to colortex7. // undefined data to be written to colortex7.
// //
// TODO: Figure out how to infer the DRAWBUFFERS directive when it is missing. // TODO: Figure out how to infer the DRAWBUFFERS directive when it is missing.
Optional<CommentDirective> optionalDrawbuffersDirective = findDrawbuffersDirective(source.getFragmentSource()); Optional<CommentDirective> optionalDrawbuffersDirective = findDrawbuffersDirective(source.getSource(ShaderType.FRAGMENT));
Optional<CommentDirective> optionalRendertargetsDirective = findRendertargetsDirective(source.getFragmentSource()); Optional<CommentDirective> optionalRendertargetsDirective = findRendertargetsDirective(source.getSource(ShaderType.FRAGMENT));
Optional<CommentDirective> optionalCommentDirective = getAppliedDirective(optionalDrawbuffersDirective, optionalRendertargetsDirective); Optional<CommentDirective> optionalCommentDirective = getAppliedDirective(optionalDrawbuffersDirective, optionalRendertargetsDirective);
drawBuffers = optionalCommentDirective.map(commentDirective -> { drawBuffers = optionalCommentDirective.map(commentDirective -> {
@@ -112,7 +113,7 @@ public class ProgramDirectives {
} }
}); });
source.getFragmentSource().map(ConstDirectiveParser::findDirectives).ifPresent(directives -> { source.getSource(ShaderType.FRAGMENT).map(ConstDirectiveParser::findDirectives).ifPresent(directives -> {
for (ConstDirectiveParser.ConstDirective directive : directives) { for (ConstDirectiveParser.ConstDirective directive : directives) {
directiveHolder.processDirective(directive); directiveHolder.processDirective(directive);
} }
@@ -14,6 +14,7 @@ import net.irisshaders.iris.shadows.frustum.CommonFrustumHolder;
import net.irisshaders.iris.uniforms.CelestialUniforms; import net.irisshaders.iris.uniforms.CelestialUniforms;
import org.embeddedt.embeddium.compat.mc.MCCamera; import org.embeddedt.embeddium.compat.mc.MCCamera;
import org.embeddedt.embeddium.compat.mc.MCLevelRenderer; import org.embeddedt.embeddium.compat.mc.MCLevelRenderer;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.joml.Matrix4f; import org.joml.Matrix4f;
import org.lwjgl.opengl.ARBTextureSwizzle; import org.lwjgl.opengl.ARBTextureSwizzle;
import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL20C;
@@ -87,7 +88,7 @@ public abstract class CommonShadowRenderer {
if (shadow != null) { if (shadow != null) {
// Assume that the shader pack is doing voxelization if a geometry shader is detected. // Assume that the shader pack is doing voxelization if a geometry shader is detected.
// Also assume voxelization if image load / store is detected. // Also assume voxelization if image load / store is detected.
this.packHasVoxelization = shadow.getGeometrySource().isPresent(); this.packHasVoxelization = shadow.getSource(ShaderType.GEOM).isPresent();
this.packCullingState = shadowDirectives.getCullingState(); this.packCullingState = shadowDirectives.getCullingState();
} else { } else {
this.packHasVoxelization = false; this.packHasVoxelization = false;
@@ -8,6 +8,7 @@ import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import static com.mitchej123.glsm.RenderSystemService.RENDER_SYSTEM; import static com.mitchej123.glsm.RenderSystemService.RENDER_SYSTEM;
import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM; import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@@ -24,7 +25,6 @@ import net.irisshaders.iris.gl.texture.TextureAccess;
import net.irisshaders.iris.pathways.FullScreenQuadRenderer; import net.irisshaders.iris.pathways.FullScreenQuadRenderer;
import net.irisshaders.iris.pipeline.WorldRenderingPipeline; import net.irisshaders.iris.pipeline.WorldRenderingPipeline;
import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge; import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.ShaderPrinter; import net.irisshaders.iris.pipeline.transform.ShaderPrinter;
import net.irisshaders.iris.samplers.IrisImages; import net.irisshaders.iris.samplers.IrisImages;
import net.irisshaders.iris.samplers.IrisSamplers; import net.irisshaders.iris.samplers.IrisSamplers;
@@ -39,6 +39,7 @@ import net.irisshaders.iris.targets.RenderTarget;
import net.irisshaders.iris.uniforms.CommonUniforms; import net.irisshaders.iris.uniforms.CommonUniforms;
import net.irisshaders.iris.uniforms.FrameUpdateNotifier; import net.irisshaders.iris.uniforms.FrameUpdateNotifier;
import net.irisshaders.iris.uniforms.custom.CustomUniforms; import net.irisshaders.iris.uniforms.custom.CustomUniforms;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.lwjgl.opengl.GL15C; import org.lwjgl.opengl.GL15C;
import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL20C;
import org.lwjgl.opengl.GL30C; import org.lwjgl.opengl.GL30C;
@@ -245,14 +246,13 @@ public class ShadowCompositeRenderer {
private Program createProgram(ProgramSource source, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot, private Program createProgram(ProgramSource source, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot,
ShadowRenderTargets targets) { ShadowRenderTargets targets) {
// TODO: Properly handle empty shaders // TODO: Properly handle empty shaders
Map<PatchShaderType, String> transformed = TransformPatcherBridge.patchComposite( Preconditions.checkArgument(source.isValid());
Map<ShaderType, String> transformed = TransformPatcherBridge.patchComposite(
source.getName(), source.getName(),
source.getVertexSource().orElseThrow(NullPointerException::new), source.getSourcesMap(), TextureStage.SHADOWCOMP, pipeline.getTextureMap());
source.getGeometrySource().orElse(null), String vertex = transformed.get(ShaderType.VERTEX);
source.getFragmentSource().orElseThrow(NullPointerException::new), TextureStage.SHADOWCOMP, pipeline.getTextureMap()); String geometry = transformed.get(ShaderType.GEOMETRY);
String vertex = transformed.get(PatchShaderType.VERTEX); String fragment = transformed.get(ShaderType.FRAGMENT);
String geometry = transformed.get(PatchShaderType.GEOMETRY);
String fragment = transformed.get(PatchShaderType.FRAGMENT);
ShaderPrinter.printProgram(source.getName()).addSources(transformed).print(); ShaderPrinter.printProgram(source.getName()).addSources(transformed).print();
Objects.requireNonNull(flipped); Objects.requireNonNull(flipped);
@@ -298,7 +298,7 @@ public class ShadowCompositeRenderer {
try { try {
String transformed = TransformPatcherBridge.patchCompute(source.getName(), source.getSource().orElse(null), TextureStage.SHADOWCOMP, pipeline.getTextureMap()); String transformed = TransformPatcherBridge.patchCompute(source.getName(), source.getSource().orElse(null), TextureStage.SHADOWCOMP, pipeline.getTextureMap());
ShaderPrinter.printProgram(source.getName()).addSource(PatchShaderType.COMPUTE, transformed).print(); ShaderPrinter.printProgram(source.getName()).addSource(ShaderType.COMPUTE, transformed).print();
builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
} catch (RuntimeException e) { } catch (RuntimeException e) {
@@ -2,18 +2,18 @@ package net.irisshaders.iris.targets;
import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER; import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import net.irisshaders.iris.gl.GlResource;
import net.irisshaders.iris.gl.IrisRenderSystem; import net.irisshaders.iris.gl.IrisRenderSystem;
import net.irisshaders.iris.gl.texture.DepthBufferFormat; import net.irisshaders.iris.gl.texture.DepthBufferFormat;
import org.embeddedt.embeddium.impl.gl.GlObject;
import org.embeddedt.embeddium.impl.gl.debug.GLDebug; import org.embeddedt.embeddium.impl.gl.debug.GLDebug;
import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL11C;
import org.lwjgl.opengl.GL13C; import org.lwjgl.opengl.GL13C;
import org.lwjgl.opengl.GL43C; import org.lwjgl.opengl.GL43C;
public class DepthTexture extends GlResource { public class DepthTexture extends GlObject {
public DepthTexture(String name, int width, int height, DepthBufferFormat format) { public DepthTexture(String name, int width, int height, DepthBufferFormat format) {
super(IrisRenderSystem.createTexture(GL11C.GL_TEXTURE_2D)); this.setHandle(IrisRenderSystem.createTexture(GL11C.GL_TEXTURE_2D));
int texture = getGlId(); int texture = handle();
resize(width, height, format); resize(width, height, format);
GLDebug.nameObject(GL43C.GL_TEXTURE, texture, name); GLDebug.nameObject(GL43C.GL_TEXTURE, texture, name);
@@ -32,11 +32,11 @@ public class DepthTexture extends GlResource {
} }
public int getTextureId() { public int getTextureId() {
return getGlId(); return handle();
} }
@Override @Override
protected void destroyInternal() { protected void destroyInternal() {
GL_STATE_MANAGER.glDeleteTextures(getGlId()); GL_STATE_MANAGER.glDeleteTextures(handle());
} }
} }
@@ -79,7 +79,7 @@ public class RenderTargets {
destroyed = true; destroyed = true;
for (GlFramebuffer owned : ownedFramebuffers) { for (GlFramebuffer owned : ownedFramebuffers) {
owned.destroy(); owned.delete();
} }
for (RenderTarget target : targets) { for (RenderTarget target : targets) {
@@ -88,8 +88,8 @@ public class RenderTargets {
} }
} }
noTranslucents.destroy(); noTranslucents.delete();
noHand.destroy(); noHand.delete();
} }
public int getRenderTargetCount() { public int getRenderTargetCount() {
@@ -347,7 +347,7 @@ public class RenderTargets {
if (drawBuffers[i] >= getRenderTargetCount()) { if (drawBuffers[i] >= getRenderTargetCount()) {
// TODO: This causes resource leaks, also we should really verify this in the shaderpack parser... // TODO: This causes resource leaks, also we should really verify this in the shaderpack parser...
framebuffer.destroy(); framebuffer.delete();
ownedFramebuffers.remove(framebuffer); ownedFramebuffers.remove(framebuffer);
throw new IllegalStateException("Render target with index " + drawBuffers[i] + " is not supported, only " throw new IllegalStateException("Render target with index " + drawBuffers[i] + " is not supported, only "
+ getRenderTargetCount() + " render targets are supported."); + getRenderTargetCount() + " render targets are supported.");
@@ -373,7 +373,7 @@ public class RenderTargets {
} }
public void destroyFramebuffer(GlFramebuffer framebuffer) { public void destroyFramebuffer(GlFramebuffer framebuffer) {
framebuffer.destroy(); framebuffer.delete();
ownedFramebuffers.remove(framebuffer); ownedFramebuffers.remove(framebuffer);
} }
@@ -5,9 +5,9 @@ import java.util.Random;
import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER; import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import net.irisshaders.iris.gl.GlResource;
import net.irisshaders.iris.gl.IrisRenderSystem; import net.irisshaders.iris.gl.IrisRenderSystem;
import net.irisshaders.iris.gl.texture.TextureUploadHelper; import net.irisshaders.iris.gl.texture.TextureUploadHelper;
import org.embeddedt.embeddium.impl.gl.GlObject;
import org.embeddedt.embeddium.impl.gl.debug.GLDebug; import org.embeddedt.embeddium.impl.gl.debug.GLDebug;
import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL11C;
import org.lwjgl.opengl.GL13C; import org.lwjgl.opengl.GL13C;
@@ -18,14 +18,14 @@ import org.lwjgl.opengl.GL43C;
* An extremely simple noise texture. Each color channel contains a uniform random value from 0 to 255. Essentially just * An extremely simple noise texture. Each color channel contains a uniform random value from 0 to 255. Essentially just
* dumps an array of random bytes into a texture and calls it a day, literally could not be any simpler than that. * dumps an array of random bytes into a texture and calls it a day, literally could not be any simpler than that.
*/ */
public class NoiseTexture extends GlResource { public class NoiseTexture extends GlObject {
int width; int width;
int height; int height;
public NoiseTexture(int width, int height) { public NoiseTexture(int width, int height) {
super(IrisRenderSystem.createTexture(GL11C.GL_TEXTURE_2D)); this.setHandle(IrisRenderSystem.createTexture(GL11C.GL_TEXTURE_2D));
int texture = getGlId(); int texture = handle();
IrisRenderSystem.texParameteri(texture, GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_MIN_FILTER, GL11C.GL_LINEAR); IrisRenderSystem.texParameteri(texture, GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_MIN_FILTER, GL11C.GL_LINEAR);
IrisRenderSystem.texParameteri(texture, GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_MAG_FILTER, GL11C.GL_LINEAR); IrisRenderSystem.texParameteri(texture, GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_MAG_FILTER, GL11C.GL_LINEAR);
IrisRenderSystem.texParameteri(texture, GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_WRAP_S, GL13C.GL_REPEAT); IrisRenderSystem.texParameteri(texture, GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_WRAP_S, GL13C.GL_REPEAT);
@@ -71,11 +71,11 @@ public class NoiseTexture extends GlResource {
} }
public int getTextureId() { public int getTextureId() {
return getGlId(); return handle();
} }
@Override @Override
protected void destroyInternal() { protected void destroyInternal() {
GL_STATE_MANAGER.glDeleteTextures(getGlId()); GL_STATE_MANAGER.glDeleteTextures(handle());
} }
} }
@@ -4,18 +4,18 @@ import java.nio.ByteBuffer;
import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER; import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import net.irisshaders.iris.gl.GlResource;
import net.irisshaders.iris.gl.IrisRenderSystem; import net.irisshaders.iris.gl.IrisRenderSystem;
import net.irisshaders.iris.gl.texture.TextureUploadHelper; import net.irisshaders.iris.gl.texture.TextureUploadHelper;
import org.embeddedt.embeddium.impl.gl.GlObject;
import org.embeddedt.embeddium.impl.gl.debug.GLDebug; import org.embeddedt.embeddium.impl.gl.debug.GLDebug;
import org.lwjgl.BufferUtils; import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL11C;
import org.lwjgl.opengl.GL13C; import org.lwjgl.opengl.GL13C;
import org.lwjgl.opengl.GL43C; import org.lwjgl.opengl.GL43C;
public class SingleColorTexture extends GlResource { public class SingleColorTexture extends GlObject {
public SingleColorTexture(int red, int green, int blue, int alpha) { public SingleColorTexture(int red, int green, int blue, int alpha) {
super(IrisRenderSystem.createTexture(GL11C.GL_TEXTURE_2D)); this.setHandle(IrisRenderSystem.createTexture(GL11C.GL_TEXTURE_2D));
ByteBuffer pixel = BufferUtils.createByteBuffer(4); ByteBuffer pixel = BufferUtils.createByteBuffer(4);
pixel.put((byte) red); pixel.put((byte) red);
pixel.put((byte) green); pixel.put((byte) green);
@@ -23,7 +23,7 @@ public class SingleColorTexture extends GlResource {
pixel.put((byte) alpha); pixel.put((byte) alpha);
pixel.position(0); pixel.position(0);
int texture = getGlId(); int texture = handle();
GLDebug.nameObject(GL43C.GL_TEXTURE, texture, "single color (" + red + ", " + green + "," + blue + "," + alpha + ")"); GLDebug.nameObject(GL43C.GL_TEXTURE, texture, "single color (" + red + ", " + green + "," + blue + "," + alpha + ")");
@@ -37,11 +37,11 @@ public class SingleColorTexture extends GlResource {
} }
public int getTextureId() { public int getTextureId() {
return getGlId(); return handle();
} }
@Override @Override
protected void destroyInternal() { protected void destroyInternal() {
GL_STATE_MANAGER.glDeleteTextures(getGlId()); GL_STATE_MANAGER.glDeleteTextures(handle());
} }
} }
@@ -35,7 +35,15 @@ public abstract class GlObject {
return this.handle != INVALID_HANDLE; return this.handle != INVALID_HANDLE;
} }
public final void invalidateHandle() { public final void delete() {
this.destroyInternal();
this.handle = INVALID_HANDLE; this.handle = INVALID_HANDLE;
} }
@Deprecated // kept around to avoid huge diffs in old Iris code
public final void destroy() {
this.delete();
}
protected abstract void destroyInternal();
} }
@@ -12,4 +12,9 @@ public class GlVertexArray extends GlObject {
public GlVertexArray() { public GlVertexArray() {
this.setHandle(GL30C.glGenVertexArrays()); this.setHandle(GL30C.glGenVertexArrays());
} }
@Override
protected void destroyInternal() {
GL30C.glDeleteVertexArrays(this.handle());
}
} }
@@ -17,4 +17,9 @@ public abstract class GlBuffer extends GlObject {
public void setActiveMapping(GlBufferMapping mapping) { public void setActiveMapping(GlBufferMapping mapping) {
this.activeMapping = mapping; this.activeMapping = mapping;
} }
@Override
protected void destroyInternal() {
GL20C.glDeleteBuffers(this.handle());
}
} }
@@ -135,20 +135,14 @@ public class GLRenderDevice implements RenderDevice {
this.stateTracker.notifyBufferDeleted(buffer); this.stateTracker.notifyBufferDeleted(buffer);
int handle = buffer.handle(); buffer.delete();
buffer.invalidateHandle();
GL20C.glDeleteBuffers(handle);
} }
@Override @Override
public void deleteVertexArray(GlVertexArray vertexArray) { public void deleteVertexArray(GlVertexArray vertexArray) {
this.stateTracker.notifyVertexArrayDeleted(vertexArray); this.stateTracker.notifyVertexArrayDeleted(vertexArray);
int handle = vertexArray.handle(); vertexArray.delete();
vertexArray.invalidateHandle();
GL30C.glDeleteVertexArrays(handle);
} }
@Override @Override
@@ -44,10 +44,9 @@ public class GlProgram<T> extends GlObject implements ShaderBindingContext {
GL20C.glUseProgram(0); GL20C.glUseProgram(0);
} }
public void delete() { @Override
protected void destroyInternal() {
GL20C.glDeleteProgram(this.handle()); GL20C.glDeleteProgram(this.handle());
this.invalidateHandle();
} }
@Override @Override
@@ -43,9 +43,8 @@ public class GlShader extends GlObject {
return this.name; return this.name;
} }
public void delete() { @Override
protected void destroyInternal() {
GL20C.glDeleteShader(this.handle()); GL20C.glDeleteShader(this.handle());
this.invalidateHandle();
} }
} }
@@ -1,22 +1,31 @@
package org.embeddedt.embeddium.impl.gl.shader; package org.embeddedt.embeddium.impl.gl.shader;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL20C;
import org.lwjgl.opengl.GL32C; import org.lwjgl.opengl.GL32C;
import org.lwjgl.opengl.GL42C; import org.lwjgl.opengl.GL42C;
import org.lwjgl.opengl.GL43C;
/** /**
* An enumeration over the supported OpenGL shader types. * An enumeration over the supported OpenGL shader types.
*/ */
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public enum ShaderType { public enum ShaderType {
VERTEX(GL20C.GL_VERTEX_SHADER), VERTEX(GL20C.GL_VERTEX_SHADER, "vsh"),
FRAGMENT(GL20C.GL_FRAGMENT_SHADER), FRAGMENT(GL20C.GL_FRAGMENT_SHADER, "fsh"),
GEOM(GL32C.GL_GEOMETRY_SHADER), GEOM(GL32C.GL_GEOMETRY_SHADER, "gsh"),
TESS_CTRL(GL42C.GL_TESS_CONTROL_SHADER), TESS_CTRL(GL42C.GL_TESS_CONTROL_SHADER, "tcs"),
TESS_EVALUATE(GL42C.GL_TESS_EVALUATION_SHADER); TESS_EVALUATE(GL42C.GL_TESS_EVALUATION_SHADER, "tes"),
COMPUTE(GL43C.GL_COMPUTE_SHADER, "csh");
@Deprecated
public static final ShaderType TESSELATION_CONTROL = ShaderType.TESS_CTRL;
@Deprecated
public static final ShaderType TESSELATION_EVAL = ShaderType.TESS_EVALUATE;
@Deprecated
public static final ShaderType GEOMETRY = ShaderType.GEOM;
public final int id; public final int id;
public final String fileExtension;
ShaderType(int id) {
this.id = id;
}
} }
@@ -8,6 +8,7 @@ import java.util.Map;
import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER; import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import static com.mitchej123.glsm.RenderSystemService.RENDER_SYSTEM; import static com.mitchej123.glsm.RenderSystemService.RENDER_SYSTEM;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints; import com.google.common.primitives.Ints;
import com.seibel.distanthorizons.api.interfaces.override.rendering.IDhApiGenericObjectShaderProgram; import com.seibel.distanthorizons.api.interfaces.override.rendering.IDhApiGenericObjectShaderProgram;
import com.seibel.distanthorizons.api.interfaces.render.IDhApiRenderableBoxGroup; import com.seibel.distanthorizons.api.interfaces.render.IDhApiRenderableBoxGroup;
@@ -25,13 +26,11 @@ import net.irisshaders.iris.gl.blending.BufferBlendOverride;
import net.irisshaders.iris.gl.program.ProgramImages; import net.irisshaders.iris.gl.program.ProgramImages;
import net.irisshaders.iris.gl.program.ProgramSamplers; import net.irisshaders.iris.gl.program.ProgramSamplers;
import net.irisshaders.iris.gl.program.ProgramUniforms; import net.irisshaders.iris.gl.program.ProgramUniforms;
import net.irisshaders.iris.gl.shader.GlShader;
import net.irisshaders.iris.gl.shader.ShaderType;
import net.irisshaders.iris.gl.state.FogMode; import net.irisshaders.iris.gl.state.FogMode;
import net.irisshaders.iris.gl.texture.TextureType; import net.irisshaders.iris.gl.texture.TextureType;
import net.irisshaders.iris.pipeline.ModernIrisRenderingPipeline; import net.irisshaders.iris.pipeline.ModernIrisRenderingPipeline;
import net.irisshaders.iris.pipeline.foss_transform.ShaderTransformer;
import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge; import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.ShaderPrinter; import net.irisshaders.iris.pipeline.transform.ShaderPrinter;
import net.irisshaders.iris.samplers.IrisSamplers; import net.irisshaders.iris.samplers.IrisSamplers;
import net.irisshaders.iris.shaderpack.programs.ProgramSource; import net.irisshaders.iris.shaderpack.programs.ProgramSource;
@@ -39,6 +38,8 @@ import net.irisshaders.iris.uniforms.CommonUniforms;
import net.irisshaders.iris.uniforms.builtin.BuiltinReplacementUniforms; import net.irisshaders.iris.uniforms.builtin.BuiltinReplacementUniforms;
import net.irisshaders.iris.uniforms.custom.CustomUniforms; import net.irisshaders.iris.uniforms.custom.CustomUniforms;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import org.embeddedt.embeddium.impl.gl.shader.GlShader;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.joml.Matrix3f; import org.joml.Matrix3f;
import org.joml.Matrix4f; import org.joml.Matrix4f;
import org.lwjgl.opengl.GL30C; import org.lwjgl.opengl.GL30C;
@@ -81,28 +82,28 @@ public class IrisGenericRenderProgram implements IDhApiGenericObjectShaderProgra
this.bufferBlendOverrides = bufferBlendOverrides; this.bufferBlendOverrides = bufferBlendOverrides;
GlShader vert = new GlShader(ShaderType.VERTEX, name + ".vsh", vertex); GlShader vert = new GlShader(ShaderType.VERTEX, name + ".vsh", vertex);
GL43C.glAttachShader(id, vert.getHandle()); GL43C.glAttachShader(id, vert.handle());
GlShader tessCont = null; GlShader tessCont = null;
if (tessControl != null) { if (tessControl != null) {
tessCont = new GlShader(ShaderType.TESSELATION_CONTROL, name + ".tcs", tessControl); tessCont = new GlShader(ShaderType.TESSELATION_CONTROL, name + ".tcs", tessControl);
GL43C.glAttachShader(id, tessCont.getHandle()); GL43C.glAttachShader(id, tessCont.handle());
} }
GlShader tessE = null; GlShader tessE = null;
if (tessEval != null) { if (tessEval != null) {
tessE = new GlShader(ShaderType.TESSELATION_EVAL, name + ".tes", tessEval); tessE = new GlShader(ShaderType.TESSELATION_EVAL, name + ".tes", tessEval);
GL43C.glAttachShader(id, tessE.getHandle()); GL43C.glAttachShader(id, tessE.handle());
} }
GlShader geom = null; GlShader geom = null;
if (geometry != null) { if (geometry != null) {
geom = new GlShader(ShaderType.GEOMETRY, name + ".gsh", geometry); geom = new GlShader(ShaderType.GEOMETRY, name + ".gsh", geometry);
GL43C.glAttachShader(id, geom.getHandle()); GL43C.glAttachShader(id, geom.handle());
} }
GlShader frag = new GlShader(ShaderType.FRAGMENT, name + ".fsh", fragment); GlShader frag = new GlShader(ShaderType.FRAGMENT, name + ".fsh", fragment);
GL43C.glAttachShader(id, frag.getHandle()); GL43C.glAttachShader(id, frag.handle());
GL32.glLinkProgram(this.id); GL32.glLinkProgram(this.id);
int status = GL32.glGetProgrami(this.id, 35714); int status = GL32.glGetProgrami(this.id, 35714);
@@ -156,19 +157,16 @@ public class IrisGenericRenderProgram implements IDhApiGenericObjectShaderProgra
} }
public static IrisGenericRenderProgram createProgram(String name, boolean isShadowPass, boolean translucent, ProgramSource source, CustomUniforms uniforms, ModernIrisRenderingPipeline pipeline) { public static IrisGenericRenderProgram createProgram(String name, boolean isShadowPass, boolean translucent, ProgramSource source, CustomUniforms uniforms, ModernIrisRenderingPipeline pipeline) {
Map<PatchShaderType, String> transformed = TransformPatcherBridge.patchDHGeneric( Preconditions.checkArgument(source.isValid());
Map<ShaderType, String> transformed = TransformPatcherBridge.patchDHGeneric(
name, name,
source.getVertexSource().orElseThrow(RuntimeException::new), source.getSourcesMap(),
source.getTessControlSource().orElse(null),
source.getTessEvalSource().orElse(null),
source.getGeometrySource().orElse(null),
source.getFragmentSource().orElseThrow(RuntimeException::new),
pipeline.getTextureMap()); pipeline.getTextureMap());
String vertex = transformed.get(PatchShaderType.VERTEX); String vertex = transformed.get(ShaderType.VERTEX);
String tessControl = transformed.get(PatchShaderType.TESS_CONTROL); String tessControl = transformed.get(ShaderType.TESS_CTRL);
String tessEval = transformed.get(PatchShaderType.TESS_EVAL); String tessEval = transformed.get(ShaderType.TESS_EVALUATE);
String geometry = transformed.get(PatchShaderType.GEOMETRY); String geometry = transformed.get(ShaderType.GEOMETRY);
String fragment = transformed.get(PatchShaderType.FRAGMENT); String fragment = transformed.get(ShaderType.FRAGMENT);
ShaderPrinter.printProgram(name + "_g") ShaderPrinter.printProgram(name + "_g")
.addSources(transformed) .addSources(transformed)
.setName("dh_" + name + "_g") .setName("dh_" + name + "_g")
@@ -7,6 +7,7 @@ import java.util.Map;
import static com.mitchej123.glsm.RenderSystemService.RENDER_SYSTEM; import static com.mitchej123.glsm.RenderSystemService.RENDER_SYSTEM;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints; import com.google.common.primitives.Ints;
import com.seibel.distanthorizons.api.DhApi; import com.seibel.distanthorizons.api.DhApi;
import com.seibel.distanthorizons.api.objects.math.DhApiVec3f; import com.seibel.distanthorizons.api.objects.math.DhApiVec3f;
@@ -16,13 +17,10 @@ import net.irisshaders.iris.gl.blending.BufferBlendOverride;
import net.irisshaders.iris.gl.program.ProgramImages; import net.irisshaders.iris.gl.program.ProgramImages;
import net.irisshaders.iris.gl.program.ProgramSamplers; import net.irisshaders.iris.gl.program.ProgramSamplers;
import net.irisshaders.iris.gl.program.ProgramUniforms; import net.irisshaders.iris.gl.program.ProgramUniforms;
import net.irisshaders.iris.gl.shader.GlShader;
import net.irisshaders.iris.gl.shader.ShaderType;
import net.irisshaders.iris.gl.state.FogMode; import net.irisshaders.iris.gl.state.FogMode;
import net.irisshaders.iris.gl.texture.TextureType; import net.irisshaders.iris.gl.texture.TextureType;
import net.irisshaders.iris.pipeline.ModernIrisRenderingPipeline; import net.irisshaders.iris.pipeline.ModernIrisRenderingPipeline;
import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge; import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.ShaderPrinter; import net.irisshaders.iris.pipeline.transform.ShaderPrinter;
import net.irisshaders.iris.samplers.IrisSamplers; import net.irisshaders.iris.samplers.IrisSamplers;
import net.irisshaders.iris.shaderpack.programs.ProgramSource; import net.irisshaders.iris.shaderpack.programs.ProgramSource;
@@ -30,6 +28,8 @@ import net.irisshaders.iris.uniforms.CommonUniforms;
import net.irisshaders.iris.uniforms.builtin.BuiltinReplacementUniforms; import net.irisshaders.iris.uniforms.builtin.BuiltinReplacementUniforms;
import net.irisshaders.iris.uniforms.custom.CustomUniforms; import net.irisshaders.iris.uniforms.custom.CustomUniforms;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import org.embeddedt.embeddium.impl.gl.shader.GlShader;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.joml.Matrix3f; import org.joml.Matrix3f;
import org.joml.Matrix4f; import org.joml.Matrix4f;
import org.joml.Matrix4fc; import org.joml.Matrix4fc;
@@ -68,28 +68,28 @@ public class IrisLodRenderProgram {
this.bufferBlendOverrides = bufferBlendOverrides; this.bufferBlendOverrides = bufferBlendOverrides;
GlShader vert = new GlShader(ShaderType.VERTEX, name + ".vsh", vertex); GlShader vert = new GlShader(ShaderType.VERTEX, name + ".vsh", vertex);
GL43C.glAttachShader(id, vert.getHandle()); GL43C.glAttachShader(id, vert.handle());
GlShader tessCont = null; GlShader tessCont = null;
if (tessControl != null) { if (tessControl != null) {
tessCont = new GlShader(ShaderType.TESSELATION_CONTROL, name + ".tcs", tessControl); tessCont = new GlShader(ShaderType.TESSELATION_CONTROL, name + ".tcs", tessControl);
GL43C.glAttachShader(id, tessCont.getHandle()); GL43C.glAttachShader(id, tessCont.handle());
} }
GlShader tessE = null; GlShader tessE = null;
if (tessEval != null) { if (tessEval != null) {
tessE = new GlShader(ShaderType.TESSELATION_EVAL, name + ".tes", tessEval); tessE = new GlShader(ShaderType.TESSELATION_EVAL, name + ".tes", tessEval);
GL43C.glAttachShader(id, tessE.getHandle()); GL43C.glAttachShader(id, tessE.handle());
} }
GlShader geom = null; GlShader geom = null;
if (geometry != null) { if (geometry != null) {
geom = new GlShader(ShaderType.GEOMETRY, name + ".gsh", geometry); geom = new GlShader(ShaderType.GEOMETRY, name + ".gsh", geometry);
GL43C.glAttachShader(id, geom.getHandle()); GL43C.glAttachShader(id, geom.handle());
} }
GlShader frag = new GlShader(ShaderType.FRAGMENT, name + ".fsh", fragment); GlShader frag = new GlShader(ShaderType.FRAGMENT, name + ".fsh", fragment);
GL43C.glAttachShader(id, frag.getHandle()); GL43C.glAttachShader(id, frag.handle());
GL32.glLinkProgram(this.id); GL32.glLinkProgram(this.id);
int status = GL32.glGetProgrami(this.id, 35714); int status = GL32.glGetProgrami(this.id, 35714);
@@ -136,19 +136,16 @@ public class IrisLodRenderProgram {
} }
public static IrisLodRenderProgram createProgram(String name, boolean isShadowPass, boolean translucent, ProgramSource source, CustomUniforms uniforms, ModernIrisRenderingPipeline pipeline) { public static IrisLodRenderProgram createProgram(String name, boolean isShadowPass, boolean translucent, ProgramSource source, CustomUniforms uniforms, ModernIrisRenderingPipeline pipeline) {
Map<PatchShaderType, String> transformed = TransformPatcherBridge.patchDHTerrain( Preconditions.checkArgument(source.isValid());
Map<ShaderType, String> transformed = TransformPatcherBridge.patchDHTerrain(
name, name,
source.getVertexSource().orElseThrow(RuntimeException::new), source.getSourcesMap(),
source.getTessControlSource().orElse(null),
source.getTessEvalSource().orElse(null),
source.getGeometrySource().orElse(null),
source.getFragmentSource().orElseThrow(RuntimeException::new),
pipeline.getTextureMap()); pipeline.getTextureMap());
String vertex = transformed.get(PatchShaderType.VERTEX); String vertex = transformed.get(ShaderType.VERTEX);
String tessControl = transformed.get(PatchShaderType.TESS_CONTROL); String tessControl = transformed.get(ShaderType.TESS_CTRL);
String tessEval = transformed.get(PatchShaderType.TESS_EVAL); String tessEval = transformed.get(ShaderType.TESS_EVALUATE);
String geometry = transformed.get(PatchShaderType.GEOMETRY); String geometry = transformed.get(ShaderType.GEOMETRY);
String fragment = transformed.get(PatchShaderType.FRAGMENT); String fragment = transformed.get(ShaderType.FRAGMENT);
ShaderPrinter.printProgram(name) ShaderPrinter.printProgram(name)
.addSources(transformed) .addSources(transformed)
.setName("dh_" + name) .setName("dh_" + name)
@@ -11,214 +11,73 @@ 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 net.irisshaders.iris.Iris; import net.irisshaders.iris.Iris;
import net.irisshaders.iris.gl.blending.AlphaTest;
import net.irisshaders.iris.gl.blending.AlphaTests;
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;
import net.irisshaders.iris.gl.framebuffer.GlFramebuffer;
import net.irisshaders.iris.pipeline.SodiumTerrainPipeline; import net.irisshaders.iris.pipeline.SodiumTerrainPipeline;
import net.irisshaders.iris.pipeline.WorldRenderingPipeline; import net.irisshaders.iris.pipeline.WorldRenderingPipeline;
import net.irisshaders.iris.shadows.ShadowRenderingState; import net.irisshaders.iris.shadows.ShadowRenderingState;
import net.minecraft.client.Minecraft;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL43C; import org.lwjgl.opengl.GL43C;
import java.util.EnumMap; import java.util.*;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
public class IrisChunkProgramOverrides { public class IrisChunkProgramOverrides {
private static final List<ShaderType> RELEVANT_SHADER_TYPES = List.of(ShaderType.VERTEX, ShaderType.GEOM, ShaderType.TESS_CTRL, ShaderType.TESS_EVALUATE, ShaderType.FRAGMENT);
private final EnumMap<IrisTerrainPass, GlProgram<IrisChunkShaderInterface>> programs = new EnumMap<>(IrisTerrainPass.class); private final EnumMap<IrisTerrainPass, GlProgram<IrisChunkShaderInterface>> programs = new EnumMap<>(IrisTerrainPass.class);
private boolean shadersCreated = false; private boolean shadersCreated = false;
private int versionCounterForSodiumShaderReload = -1; private int versionCounterForSodiumShaderReload = -1;
private GlShader createVertexShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { private GlShader createShader(ShaderType type, IrisTerrainPass pass, SodiumTerrainPipeline pipeline) {
Optional<String> irisVertexShader; Optional<String> irisVertexShader;
if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { if (pass == IrisTerrainPass.SHADOW_CUTOUT && type != ShaderType.FRAGMENT) {
irisVertexShader = pipeline.getShadowVertexShaderSource(); pass = IrisTerrainPass.SHADOW;
} else if (pass == IrisTerrainPass.GBUFFER_SOLID) { }
irisVertexShader = pipeline.getTerrainSolidVertexShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { var info = pipeline.getPassInfo(pass);
irisVertexShader = pipeline.getTerrainCutoutVertexShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { if (info == null) {
irisVertexShader = pipeline.getTranslucentVertexShaderSource();
} else {
throw new IllegalArgumentException("Unknown pass type " + pass); throw new IllegalArgumentException("Unknown pass type " + pass);
} }
irisVertexShader = info.sources().get(type);
String source = irisVertexShader.orElse(null); String source = irisVertexShader.orElse(null);
if (source == null) { if (source == null) {
return null; return null;
} }
return new GlShader(ShaderType.VERTEX, "iris:" + return new GlShader(type, "iris:" +
"sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".vsh", source); "sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + "." + type.fileExtension, source);
}
private GlShader createGeometryShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) {
Optional<String> irisGeometryShader;
if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) {
irisGeometryShader = pipeline.getShadowGeometryShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_SOLID) {
irisGeometryShader = pipeline.getTerrainSolidGeometryShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) {
irisGeometryShader = pipeline.getTerrainCutoutGeometryShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) {
irisGeometryShader = pipeline.getTranslucentGeometryShaderSource();
} else {
throw new IllegalArgumentException("Unknown pass type " + pass);
}
String source = irisGeometryShader.orElse(null);
if (source == null) {
return null;
}
return new GlShader(ShaderType.GEOM, "iris:" +
"sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".gsh", source);
}
private GlShader createTessControlShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) {
Optional<String> irisTessControlShader;
if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) {
irisTessControlShader = pipeline.getShadowTessControlShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_SOLID) {
irisTessControlShader = pipeline.getTerrainSolidTessControlShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) {
irisTessControlShader = pipeline.getTerrainCutoutTessControlShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) {
irisTessControlShader = pipeline.getTranslucentTessControlShaderSource();
} else {
throw new IllegalArgumentException("Unknown pass type " + pass);
}
String source = irisTessControlShader.orElse(null);
if (source == null) {
return null;
}
return new GlShader(ShaderType.TESS_CTRL, "iris:" +
"sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".tcs", source);
}
private GlShader createTessEvalShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) {
Optional<String> irisTessEvalShader;
if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) {
irisTessEvalShader = pipeline.getShadowTessEvalShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_SOLID) {
irisTessEvalShader = pipeline.getTerrainSolidTessEvalShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) {
irisTessEvalShader = pipeline.getTerrainCutoutTessEvalShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) {
irisTessEvalShader = pipeline.getTranslucentTessEvalShaderSource();
} else {
throw new IllegalArgumentException("Unknown pass type " + pass);
}
String source = irisTessEvalShader.orElse(null);
if (source == null) {
return null;
}
return new GlShader(ShaderType.TESS_EVALUATE, "iris:" +
"sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".tes", source);
}
private GlShader createFragmentShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) {
Optional<String> irisFragmentShader;
if (pass == IrisTerrainPass.SHADOW) {
irisFragmentShader = pipeline.getShadowFragmentShaderSource();
} else if (pass == IrisTerrainPass.SHADOW_CUTOUT) {
irisFragmentShader = pipeline.getShadowCutoutFragmentShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_SOLID) {
irisFragmentShader = pipeline.getTerrainSolidFragmentShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) {
irisFragmentShader = pipeline.getTerrainCutoutFragmentShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) {
irisFragmentShader = pipeline.getTranslucentFragmentShaderSource();
} else {
throw new IllegalArgumentException("Unknown pass type " + pass);
}
String source = irisFragmentShader.orElse(null);
if (source == null) {
return null;
}
return new GlShader(ShaderType.FRAGMENT, "iris:" +
"sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".fsh", source);
} }
private BlendModeOverride getBlendOverride(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { private BlendModeOverride getBlendOverride(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) {
if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { return pipeline.getPassInfo(pass).blendModeOverride();
return pipeline.getShadowBlendOverride();
} else if (pass == IrisTerrainPass.GBUFFER_SOLID) {
return pipeline.getTerrainSolidBlendOverride();
} else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) {
return pipeline.getTerrainCutoutBlendOverride();
} else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) {
return pipeline.getTranslucentBlendOverride();
} else {
throw new IllegalArgumentException("Unknown pass type " + pass);
}
} }
private List<BufferBlendOverride> getBufferBlendOverride(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { private List<BufferBlendOverride> getBufferBlendOverride(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) {
if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { return pipeline.getPassInfo(pass).bufferOverrides();
return pipeline.getShadowBufferOverrides();
} else if (pass == IrisTerrainPass.GBUFFER_SOLID) {
return pipeline.getTerrainSolidBufferOverrides();
} else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) {
return pipeline.getTerrainCutoutBufferOverrides();
} else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) {
return pipeline.getTranslucentBufferOverrides();
} else {
throw new IllegalArgumentException("Unknown pass type " + pass);
}
} }
@Nullable @Nullable
private GlProgram<IrisChunkShaderInterface> createShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline, RenderPassConfiguration configuration) { private GlProgram<IrisChunkShaderInterface> createShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline, RenderPassConfiguration configuration) {
GlShader vertShader = createVertexShader(pass, pipeline); Map<ShaderType, GlShader> createdShaders = new EnumMap<>(ShaderType.class);
GlShader geomShader = createGeometryShader(pass, pipeline);
GlShader tessCShader = createTessControlShader(pass, pipeline); for (var type : RELEVANT_SHADER_TYPES) {
GlShader tessEShader = createTessEvalShader(pass, pipeline); var shader = createShader(type, pass, pipeline);
GlShader fragShader = createFragmentShader(pass, pipeline); if (shader != null) {
createdShaders.put(type, shader);
}
}
BlendModeOverride blendOverride = getBlendOverride(pass, pipeline); BlendModeOverride blendOverride = getBlendOverride(pass, pipeline);
List<BufferBlendOverride> bufferOverrides = getBufferBlendOverride(pass, pipeline); List<BufferBlendOverride> bufferOverrides = getBufferBlendOverride(pass, pipeline);
float alpha = getAlphaReference(pass, pipeline); float alpha = getAlphaReference(pass, pipeline);
if (vertShader == null || fragShader == null) { if (createdShaders.get(ShaderType.VERTEX) == null || createdShaders.get(ShaderType.FRAGMENT) == null) {
if (vertShader != null) { createdShaders.values().forEach(GlShader::delete);
vertShader.delete();
}
if (geomShader != null) {
geomShader.delete();
}
if (tessCShader != null) {
tessCShader.delete();
}
if (tessEShader != null) {
tessEShader.delete();
}
if (fragShader != null) {
fragShader.delete();
}
// TODO: Partial shader programs? // TODO: Partial shader programs?
return null; return null;
@@ -228,18 +87,8 @@ public class IrisChunkProgramOverrides {
GlProgram.Builder builder = GlProgram.builder("sodium:chunk_shader_for_" GlProgram.Builder builder = GlProgram.builder("sodium:chunk_shader_for_"
+ pass.getName()); + pass.getName());
if (geomShader != null) { createdShaders.values().forEach(builder::attachShader);
builder.attachShader(geomShader);
}
if (tessCShader != null) {
builder.attachShader(tessCShader);
}
if (tessEShader != null) {
builder.attachShader(tessEShader);
}
builder.attachShader(vertShader)
.attachShader(fragShader);
int i = 0; int i = 0;
var vertexType = configuration.getVertexTypeForPass(pass.toTerrainPass(configuration)); var vertexType = configuration.getVertexTypeForPass(pass.toTerrainPass(configuration));
for (var attr : vertexType.getVertexFormat().getAttributes()) { for (var attr : vertexType.getVertexFormat().getAttributes()) {
@@ -251,35 +100,15 @@ public class IrisChunkProgramOverrides {
ShaderBindingContext contextExt = shader; ShaderBindingContext contextExt = shader;
GLDebug.nameObject(GL43C.GL_PROGRAM, handle, "sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT)); GLDebug.nameObject(GL43C.GL_PROGRAM, handle, "sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT));
return new IrisChunkShaderInterface(handle, contextExt, pipeline, new ChunkShaderOptions(ChunkFogMode.SMOOTH, pass.toTerrainPass(configuration)), return new IrisChunkShaderInterface(handle, contextExt, pipeline, new ChunkShaderOptions(ChunkFogMode.SMOOTH, pass.toTerrainPass(configuration)),
tessCShader != null || tessEShader != null, pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT, blendOverride, bufferOverrides, alpha, pipeline.getCustomUniforms()); createdShaders.get(ShaderType.TESS_CTRL) != null || createdShaders.get(ShaderType.TESS_EVALUATE) != null, pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT, blendOverride, bufferOverrides, alpha, pipeline.getCustomUniforms());
}); });
} finally { } finally {
vertShader.delete(); createdShaders.values().forEach(GlShader::delete);
if (geomShader != null) {
geomShader.delete();
}
if (tessCShader != null) {
tessCShader.delete();
}
if (tessEShader != null) {
tessEShader.delete();
}
fragShader.delete();
} }
} }
private float getAlphaReference(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { private float getAlphaReference(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) {
if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { return pipeline.getPassInfo(pass).alphaTest().orElseThrow(() -> new IllegalStateException("Expected alpha test to be available")).reference();
return pipeline.getShadowAlpha().orElse(AlphaTests.ONE_TENTH_ALPHA).reference();
} else if (pass == IrisTerrainPass.GBUFFER_SOLID) {
return AlphaTest.ALWAYS.reference();
} else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) {
return pipeline.getTerrainCutoutAlpha().orElse(AlphaTests.ONE_TENTH_ALPHA).reference();
} else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) {
return pipeline.getTranslucentAlpha().orElse(AlphaTest.ALWAYS).reference();
} else {
throw new IllegalArgumentException("Unknown pass type " + pass);
}
} }
public void createShaders(SodiumTerrainPipeline pipeline, RenderPassConfiguration configuration) { public void createShaders(SodiumTerrainPipeline pipeline, RenderPassConfiguration configuration) {
@@ -216,11 +216,11 @@ public class IrisChunkShaderInterface implements ChunkShaderInterface {
GlFramebuffer framebuffer; GlFramebuffer framebuffer;
if (isShadowPass) { if (isShadowPass) {
framebuffer = pipeline.getShadowFramebuffer(); framebuffer = pipeline.getPassInfo(IrisTerrainPass.SHADOW).framebuffer();
} else if (pass.isReverseOrder()) { } else if (pass.isReverseOrder()) {
framebuffer = pipeline.getTranslucentFramebuffer(); framebuffer = pipeline.getPassInfo(IrisTerrainPass.GBUFFER_TRANSLUCENT).framebuffer();
} else { } else {
framebuffer = pipeline.getTerrainSolidFramebuffer(); framebuffer = pipeline.getPassInfo(IrisTerrainPass.GBUFFER_SOLID).framebuffer();
} }
if (framebuffer != null) { if (framebuffer != null) {
@@ -1,5 +1,6 @@
package net.irisshaders.iris.pipeline.programs; package net.irisshaders.iris.pipeline.programs;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Ints; import com.google.common.primitives.Ints;
import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.DefaultVertexFormat;
@@ -15,7 +16,6 @@ import net.irisshaders.iris.pipeline.ModernIrisRenderingPipeline;
import net.irisshaders.iris.pipeline.WorldRenderingPipeline; import net.irisshaders.iris.pipeline.WorldRenderingPipeline;
import net.irisshaders.iris.pipeline.fallback.ShaderSynthesizer; import net.irisshaders.iris.pipeline.fallback.ShaderSynthesizer;
import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge; import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge;
import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.ShaderPrinter; import net.irisshaders.iris.pipeline.transform.ShaderPrinter;
import net.irisshaders.iris.shaderpack.loading.ProgramId; import net.irisshaders.iris.shaderpack.loading.ProgramId;
import net.irisshaders.iris.shaderpack.programs.ProgramSource; import net.irisshaders.iris.shaderpack.programs.ProgramSource;
@@ -36,6 +36,7 @@ import net.minecraft.server.packs.repository.PackSource;
import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceProvider; import net.minecraft.server.packs.resources.ResourceProvider;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.embeddedt.embeddium.compat.mc.MCVertexFormat; import org.embeddedt.embeddium.compat.mc.MCVertexFormat;
import org.embeddedt.embeddium.impl.util.ComponentUtil; import org.embeddedt.embeddium.impl.util.ComponentUtil;
@@ -63,21 +64,18 @@ public class ShaderCreator {
BlendModeOverride blendModeOverride = source.getDirectives().getBlendModeOverride().orElse(programId.getBlendModeOverride()); BlendModeOverride blendModeOverride = source.getDirectives().getBlendModeOverride().orElse(programId.getBlendModeOverride());
return CompletableFuture.supplyAsync(() -> { return CompletableFuture.supplyAsync(() -> {
Preconditions.checkArgument(source.isValid());
return TransformPatcherBridge.patchVanilla( return TransformPatcherBridge.patchVanilla(
name, name,
source.getVertexSource().orElseThrow(RuntimeException::new), source.getSourcesMap(),
source.getGeometrySource().orElse(null),
source.getTessControlSource().orElse(null),
source.getTessEvalSource().orElse(null),
source.getFragmentSource().orElseThrow(RuntimeException::new),
alpha, isLines, true, inputs, pipeline.getTextureMap()); alpha, isLines, true, inputs, pipeline.getTextureMap());
}, Util.backgroundExecutor()).thenApplyAsync(transformed -> { }, Util.backgroundExecutor()).thenApplyAsync(transformed -> {
String vertex = transformed.get(PatchShaderType.VERTEX); String vertex = transformed.get(ShaderType.VERTEX);
String geometry = transformed.get(PatchShaderType.GEOMETRY); String geometry = transformed.get(ShaderType.GEOMETRY);
String tessControl = transformed.get(PatchShaderType.TESS_CONTROL); String tessControl = transformed.get(ShaderType.TESS_CTRL);
String tessEval = transformed.get(PatchShaderType.TESS_EVAL); String tessEval = transformed.get(ShaderType.TESS_EVALUATE);
String fragment = transformed.get(PatchShaderType.FRAGMENT); String fragment = transformed.get(ShaderType.FRAGMENT);
String shaderJsonString = String.format(""" String shaderJsonString = String.format("""
{ {
@@ -189,8 +187,8 @@ public class ShaderCreator {
] ]
}""", name, name); }""", name, name);
ShaderPrinter.printProgram(name) ShaderPrinter.printProgram(name)
.addSource(PatchShaderType.VERTEX, vertex) .addSource(ShaderType.VERTEX, vertex)
.addSource(PatchShaderType.FRAGMENT, fragment) .addSource(ShaderType.FRAGMENT, fragment)
.addJson(shaderJsonString) .addJson(shaderJsonString)
.print(); .print();
@@ -48,6 +48,8 @@ import net.minecraft.world.level.block.entity.BlockEntity;
import org.embeddedt.embeddium.compat.mc.MCCamera; import org.embeddedt.embeddium.compat.mc.MCCamera;
import org.embeddedt.embeddium.compat.mc.MCLevelRenderer; import org.embeddedt.embeddium.compat.mc.MCLevelRenderer;
import org.embeddedt.embeddium.impl.gl.debug.GLDebug; import org.embeddedt.embeddium.impl.gl.debug.GLDebug;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.embeddedt.embeddium.impl.render.viewport.ViewportProvider; import org.embeddedt.embeddium.impl.render.viewport.ViewportProvider;
import org.embeddedt.embeddium.impl.util.WorldUtil; import org.embeddedt.embeddium.impl.util.WorldUtil;
import org.embeddedt.embeddium.impl.world.WorldRendererExtended; import org.embeddedt.embeddium.impl.world.WorldRendererExtended;