Mipmap stuff again (#2300)

This commit is contained in:
Eclipse-Sol authored and GitHub committed 2026-10-25 19:25:54 -07:00
1 parent 17a2ed7f37
commit 1772e9eae2
56 files changed
+1872 -529

No files matched your search

@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.common;
import com.gtnewhorizons.angelica.rendering.TextureAtlasType;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
@@ -39,7 +40,7 @@ public class BlockError extends Block {
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void onTextureStitch(TextureStitchEvent.Pre event) {
if (event.map.getTextureType() == 0) {
if (event.map.getTextureType() == TextureAtlasType.BLOCK) {
for (int i = 0; i < icons.length; i++) {
icons[i] = event.map.registerIcon("angelica:error_block_" + i);
}
@@ -73,6 +73,7 @@ public enum Mixins implements IMixins {
, "angelica.textures.MixinRenderItem_GuiSupersampling"
, "angelica.textures.MixinTileEntityRendererDispatcher_GuiSupersampling"
, "angelica.gui.MixinGuiIngameForge_ModernF3"
, "angelica.textures.MixinRenderItem_GuiSampler"
)
),
@@ -456,6 +457,7 @@ public enum Mixins implements IMixins {
, "celeritas.frustum.MixinClippingHelperImpl"
, "celeritas.frustum.MixinFrustrum"
, "celeritas.features.culling.MixinEffectRenderer"
, "celeritas.features.mipmaps.MixinEffectRenderer"
, "celeritas.features.mipmaps.MixinTextureAtlasSprite"
, "celeritas.features.mipmaps.MixinTextureMetadataSection"
, "celeritas.features.mipmaps.MixinTextureMetadataSectionSerializer"
@@ -894,6 +896,11 @@ public enum Mixins implements IMixins {
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins("client.dragonapi.MixinThrottleableEffectRenderer")
),
DRAGONAPI_PARTICLE_CUTOFF(new MixinBuilder("Modern 26.2 mipmap alpha cutoff for DragonAPI's terrain particles")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.DRAGON_API)
.addClientMixins("client.dragonapi.MixinThrottleableEffectRenderer_MipmapCutoff")
),
DRAGONAPI_PARTICLE_BATCH(new MixinBuilder("Particle instancing for DragonAPI's replacement particle renderer")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.DRAGON_API)
@@ -7,4 +7,8 @@ public interface TextureMetadataExtension {
void angelica$setMipmapStrategy(MipmapStrategy strategy);
MipmapStrategy angelica$getMipmapStrategy();
void angelica$setAlphaCutoffBias(float bias);
float angelica$getAlphaCutoffBias();
}
@@ -79,6 +79,7 @@ import com.gtnewhorizons.angelica.rendering.AngelicaBlockSafetyRegistry;
import com.gtnewhorizons.angelica.rendering.FpsReducer;
import com.gtnewhorizons.angelica.rendering.FramePacer;
import com.gtnewhorizons.angelica.rendering.IsbrhTestRenderer;
import com.gtnewhorizons.angelica.rendering.TextureSamplers;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasDebugScreenHandler;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasSetup;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer;
@@ -169,6 +170,7 @@ public final class ClientProxy extends CommonProxy {
HUDCaching.init();
}
CeleritasSetup.ensureInitialized();
TextureSamplers.initRenderer();
DarkModeUtils.init();
final SodiumGameOptions opts = options();
if (opts.advanced.vsyncMode == null) {
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.render;
import com.gtnewhorizons.angelica.rendering.TextureAtlasType;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@@ -22,7 +23,7 @@ public class EmissiveTextureAutoloader {
@SubscribeEvent
public void onTextureStitchPre(TextureStitchEvent.Pre event) {
if (event.map.getTextureType() != 0) return;
if (event.map.getTextureType() != TextureAtlasType.BLOCK) return;
TextureMap map = event.map;
EmissiveTextureHelper.clearCache();
@@ -0,0 +1,8 @@
package com.gtnewhorizons.angelica.rendering;
public final class TextureAtlasType {
public static final int BLOCK = 0;
public static final int ITEM = 1;
private TextureAtlasType() {}
}
@@ -0,0 +1,32 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import lombok.Getter;
import net.coderbot.iris.gl.sampler.GlSampler;
import org.lwjgl.opengl.EXTTextureFilterAnisotropic;
public final class TextureSamplers {
private static final GlSampler[][] TERRAIN_SAMPLERS = new GlSampler[2][17];
@Getter
private static GlSampler guiSampler;
private TextureSamplers() {
}
public static void initRenderer() {
guiSampler = new GlSampler(false, false, false, false, false, true);
}
public static GlSampler getTerrainSampler(boolean linear, int anisotropy) {
final GlSampler[] samplers = TERRAIN_SAMPLERS[linear ? 1 : 0];
GlSampler sampler = samplers[anisotropy];
if (sampler == null) {
sampler = new GlSampler(linear, true, true, false, false, true);
if (anisotropy > 1) {
RenderSystem.samplerParameterf(sampler.getId(), EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropy);
}
samplers[anisotropy] = sampler;
}
return sampler;
}
}
@@ -8,6 +8,7 @@ import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.rendering.culling.GpuTerrainCuller;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import com.gtnewhorizons.angelica.rendering.TextureSamplers;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
import com.gtnewhorizons.angelica.rendering.culling.GpuCulling;
@@ -20,6 +21,7 @@ import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.program.ComputeProgram;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.samplers.IrisSamplers;
import net.coderbot.iris.shadows.ShadowRenderingState;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.DirectMultiDrawBatch;
@@ -52,9 +54,6 @@ import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.EXTTextureFilterAnisotropic;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL20;
import java.util.ArrayList;
@@ -65,15 +64,7 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
private static final Tracy.ZoneId Z_CHUNK_BEGIN = Tracy.zoneId("chunkBegin", Tracy.COLOR_TERRAIN);
private static final Tracy.ZoneId Z_CHUNK_ASSEMBLE_REGION = Tracy.zoneId("chunkAssembleRegion", Tracy.COLOR_TERRAIN);
private GlProgram<? extends ChunkShaderInterface> irisProgram;
private boolean usingIrisProgram;
private int terrainSampler;
private boolean terrainSamplerResolved;
private int terrainSamplerAnisotropy = -1;
private boolean terrainSamplerNearest;
private int packTerrainSampler;
private boolean packTerrainSamplerResolved;
private int packTerrainSamplerAnisotropy = -1;
private GlProgram<ChunkShaderInterface> irisProgram;
private boolean terrainSamplerBound;
private final GpuTerrainCuller culler;
private final SdlShadowVoxelizationSink shadowVoxelSink = new SdlShadowVoxelizationSink();
@@ -160,21 +151,19 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
// Check if Iris shaders are active and we have an override
if (provider != null && provider.isShadersEnabled()) {
final GlProgram<? extends ChunkShaderInterface> override = provider.getShaderOverride(pass);
final GlProgram<ChunkShaderInterface> override = provider.getShaderOverride(pass);
if (override != null) {
pass.startDrawing();
this.irisProgram = override;
this.activeProgram = override;
override.bind();
override.getInterface().setupState(pass);
this.activeProgram = (GlProgram<ChunkShaderInterface>) override;
this.irisProgram = override;
this.usingIrisProgram = true;
bindPackTerrainSampler();
return;
}
}
// Fall back to default shader
this.usingIrisProgram = false;
this.irisProgram = null;
beginDefault(pass);
bindTerrainSampler();
@@ -211,85 +200,43 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
@Override
protected void end(TerrainRenderPass pass) {
unbindTerrainSampler();
if (usingIrisProgram && irisProgram != null) {
irisProgram.getInterface().restoreState();
irisProgram.unbind();
irisProgram = null;
usingIrisProgram = false;
this.activeProgram = null;
pass.endDrawing();
return;
if (irisProgram != null) {
endIrisPass(pass);
} else {
super.end(pass);
}
}
super.end(pass);
private void endIrisPass(TerrainRenderPass pass) {
final GlProgram<ChunkShaderInterface> program = irisProgram;
irisProgram = null;
activeProgram = null;
try {
program.getInterface().restoreState();
} finally {
try {
program.unbind();
} finally {
pass.endDrawing();
}
}
}
private void bindTerrainSampler() {
if (!SodiumGameOptions.usesTerrainTexelSnap()) {
return;
}
final int anisotropy = SodiumGameOptions.resolvedAnisotropicFiltering();
final boolean nearest = ClientProxy.options().quality.texelSampling.isNearest();
if (!terrainSamplerResolved || terrainSamplerAnisotropy != anisotropy
|| terrainSamplerNearest != nearest) {
if (!terrainSamplerResolved) {
terrainSampler = RenderSystem.genSampler();
if (terrainSampler == 0) {
AngelicaMod.LOGGER.warn("Sampler objects unavailable; terrain filtering will fall back to the atlas texture's own parameters");
}
}
terrainSamplerResolved = true;
terrainSamplerAnisotropy = anisotropy;
terrainSamplerNearest = nearest;
configureTerrainSampler(terrainSampler, nearest, anisotropy);
}
if (terrainSampler != 0) {
RenderSystem.bindSamplerToUnit(BLOCK_TEXTURE_UNIT, terrainSampler);
terrainSamplerBound = true;
if (SodiumGameOptions.usesTerrainTexelSnap()) {
bindBlockSampler(TextureSamplers.getTerrainSampler(!ClientProxy.options().quality.texelSampling.isNearest(),
SodiumGameOptions.resolvedAnisotropicFiltering()).getId());
}
}
private void bindPackTerrainSampler() {
final int anisotropy = SodiumGameOptions.resolvedAnisotropicFiltering();
if (!packTerrainSamplerResolved || packTerrainSamplerAnisotropy != anisotropy) {
if (!packTerrainSamplerResolved) {
packTerrainSampler = RenderSystem.genSampler();
if (packTerrainSampler == 0) {
AngelicaMod.LOGGER.warn("Sampler objects unavailable; shader pack terrain filtering will fall back to the atlas texture's own parameters");
}
}
packTerrainSamplerResolved = true;
packTerrainSamplerAnisotropy = anisotropy;
configureTerrainSampler(packTerrainSampler, true, anisotropy);
}
if (packTerrainSampler != 0) {
RenderSystem.bindSamplerToUnit(BLOCK_TEXTURE_UNIT, packTerrainSampler);
terrainSamplerBound = true;
}
bindBlockSampler(IrisSamplers.getTerrainSampler(SodiumGameOptions.resolvedAnisotropicFiltering()).getId());
}
private static void configureTerrainSampler(int sampler, boolean nearest, int anisotropy) {
if (sampler == 0) {
return;
}
RenderSystem.samplerParameteri(sampler, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
RenderSystem.samplerParameteri(sampler, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
RenderSystem.samplerParameteri(sampler, GL11.GL_TEXTURE_MIN_FILTER,
nearest ? GL11.GL_NEAREST_MIPMAP_LINEAR : GL11.GL_LINEAR_MIPMAP_LINEAR);
RenderSystem.samplerParameteri(sampler, GL11.GL_TEXTURE_MAG_FILTER,
nearest ? GL11.GL_NEAREST : GL11.GL_LINEAR);
if (SodiumGameOptions.anisotropySupported()) {
RenderSystem.samplerParameterf(sampler,
EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, (float) anisotropy);
private void bindBlockSampler(int id) {
if (id != 0) {
RenderSystem.bindSamplerToUnit(BLOCK_TEXTURE_UNIT, id);
terrainSamplerBound = true;
}
}
@@ -311,15 +258,6 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
shadowVoxelSink.delete();
unbindTerrainSampler();
RenderSystem.destroySampler(terrainSampler);
terrainSampler = 0;
terrainSamplerResolved = false;
terrainSamplerAnisotropy = -1;
terrainSamplerNearest = false;
RenderSystem.destroySampler(packTerrainSampler);
packTerrainSampler = 0;
packTerrainSamplerResolved = false;
packTerrainSamplerAnisotropy = -1;
}
@Override
@@ -357,8 +295,11 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
voxelizeShadowTerrain(matrices, renderLists, renderPass, occlusionCamera, camera);
super.render(matrices, commandList, renderLists, renderPass, occlusionCamera, camera);
} finally {
if (culler != null) {
culler.endPass();
try {
if (irisProgram != null) endIrisPass(renderPass);
} finally {
unbindTerrainSampler();
if (culler != null) culler.endPass();
}
}
}
@@ -469,7 +410,7 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
@Override
protected void configureShaderInterface(ChunkShaderInterface shader) {
if (!usingIrisProgram) {
if (irisProgram == null) {
shader.setTextureSlot(ChunkShaderTextureSlot.BLOCK, 0);
shader.setTextureSlot(ChunkShaderTextureSlot.LIGHT, 1);
}
@@ -8,6 +8,7 @@ import com.gtnewhorizons.angelica.utils.SpritePadding;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap;
import lombok.Getter;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions;
import me.jellysquid.mods.sodium.client.gui.options.named.MipmapGeneration;
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
@@ -27,9 +28,11 @@ public class AngelicaRenderPassConfiguration {
@Getter
private static boolean rgssEnabled;
private static TerrainRenderPass.TerrainRenderPassBuilder builderForRenderType(int pass, boolean disableAlphaTest, ChunkVertexType vertexType) {
private static TerrainRenderPass.TerrainRenderPassBuilder builderForRenderType(int pass, boolean disableAlphaTest,
AlphaCutoffParameter alphaCutoff, ChunkVertexType vertexType) {
final TerrainRenderPass.TerrainRenderPassBuilder builder = TerrainRenderPass.builder()
.pipelineState(new AngelicaPipelineState(pass, disableAlphaTest))
.pipelineState(new AngelicaPipelineState(pass, disableAlphaTest, alphaCutoff))
.fragmentDiscard(!disableAlphaTest && alphaCutoff != AlphaCutoffParameter.ZERO)
.vertexType(vertexType)
.primitiveType(QuadPrimitiveType.TRIANGULATED);
@@ -61,27 +64,25 @@ public class AngelicaRenderPassConfiguration {
public static RenderPassConfiguration<BlockRenderLayer> build(ChunkVertexType vertexType) {
rgssEnabled = SodiumGameOptions.effectiveTextureFilterMode().usesRgss();
final AlphaCutoffParameter translucentCutoff = MipmapGeneration.alphaFloorCutoff();
SOLID_PASS = builderForRenderType(0, true, vertexType)
SOLID_PASS = builderForRenderType(0, true, AlphaCutoffParameter.HALF, vertexType)
.name("solid")
.fragmentDiscard(false)
.useReverseOrder(false)
.build();
CUTOUT_MIPPED_PASS = builderForRenderType(0, false, vertexType)
CUTOUT_MIPPED_PASS = builderForRenderType(0, false, AlphaCutoffParameter.HALF, vertexType)
.name("cutout_mipped")
.fragmentDiscard(true)
.useReverseOrder(false)
.build();
TRANSLUCENT_PASS = builderForRenderType(1, false, vertexType)
TRANSLUCENT_PASS = builderForRenderType(1, false, translucentCutoff, vertexType)
.name("translucent")
.fragmentDiscard(false)
.useReverseOrder(true)
.useTranslucencySorting(ClientProxy.options().performance.translucencySorting)
.build();
TRANSLUCENT_MATERIAL = new Material(TRANSLUCENT_PASS, AlphaCutoffParameter.ZERO, true);
TRANSLUCENT_MATERIAL = new Material(TRANSLUCENT_PASS, translucentCutoff, true);
SOLID_MATERIAL = new Material(SOLID_PASS, AlphaCutoffParameter.ZERO, true);
CUTOUT_MIPPED_MATERIAL = new Material(CUTOUT_MIPPED_PASS, AlphaCutoffParameter.HALF, true);
CUTOUT_MATERIAL = new Material(CUTOUT_MIPPED_PASS, AlphaCutoffParameter.ONE_TENTH, false);
@@ -105,24 +106,29 @@ public class AngelicaRenderPassConfiguration {
private static final class AngelicaPipelineState implements TerrainRenderPass.PipelineState {
private final int pass;
private final boolean disableAlphaTest;
private final float alphaCutoff;
private int alphaStateDepth = -1;
private AngelicaPipelineState(int pass, boolean disableAlphaTest) {
private AngelicaPipelineState(int pass, boolean disableAlphaTest, AlphaCutoffParameter alphaCutoff) {
this.pass = pass;
this.disableAlphaTest = disableAlphaTest;
this.alphaCutoff = alphaCutoff.cutoff();
}
@Override
public void setup() {
GLStateManager.glDepthMask(true);
if (pass == 0) {
if (alphaCutoff > 0.0f) {
if (alphaStateDepth >= 0) {
GLStateManager.popStateTo(alphaStateDepth);
alphaStateDepth = -1;
}
alphaStateDepth = GLStateManager.pushState(StateSet.ALPHA);
GLStateManager.glAlphaFunc(GL11.GL_GREATER, AlphaCutoffParameter.HALF.cutoff());
GLStateManager.glAlphaFunc(GL11.GL_GREATER, alphaCutoff);
if (pass == 1) {
GLStateManager.enableAlphaTest();
}
}
if (disableAlphaTest) {
GLStateManager.disableAlphaTest();
@@ -11,7 +11,11 @@ public interface SpriteExtension {
/** One-shot: returns true if marked, then resets. */
boolean celeritas$shouldUpdate();
void celeritas$setMipmapStrategy(MipmapStrategy strategy, boolean explicit, int textureType);
void celeritas$setMipmapStrategy(MipmapStrategy strategy, boolean explicit);
void angelica$setTextureType(int textureType);
void angelica$setAlphaCutoffBias(float bias);
/** Width of the replicated-edge border reserved around this sprite in its stitcher slot. */
int angelica$getGutterWidth();
@@ -19,7 +19,7 @@ public interface IrisShaderProvider {
boolean shouldUseFaceCulling();
@Nullable GlProgram<? extends ChunkShaderInterface> getShaderOverride(TerrainRenderPass pass);
@Nullable GlProgram<ChunkShaderInterface> getShaderOverride(TerrainRenderPass pass);
ChunkVertexType getVertexType(ChunkVertexType defaultType);
@@ -0,0 +1,20 @@
package com.gtnewhorizons.angelica.rendering.particles;
import me.jellysquid.mods.sodium.client.gui.options.named.MipmapGeneration;
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.parameters.AlphaCutoffParameter;
public final class ParticleAlphaCutoff {
private static final int TERRAIN_PARTICLE_LAYER = 1;
private ParticleAlphaCutoff() {
}
public static float forLayer(float original, int layer) {
if (layer != TERRAIN_PARTICLE_LAYER) {
return original;
}
final AlphaCutoffParameter cutoff = MipmapGeneration.alphaFloorCutoff();
return cutoff == AlphaCutoffParameter.ZERO ? original : cutoff.cutoff();
}
}
@@ -0,0 +1,230 @@
package com.gtnewhorizons.angelica.utils;
import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue;
import org.embeddedt.embeddium.api.util.ColorARGB;
import org.embeddedt.embeddium.impl.texture.MipmapHelper;
import static com.gtnewhorizons.angelica.utils.MipmapGenerator.ALPHA_BIAS;
import static org.joml.Math.clamp;
final class CeleritasMipmapGenerator {
private CeleritasMipmapGenerator() {
}
static int[][] generateMipLevels(int mipLevel, int width, int[][] currentMips,
boolean isCutout, boolean darkCutout, float cutoutRef) {
final int[][] result = new int[mipLevel + 1][];
final int[] base = currentMips[0];
if (mipLevel > 0 && (currentMips.length == 1 || currentMips[1] == null)) {
if (darkCutout) {
MipmapGenerator.fillEmptyAreasWithDarkColor(base, 1);
} else {
solidify(base, width, base.length / width);
}
}
result[0] = base;
if (mipLevel <= 0) {
return result;
}
final float originalCoverage = isCutout ? alphaTestCoverage(base, width, cutoutRef, 1.0f) : 0.0f;
for (int level = 1; level <= mipLevel; level++) {
final int levelWidth = width >> level;
final int[] provided = level < currentMips.length ? currentMips[level] : null;
if (provided != null) {
result[level] = provided;
} else {
final int[] input = result[level - 1];
final int prevWidth = width >> (level - 1);
final int prevHeight = input.length / prevWidth;
final int levelHeight = prevHeight >> 1;
final int[] output = new int[levelWidth * levelHeight];
for (int y = 0; y < levelHeight; y++) {
for (int x = 0; x < levelWidth; x++) {
final int i = x * 2 + y * 2 * prevWidth;
output[x + y * levelWidth] = MipmapHelper.weightedAverageColor(
MipmapHelper.weightedAverageColor(input[i], input[i + 1]),
MipmapHelper.weightedAverageColor(input[i + prevWidth], input[i + prevWidth + 1]));
}
}
result[level] = output;
}
if (isCutout) {
scaleAlphaToCoverage(result[level], levelWidth, originalCoverage, cutoutRef);
}
}
return result;
}
private static void solidify(int[] image, int width, int height) {
final int size = Math.min(width * height, image.length);
if (size <= 0) {
return;
}
boolean hasTransparent = false;
for (int i = 0; i < size; i++) {
if (ColorARGB.unpackAlpha(image[i]) == 0) {
hasTransparent = true;
break;
}
}
if (!hasTransparent) {
return;
}
final int[] color = new int[size];
final IntArrayFIFOQueue queue = new IntArrayFIFOQueue(64);
for (int i = 0; i < size; i++) {
final int pixel = image[i];
if (ColorARGB.unpackAlpha(pixel) == 0) {
continue;
}
color[i] = pixel;
if (hasTransparentNeighbor(image, i, width, size)) {
queue.enqueue(i);
}
}
if (queue.isEmpty()) {
return;
}
while (!queue.isEmpty()) {
final int index = queue.dequeueInt();
final int x = index % width;
final int source = color[index];
if (x > 0) {
fill(index - 1, source, color, queue);
}
if (x < width - 1) {
fill(index + 1, source, color, queue);
}
if (index >= width) {
fill(index - width, source, color, queue);
}
if (index + width < size) {
fill(index + width, source, color, queue);
}
}
for (int i = 0; i < size; i++) {
if (ColorARGB.unpackAlpha(image[i]) == 0) {
image[i] = color[i] & 0x00FFFFFF;
}
}
}
private static boolean hasTransparentNeighbor(int[] image, int index, int width, int size) {
final int x = index % width;
return (x > 0 && ColorARGB.unpackAlpha(image[index - 1]) == 0)
|| (x < width - 1 && ColorARGB.unpackAlpha(image[index + 1]) == 0)
|| (index >= width && ColorARGB.unpackAlpha(image[index - width]) == 0)
|| (index + width < size && ColorARGB.unpackAlpha(image[index + width]) == 0);
}
private static void fill(int neighbor, int source, int[] color, IntArrayFIFOQueue queue) {
if (color[neighbor] == 0) {
color[neighbor] = source;
queue.enqueue(neighbor);
}
}
private static float alphaTestCoverage(int[] image, int width, float alphaRef, float alphaScale) {
final int height = image.length / width;
final float alphaFactor = alphaScale / 255.0f;
float total = 0.0f;
int quads = 0;
for (int y = 0; y < height - 1; y++) {
for (int x = 0; x < width - 1; x++) {
final int i = x + y * width;
final float a00 = scaledAlpha(image[i], alphaFactor);
final float a10 = scaledAlpha(image[i + 1], alphaFactor);
final float a01 = scaledAlpha(image[i + width], alphaFactor);
final float a11 = scaledAlpha(image[i + width + 1], alphaFactor);
final float lo = Math.min(Math.min(a00, a10), Math.min(a01, a11));
if (lo > alphaRef) {
total += 1.0f;
quads++;
continue;
}
final float hi = Math.max(Math.max(a00, a10), Math.max(a01, a11));
if (hi <= alphaRef) {
quads++;
continue;
}
int hits = 0;
for (int sy = 0; sy < 4; sy++) {
final float fy = (sy + 0.5f) / 4.0f;
for (int sx = 0; sx < 4; sx++) {
final float fx = (sx + 0.5f) / 4.0f;
final float top = a00 + (a10 - a00) * fx;
final float bottom = a01 + (a11 - a01) * fx;
if (top + (bottom - top) * fy > alphaRef) {
hits++;
}
}
}
total += hits / 16.0f;
quads++;
}
}
if (quads == 0) {
return scaledAlpha(image[0], alphaFactor) > alphaRef ? 1.0f : 0.0f;
}
return total / quads;
}
private static float scaledAlpha(int color, float alphaFactor) {
return clamp(0.0f, 1.0f, ColorARGB.unpackAlpha(color) * alphaFactor);
}
private static void scaleAlphaToCoverage(int[] image, int width, float desiredCoverage, float alphaRef) {
float min = 0.0f;
float max = 4.0f;
float scale = 1.0f;
float bestScale = 1.0f;
float bestError = Float.POSITIVE_INFINITY;
for (int i = 0; i < 5; i++) {
final float coverage = alphaTestCoverage(image, width, alphaRef, scale);
final float error = Math.abs(coverage - desiredCoverage);
if (error < bestError) {
bestError = error;
bestScale = scale;
}
if (coverage < desiredCoverage) {
min = scale;
} else if (!(coverage > desiredCoverage)) {
break;
} else {
max = scale;
}
scale = (min + max) / 2.0f;
}
for (int i = 0; i < image.length; i++) {
final int color = image[i];
final int rawAlpha = ColorARGB.unpackAlpha(color);
final float bias = rawAlpha > 0 ? ALPHA_BIAS : 0.0f;
final int alpha = (int) Math.floor(clamp(0.0f, 1.0f, rawAlpha / 255.0f * bestScale + bias) * 255.0f);
image[i] = ColorARGB.withAlpha(color, alpha);
}
}
}
@@ -1,19 +1,16 @@
package com.gtnewhorizons.angelica.utils;
import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue;
import me.jellysquid.mods.sodium.client.gui.options.named.MipmapGeneration;
import org.embeddedt.embeddium.api.util.ColorARGB;
import org.embeddedt.embeddium.impl.texture.MipmapHelper;
import static org.joml.Math.clamp;
/**
* Mipmap downsampling for atlas sprites, replacing vanilla's {@code TextureUtil.generateMipmapData}.
*/
public final class MipmapGenerator {
static final float ALPHA_BIAS = 0.025f;
private static final float CUTOUT_ALPHA_REF = 0.5f;
private static final float STRICT_CUTOUT_ALPHA_REF = 0.3f;
private static final float ALPHA_BIAS = 0.025f;
private MipmapGenerator() {
}
@@ -25,101 +22,29 @@ public final class MipmapGenerator {
return strategy;
}
static boolean isCutoutStrategy(MipmapStrategy strategy, boolean hasTransparentPixel) {
final MipmapStrategy resolved = resolve(strategy, hasTransparentPixel);
private static boolean isCutoutStrategy(MipmapStrategy resolved) {
return resolved == MipmapStrategy.CUTOUT
|| resolved == MipmapStrategy.STRICT_CUTOUT
|| resolved == MipmapStrategy.DARK_CUTOUT;
}
static void solidify(int[] image, int width, int height) {
final int size = Math.min(width * height, image.length);
if (size <= 0) {
return;
}
boolean hasTransparent = false;
for (int i = 0; i < size; i++) {
if (ColorARGB.unpackAlpha(image[i]) == 0) {
hasTransparent = true;
break;
}
}
if (!hasTransparent) {
return;
}
final int[] color = new int[size];
final IntArrayFIFOQueue queue = new IntArrayFIFOQueue(64);
for (int i = 0; i < size; i++) {
final int pixel = image[i];
if (ColorARGB.unpackAlpha(pixel) == 0) {
continue;
}
color[i] = pixel;
if (hasTransparentNeighbour(image, i, width, size)) {
queue.enqueue(i);
}
}
if (queue.isEmpty()) {
return;
}
while (!queue.isEmpty()) {
final int index = queue.dequeueInt();
final int x = index % width;
final int source = color[index];
if (x > 0) {
fill(index - 1, source, color, queue);
}
if (x < width - 1) {
fill(index + 1, source, color, queue);
}
if (index >= width) {
fill(index - width, source, color, queue);
}
if (index + width < size) {
fill(index + width, source, color, queue);
}
}
for (int i = 0; i < size; i++) {
if (ColorARGB.unpackAlpha(image[i]) == 0) {
image[i] = color[i] & 0x00FFFFFF;
}
}
}
private static boolean hasTransparentNeighbour(int[] image, int index, int width, int size) {
final int x = index % width;
return (x > 0 && ColorARGB.unpackAlpha(image[index - 1]) == 0)
|| (x < width - 1 && ColorARGB.unpackAlpha(image[index + 1]) == 0)
|| (index >= width && ColorARGB.unpackAlpha(image[index - width]) == 0)
|| (index + width < size && ColorARGB.unpackAlpha(image[index + width]) == 0);
}
private static void fill(int neighbour, int source, int[] color, IntArrayFIFOQueue queue) {
if (color[neighbour] == 0) {
color[neighbour] = source;
queue.enqueue(neighbour);
}
}
static void fillEmptyAreasWithDarkColor(int[] image) {
// Scan order controls which equally dark color wins.
static void fillEmptyAreasWithDarkColor(int[] image, int columns) {
final int rows = image.length / columns;
int darkest = ColorARGB.pack(255, 255, 255, 255);
int darkestSum = 255 * 3;
int darkestSum = Integer.MAX_VALUE;
for (final int pixel : image) {
if (ColorARGB.unpackAlpha(pixel) == 0) {
continue;
}
final int sum = ColorARGB.unpackRed(pixel) + ColorARGB.unpackGreen(pixel) + ColorARGB.unpackBlue(pixel);
if (sum < darkestSum) {
darkestSum = sum;
darkest = pixel;
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
final int pixel = image[x + y * columns];
if (ColorARGB.unpackAlpha(pixel) == 0) {
continue;
}
final int sum = ColorARGB.unpackRed(pixel) + ColorARGB.unpackGreen(pixel) + ColorARGB.unpackBlue(pixel);
if (sum < darkestSum) {
darkestSum = sum;
darkest = pixel;
}
}
}
@@ -133,152 +58,22 @@ public final class MipmapGenerator {
}
}
/**
* Estimates the fraction of the image that survives, with bilinear filtering modeled by
* supersampling each texel quad on a 4x4 interior grid.
*/
static float alphaTestCoverage(int[] image, int width, float alphaRef, float alphaScale) {
final int height = image.length / width;
final float alphaFactor = alphaScale / 255.0f;
float total = 0.0f;
int quads = 0;
for (int y = 0; y < height - 1; y++) {
for (int x = 0; x < width - 1; x++) {
final int i = x + y * width;
final float a00 = scaledAlpha(image[i], alphaFactor);
final float a10 = scaledAlpha(image[i + 1], alphaFactor);
final float a01 = scaledAlpha(image[i + width], alphaFactor);
final float a11 = scaledAlpha(image[i + width + 1], alphaFactor);
final float lo = Math.min(Math.min(a00, a10), Math.min(a01, a11));
if (lo > alphaRef) {
total += 1.0f;
quads++;
continue;
}
final float hi = Math.max(Math.max(a00, a10), Math.max(a01, a11));
if (hi <= alphaRef) {
quads++;
continue;
}
int hits = 0;
for (int sy = 0; sy < 4; sy++) {
final float fy = (sy + 0.5f) / 4.0f;
for (int sx = 0; sx < 4; sx++) {
final float fx = (sx + 0.5f) / 4.0f;
final float top = a00 + (a10 - a00) * fx;
final float bottom = a01 + (a11 - a01) * fx;
if (top + (bottom - top) * fy > alphaRef) {
hits++;
}
}
}
total += hits / 16.0f;
quads++;
}
}
if (quads == 0) {
return scaledAlpha(image[0], alphaFactor) > alphaRef ? 1.0f : 0.0f;
}
return total / quads;
}
private static float scaledAlpha(int color, float alphaFactor) {
return clamp(0.0f, 1.0f, ColorARGB.unpackAlpha(color) * alphaFactor);
}
static void scaleAlphaToCoverage(int[] image, int width, float desiredCoverage, float alphaRef) {
float min = 0.0f;
float max = 4.0f;
float scale = 1.0f;
float bestScale = 1.0f;
float bestError = Float.POSITIVE_INFINITY;
for (int i = 0; i < 5; i++) {
final float coverage = alphaTestCoverage(image, width, alphaRef, scale);
final float error = Math.abs(coverage - desiredCoverage);
if (error < bestError) {
bestError = error;
bestScale = scale;
}
if (coverage < desiredCoverage) {
min = scale;
} else if (!(coverage > desiredCoverage)) {
break;
} else {
max = scale;
}
scale = (min + max) / 2.0f;
}
for (int i = 0; i < image.length; i++) {
final int color = image[i];
final int rawAlpha = ColorARGB.unpackAlpha(color);
final float bias = rawAlpha > 0 ? ALPHA_BIAS : 0.0f;
final int alpha = (int) Math.floor(clamp(0.0f, 1.0f, rawAlpha / 255.0f * bestScale + bias) * 255.0f);
image[i] = ColorARGB.withAlpha(color, alpha);
}
}
public static int[][] generateMipLevels(int mipLevel, int width, int[][] currentMips,
MipmapStrategy strategy, boolean hasTransparentPixel) {
MipmapStrategy strategy, boolean hasTransparentPixel, MipmapGeneration generation,
float alphaCutoffBias, boolean isItem) {
if (generation == MipmapGeneration.VANILLA_1_7_10) {
return VanillaMipmapGenerator.generateMipLevels(mipLevel, width, currentMips);
}
final MipmapStrategy resolved = resolve(strategy, hasTransparentPixel);
final boolean isCutout = isCutoutStrategy(strategy, hasTransparentPixel);
final boolean isCutout = isCutoutStrategy(resolved);
final boolean darkCutout = resolved == MipmapStrategy.DARK_CUTOUT;
final int[][] result = new int[mipLevel + 1][];
final int[] base = currentMips[0];
if (mipLevel > 0 && (currentMips.length == 1 || currentMips[1] == null)) {
if (darkCutout) {
fillEmptyAreasWithDarkColor(base);
} else {
solidify(base, width, base.length / width);
}
}
result[0] = base;
if (mipLevel <= 0) {
return result;
}
final float cutoutRef = resolved == MipmapStrategy.STRICT_CUTOUT ? STRICT_CUTOUT_ALPHA_REF : CUTOUT_ALPHA_REF;
final float originalCoverage = isCutout ? alphaTestCoverage(base, width, cutoutRef, 1.0f) : 0.0f;
for (int level = 1; level <= mipLevel; level++) {
final int levelWidth = width >> level;
final int[] provided = level < currentMips.length ? currentMips[level] : null;
if (provided != null) {
result[level] = provided;
} else {
final int[] input = result[level - 1];
final int prevWidth = width >> (level - 1);
final int prevHeight = input.length / prevWidth;
final int levelHeight = prevHeight >> 1;
final int[] output = new int[levelWidth * levelHeight];
for (int y = 0; y < levelHeight; y++) {
for (int x = 0; x < levelWidth; x++) {
final int i = x * 2 + y * 2 * prevWidth;
output[x + y * levelWidth] = MipmapHelper.weightedAverageColor(
MipmapHelper.weightedAverageColor(input[i], input[i + 1]),
MipmapHelper.weightedAverageColor(input[i + prevWidth], input[i + prevWidth + 1]));
}
}
result[level] = output;
}
if (isCutout) {
scaleAlphaToCoverage(result[level], levelWidth, originalCoverage, cutoutRef);
}
if (generation == MipmapGeneration.MODERN_VANILLA) {
return ModernMipmapGenerator.generateMipLevels(mipLevel, width, currentMips,
isCutout, darkCutout, cutoutRef, alphaCutoffBias, isItem);
}
return result;
return CeleritasMipmapGenerator.generateMipLevels(mipLevel, width, currentMips, isCutout, darkCutout, cutoutRef);
}
}
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.utils;
import com.gtnewhorizons.angelica.rendering.TextureAtlasType;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFlower;
@@ -55,7 +56,7 @@ public final class MipmapStrategies {
}
MipmapStrategy strategy = STRATEGY_STACK.get().peek();
if (strategy == null && textureType == 0 && iconName.contains("leaves")) {
if (strategy == null && textureType == TextureAtlasType.BLOCK && iconName.contains("leaves")) {
strategy = MipmapStrategy.DARK_CUTOUT;
}
if (strategy == null) {
@@ -67,7 +68,7 @@ public final class MipmapStrategies {
}
public static MipmapStrategy inheritedFor(int textureType, String iconName) {
if (iconName == null || textureType != 0) {
if (iconName == null || textureType != TextureAtlasType.BLOCK) {
return null;
}
return SPRITE_RULES.get(iconName);
@@ -0,0 +1,77 @@
package com.gtnewhorizons.angelica.utils;
import org.embeddedt.embeddium.api.util.ColorARGB;
/**
* Minecraft 26.2's ARGB.meanLinear and MipmapGenerator.darkenedAlphaBlend, using its 10-bit linear color tables.
*/
final class ModernMipmapBlender {
private static final int[] SRGB_TO_LINEAR = new int[256];
private static final float[] SRGB_TO_LINEAR_FLOAT = new float[256];
private static final int[] LINEAR_TO_SRGB = new int[1024];
static {
for (int i = 0; i < SRGB_TO_LINEAR.length; i++) {
final float channel = i / 255.0f;
final float linear = channel >= 0.04045f ? (float) Math.pow((channel + 0.055) / 1.055, 2.4) : channel / 12.92f;
SRGB_TO_LINEAR[i] = Math.round(linear * 1023.0f);
SRGB_TO_LINEAR_FLOAT[i] = SRGB_TO_LINEAR[i] / 1023.0f;
}
for (int i = 0; i < LINEAR_TO_SRGB.length; i++) {
final float channel = i / 1023.0f;
final float srgb = channel >= 0.0031308f ? (float) (1.055 * Math.pow(channel, 1.0 / 2.4) - 0.055) : 12.92f * channel;
LINEAR_TO_SRGB[i] = Math.round(srgb * 255.0f);
}
}
private ModernMipmapBlender() {
}
static int blend(int a, int b, int c, int d, boolean darkCutout) {
if (darkCutout) {
return darkenedAlphaBlend(a, b, c, d);
}
return ColorARGB.pack(meanChannel(a, b, c, d, 16), meanChannel(a, b, c, d, 8), meanChannel(a, b, c, d, 0), (ColorARGB.unpackAlpha(a) + ColorARGB.unpackAlpha(b) + ColorARGB.unpackAlpha(c) + ColorARGB.unpackAlpha(d)) / 4);
}
private static int meanChannel(int a, int b, int c, int d, int shift) {
final int linear = (SRGB_TO_LINEAR[(a >>> shift) & 255] + SRGB_TO_LINEAR[(b >>> shift) & 255] + SRGB_TO_LINEAR[(c >>> shift) & 255] + SRGB_TO_LINEAR[(d >>> shift) & 255]) / 4;
return LINEAR_TO_SRGB[linear];
}
private static int darkenedAlphaBlend(int a, int b, int c, int d) {
float alpha = 0.0f;
float red = 0.0f;
float green = 0.0f;
float blue = 0.0f;
if (ColorARGB.unpackAlpha(a) != 0) {
alpha += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackAlpha(a)];
red += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackRed(a)];
green += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackGreen(a)];
blue += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackBlue(a)];
}
if (ColorARGB.unpackAlpha(b) != 0) {
alpha += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackAlpha(b)];
red += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackRed(b)];
green += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackGreen(b)];
blue += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackBlue(b)];
}
if (ColorARGB.unpackAlpha(c) != 0) {
alpha += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackAlpha(c)];
red += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackRed(c)];
green += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackGreen(c)];
blue += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackBlue(c)];
}
if (ColorARGB.unpackAlpha(d) != 0) {
alpha += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackAlpha(d)];
red += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackRed(d)];
green += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackGreen(d)];
blue += SRGB_TO_LINEAR_FLOAT[ColorARGB.unpackBlue(d)];
}
return ColorARGB.pack(toSrgb(red), toSrgb(green), toSrgb(blue), toSrgb(alpha));
}
private static int toSrgb(float sum) {
return LINEAR_TO_SRGB[(int) (sum * 0.25f * 1023.0f)];
}
}
@@ -0,0 +1,238 @@
package com.gtnewhorizons.angelica.utils;
import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue;
import it.unimi.dsi.fastutil.ints.IntArrays;
import org.embeddedt.embeddium.api.util.ColorARGB;
import java.util.Arrays;
import static com.gtnewhorizons.angelica.utils.MipmapGenerator.ALPHA_BIAS;
import static org.joml.Math.clamp;
/**
* Minecraft 26.2's mipmap generation and texture preparation.
*/
final class ModernMipmapGenerator {
private static final float[] NORMALIZED_ALPHA = new float[256];
static {
for (int i = 0; i < NORMALIZED_ALPHA.length; i++) {
NORMALIZED_ALPHA[i] = i / 255.0f;
}
}
private ModernMipmapGenerator() {
}
static int[][] generateMipLevels(int mipLevel, int width, int[][] currentMips, boolean isCutout, boolean darkCutout, float cutoutRef, float alphaCutoffBias, boolean isItem) {
final int[] base = currentMips[0];
// Unlike modern NativeImage arrays, 1.7.10 preallocates null slots for missing mip levels.
boolean hasProvidedMips = false;
boolean complete = mipLevel < currentMips.length;
int maxPixels = base.length;
for (int level = 1; level < currentMips.length; level++) {
if (currentMips[level] != null) {
hasProvidedMips = true;
if (level <= mipLevel) {
maxPixels = Math.max(maxPixels, currentMips[level].length);
}
} else if (level <= mipLevel) {
complete = false;
}
}
if (!hasProvidedMips && !isItem && isCutout) {
if (darkCutout) {
MipmapGenerator.fillEmptyAreasWithDarkColor(base, width);
} else {
solidify(base, width);
}
}
if (complete) {
return currentMips.length == mipLevel + 1 ? currentMips : Arrays.copyOf(currentMips, mipLevel + 1);
}
final int[][] result = Arrays.copyOf(currentMips, mipLevel + 1);
final float[] alphaScratch = isCutout ? new float[maxPixels] : null;
final float originalCoverage = isCutout ? alphaTestCoverage(base, width, cutoutRef, 1.0f, alphaScratch) : 0.0f;
for (int level = 1; level <= mipLevel; level++) {
final int levelWidth = width >> level;
if (levelWidth == 0) {
if (result[level] == null) {
result[level] = IntArrays.EMPTY_ARRAY;
}
continue;
}
if (result[level] == null) {
final int[] input = result[level - 1];
final int prevWidth = width >> (level - 1);
final int levelHeight = (input.length / prevWidth) >> 1;
if (levelHeight == 0) {
result[level] = IntArrays.EMPTY_ARRAY;
continue;
}
final int[] output = new int[levelWidth * levelHeight];
for (int y = 0; y < levelHeight; y++) {
for (int x = 0; x < levelWidth; x++) {
final int i = x * 2 + y * 2 * prevWidth;
output[x + y * levelWidth] = ModernMipmapBlender.blend(input[i], input[i + 1], input[i + prevWidth], input[i + prevWidth + 1], darkCutout);
}
}
result[level] = output;
}
if (isCutout && result[level].length > 0) {
scaleAlphaToCoverage(result[level], levelWidth, originalCoverage, cutoutRef, alphaCutoffBias, alphaScratch);
}
}
return result;
}
private static void solidify(int[] image, int width) {
boolean hasTransparentPixel = false;
boolean hasOpaquePixel = false;
for (int color : image) {
if (ColorARGB.unpackAlpha(color) == 0) {
hasTransparentPixel = true;
} else {
hasOpaquePixel = true;
}
if (hasTransparentPixel && hasOpaquePixel) {
break;
}
}
if (!hasTransparentPixel) {
return;
}
if (!hasOpaquePixel) {
Arrays.fill(image, 0);
return;
}
final int height = image.length / width;
final int[] nearestColor = new int[image.length];
final IntArrayFIFOQueue queue = new IntArrayFIFOQueue(64);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
final int i = x + y * width;
if (ColorARGB.unpackAlpha(image[i]) != 0) {
nearestColor[i] = image[i];
if (hasTransparentNeighbor(image, width, i, x)) {
queue.enqueue(i);
}
}
}
}
while (!queue.isEmpty()) {
final int i = queue.dequeueInt();
final int x = i % width;
final int color = nearestColor[i];
if (x < width - 1) {
fill(i + 1, color, nearestColor, queue);
}
if (x > 0) {
fill(i - 1, color, nearestColor, queue);
}
if (i + width < image.length) {
fill(i + width, color, nearestColor, queue);
}
if (i >= width) {
fill(i - width, color, nearestColor, queue);
}
}
for (int i = 0; i < image.length; i++) {
if (ColorARGB.unpackAlpha(image[i]) == 0) {
image[i] = nearestColor[i] & 0x00FFFFFF;
}
}
}
private static boolean hasTransparentNeighbor(int[] image, int width, int i, int x) {
return (x < width - 1 && ColorARGB.unpackAlpha(image[i + 1]) == 0) || (x > 0 && ColorARGB.unpackAlpha(image[i - 1]) == 0) || (i + width < image.length && ColorARGB.unpackAlpha(image[i + width]) == 0)
|| (i >= width && ColorARGB.unpackAlpha(image[i - width]) == 0);
}
private static void fill(int i, int color, int[] nearestColor, IntArrayFIFOQueue queue) {
if (nearestColor[i] == 0) {
nearestColor[i] = color;
queue.enqueue(i);
}
}
private static float alphaTestCoverage(int[] image, int width, float alphaRef, float alphaScale, float[] alphaScratch) {
final int height = image.length / width;
for (int i = 0; i < image.length; i++) {
alphaScratch[i] = clamp(0.0f, 1.0f, NORMALIZED_ALPHA[ColorARGB.unpackAlpha(image[i])] * alphaScale);
}
final float margin = 8.0f * Math.ulp(alphaRef);
final float safelyAbove = alphaRef + margin;
final float safelyBelow = alphaRef - margin;
float coverage = 0.0f;
for (int y = 0; y < height - 1; y++) {
for (int x = 0; x < width - 1; x++) {
final int i = x + y * width;
final float a00 = alphaScratch[i];
final float a10 = alphaScratch[i + 1];
final float a01 = alphaScratch[i + width];
final float a11 = alphaScratch[i + width + 1];
if (a00 > safelyAbove && a10 > safelyAbove && a01 > safelyAbove && a11 > safelyAbove) {
coverage += 1.0f;
continue;
}
if (a00 < safelyBelow && a10 < safelyBelow && a01 < safelyBelow && a11 < safelyBelow) {
continue;
}
float texelCoverage = 0.0f;
for (int sy = 0; sy < 4; sy++) {
final float fy = (sy + 0.5f) / 4.0f;
for (int sx = 0; sx < 4; sx++) {
final float fx = (sx + 0.5f) / 4.0f;
final float alpha = a00 * (1.0f - fx) * (1.0f - fy) + a10 * fx * (1.0f - fy) + a01 * (1.0f - fx) * fy + a11 * fx * fy;
if (alpha > alphaRef) {
texelCoverage++;
}
}
}
coverage += texelCoverage / 16.0f;
}
}
return coverage / ((width - 1) * (height - 1));
}
private static void scaleAlphaToCoverage(int[] image, int width, float desiredCoverage, float alphaRef, float alphaCutoffBias, float[] alphaScratch) {
float min = 0.0f;
float max = 4.0f;
float scale = 1.0f;
float bestScale = 1.0f;
float bestError = Float.MAX_VALUE;
if (width > 1 && image.length / width > 1) {
for (int i = 0; i < 5; i++) {
final float coverage = alphaTestCoverage(image, width, alphaRef, scale, alphaScratch);
final float error = Math.abs(coverage - desiredCoverage);
if (error < bestError) {
bestError = error;
bestScale = scale;
}
if (coverage < desiredCoverage) {
min = scale;
} else if (coverage > desiredCoverage) {
max = scale;
} else {
break;
}
scale = (min + max) * 0.5f;
}
}
for (int i = 0; i < image.length; i++) {
final int color = image[i];
final float alpha = NORMALIZED_ALPHA[ColorARGB.unpackAlpha(color)] * bestScale + alphaCutoffBias + ALPHA_BIAS;
image[i] = ColorARGB.withAlpha(color, (int) (clamp(0.0f, 1.0f, alpha) * 255.0f));
}
}
}
@@ -0,0 +1,97 @@
package com.gtnewhorizons.angelica.utils;
import it.unimi.dsi.fastutil.ints.IntArrays;
import org.embeddedt.embeddium.api.util.ColorARGB;
/**
* Minecraft 1.7.10's TextureUtil mipmap generator without its shared mutable color buffer.
*/
final class VanillaMipmapGenerator {
private static final float[] TO_LINEAR = new float[256];
static {
for (int i = 0; i < TO_LINEAR.length; i++) {
TO_LINEAR[i] = (float) Math.pow(i / 255.0f, 2.2);
}
}
private VanillaMipmapGenerator() {
}
static int[][] generateMipLevels(int mipLevel, int width, int[][] currentMips) {
final int[][] result = new int[mipLevel + 1][];
result[0] = currentMips[0];
if (mipLevel <= 0) {
return result;
}
boolean hasTransparentPixel = false;
for (int i = 0; i < Math.min(currentMips.length, result[0].length); i++) {
if (ColorARGB.unpackAlpha(result[0][i]) == 0) {
hasTransparentPixel = true;
break;
}
}
for (int level = 1; level <= mipLevel; level++) {
final int[] provided = level < currentMips.length ? currentMips[level] : null;
if (provided != null) {
result[level] = provided;
continue;
}
final int levelWidth = width >> level;
if (levelWidth == 0) {
result[level] = IntArrays.EMPTY_ARRAY;
continue;
}
final int[] input = result[level - 1];
final int[] output = new int[input.length >> 2];
final int levelHeight = output.length / levelWidth;
final int stride = levelWidth << 1;
for (int y = 0; y < levelHeight; y++) {
for (int x = 0; x < levelWidth; x++) {
final int i = 2 * (x + y * stride);
output[x + y * levelWidth] = blend(input[i], input[i + 1], input[i + stride], input[i + stride + 1], hasTransparentPixel);
}
}
result[level] = output;
}
return result;
}
private static int blend(int a, int b, int c, int d, boolean hasTransparentPixel) {
if (hasTransparentPixel) {
int alpha = transparentChannel(a, b, c, d, 24);
if (alpha < 96) {
alpha = 0;
}
return ColorARGB.pack(transparentChannel(a, b, c, d, 16), transparentChannel(a, b, c, d, 8), transparentChannel(a, b, c, d, 0), alpha);
}
return ColorARGB.pack(meanChannel(a, b, c, d, 16), meanChannel(a, b, c, d, 8), meanChannel(a, b, c, d, 0), meanChannel(a, b, c, d, 24));
}
private static int meanChannel(int a, int b, int c, int d, int shift) {
final float sum = TO_LINEAR[(a >>> shift) & 255] + TO_LINEAR[(b >>> shift) & 255] + TO_LINEAR[(c >>> shift) & 255] + TO_LINEAR[(d >>> shift) & 255];
final float value = (float) Math.pow(sum * 0.25, 1.0 / 2.2);
return (int) (value * 255.0);
}
private static int transparentChannel(int a, int b, int c, int d, int shift) {
float sum = 0.0f;
if (ColorARGB.unpackAlpha(a) != 0) {
sum += TO_LINEAR[(a >>> shift) & 255];
}
if (ColorARGB.unpackAlpha(b) != 0) {
sum += TO_LINEAR[(b >>> shift) & 255];
}
if (ColorARGB.unpackAlpha(c) != 0) {
sum += TO_LINEAR[(c >>> shift) & 255];
}
if (ColorARGB.unpackAlpha(d) != 0) {
sum += TO_LINEAR[(d >>> shift) & 255];
}
return (int) (Math.pow(sum / 4.0f, 1.0 / 2.2) * 255.0);
}
}
@@ -42,6 +42,7 @@ import me.jellysquid.mods.sodium.client.gui.options.named.BiomeBlendMode;
import me.jellysquid.mods.sodium.client.gui.options.named.GraphicsMode;
import me.jellysquid.mods.sodium.client.gui.options.named.GraphicsQuality;
import me.jellysquid.mods.sodium.client.gui.options.named.LightingQuality;
import me.jellysquid.mods.sodium.client.gui.options.named.MipmapGeneration;
import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode;
import me.jellysquid.mods.sodium.client.gui.options.named.ParticleMode;
import me.jellysquid.mods.sodium.client.gui.options.named.TexelSampling;
@@ -313,6 +314,14 @@ public class SodiumGameOptionPages {
groups.add(OptionGroup.createBuilder()
.add(mipmapLevels)
.add(OptionImpl.createBuilder(MipmapGeneration.class, sodiumOpts)
.setName(I18n.format("sodium.options.mipmap_generation.name"))
.setTooltip(I18n.format("sodium.options.mipmap_generation.tooltip"))
.setControl(option -> new CyclingControl<>(option, MipmapGeneration.class))
.setBinding((opts, value) -> opts.quality.mipmapGeneration = value, opts -> opts.quality.mipmapGeneration)
.setImpact(OptionImpact.LOW)
.setFlags(OptionFlag.REQUIRES_ASSET_RELOAD)
.build())
.build());
groups.add(OptionGroup.createBuilder()
.add(Settings.MODE_GLINT_INV.option)
@@ -765,7 +774,6 @@ public class SodiumGameOptionPages {
(opts, value) -> opts.anisotropicFiltering = 1 << MathHelper.clamp_int(value, min, max),
opts -> MathHelper.clamp_int(Integer.numberOfTrailingZeros(Math.max(opts.anisotropicFiltering, 1)), min, max))
.setImpact(OptionImpact.MEDIUM)
.setFlags(OptionFlag.REQUIRES_ASSET_RELOAD)
.build();
option.iris$dynamicallyEnable(() -> mode.get().usesAnisotropy() && SodiumGameOptions.hasAnisotropyRange());
@@ -11,6 +11,7 @@ import com.gtnewhorizons.angelica.glsm.streaming.StreamingUploader;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import me.jellysquid.mods.sodium.client.gui.options.named.BiomeBlendMode;
import me.jellysquid.mods.sodium.client.gui.options.named.GraphicsQuality;
import me.jellysquid.mods.sodium.client.gui.options.named.MipmapGeneration;
import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode;
import me.jellysquid.mods.sodium.client.gui.options.named.TexelSampling;
import me.jellysquid.mods.sodium.client.gui.options.named.TextureFilterMode;
@@ -61,7 +62,8 @@ public class SodiumGameOptions {
final TextureMap atlas = mc.getTextureMapBlocks();
atlas.setMipmapLevels(mc.gameSettings.mipmapLevels);
atlas.setAnisotropicFiltering(resolvedAnisotropicFiltering());
// Drivers may ignore NEAREST when anisotropy is enabled
atlas.setAnisotropicFiltering(1);
}
public static int resolvedAnisotropicFiltering() {
@@ -153,6 +155,10 @@ public class SodiumGameOptions {
}
config.quality.guiBlockSupersampling = Integer.highestOneBit(MathHelper.clamp_int(config.quality.guiBlockSupersampling, 1, 16));
if (config.quality.mipmapGeneration == null) {
config.quality.mipmapGeneration = MipmapGeneration.MODERN_VANILLA;
}
if (GLStateManager.capabilities != null) {
if (!GLStateManager.capabilities.OpenGL32) {
config.performance.cpuRenderAheadLimit = 0;
@@ -251,6 +257,7 @@ public class SodiumGameOptions {
public boolean useCeleritasSmoothLighting = true;
public TextureFilterMode textureFilterMode = TextureFilterMode.RGSS_ANISOTROPIC;
public TexelSampling texelSampling = TexelSampling.LINEAR;
public MipmapGeneration mipmapGeneration = MipmapGeneration.MODERN_VANILLA;
public int guiBlockSupersampling = 1;
}
@@ -0,0 +1,33 @@
package me.jellysquid.mods.sodium.client.gui.options.named;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.parameters.AlphaCutoffParameter;
public enum MipmapGeneration implements NamedState {
VANILLA_1_7_10("sodium.options.mipmap_generation.vanilla_1_7_10"),
CELERITAS("sodium.options.mipmap_generation.celeritas"),
MODERN_VANILLA("sodium.options.mipmap_generation.modern_vanilla");
private final String name;
MipmapGeneration(String name) {
this.name = name;
}
public static MipmapGeneration current() {
return ClientProxy.options().quality.mipmapGeneration;
}
public static boolean usesModernMipmaps() {
return current() == MODERN_VANILLA;
}
public static AlphaCutoffParameter alphaFloorCutoff() {
return usesModernMipmaps() ? AlphaCutoffParameter.ONE_TENTH : AlphaCutoffParameter.ZERO;
}
@Override
public String getKey() {
return this.name;
}
}
@@ -93,6 +93,7 @@ public class BlockRenderingSettings {
private float ambientOcclusionLevel;
private boolean disableDirectionalShading;
private boolean useSeparateAo;
@Setter private boolean breaksAnisotropy;
private boolean useExtendedVertexFormat;
@Setter
private boolean hasSnowyEntries;
@@ -213,6 +214,10 @@ public class BlockRenderingSettings {
return useSeparateAo;
}
public boolean breaksAnisotropy() {
return breaksAnisotropy;
}
public void setUseSeparateAo(boolean useSeparateAo) {
if (useSeparateAo == this.useSeparateAo) {
return;
@@ -27,7 +27,7 @@ import java.util.Optional;
import java.util.function.Function;
public class IrisCeleritasChunkProgramOverrides {
private final EnumMap<IrisTerrainPass, GlProgram<IrisCeleritasChunkShaderInterface>> programs = new EnumMap<>(IrisTerrainPass.class);
private final EnumMap<IrisTerrainPass, GlProgram<ChunkShaderInterface>> programs = new EnumMap<>(IrisTerrainPass.class);
private boolean shadersCreated = false;
private int versionCounterForShaderReload = -1;
@@ -80,19 +80,19 @@ public class IrisCeleritasChunkProgramOverrides {
return key;
}
private static final class SavedProgram extends GlProgram<IrisCeleritasChunkShaderInterface> {
SavedProgram(int program, Function<ShaderBindingContext, IrisCeleritasChunkShaderInterface> factory) {
private static final class SavedProgram extends GlProgram<ChunkShaderInterface> {
SavedProgram(int program, Function<ShaderBindingContext, ChunkShaderInterface> factory) {
super(program, factory);
}
}
@Nullable
private GlProgram<IrisCeleritasChunkShaderInterface> createShader(IrisTerrainPass pass, CeleritasTerrainPipeline pipeline, ChunkVertexType vertexType) {
private GlProgram<ChunkShaderInterface> createShader(IrisTerrainPass pass, CeleritasTerrainPipeline pipeline, ChunkVertexType vertexType) {
final CeleritasTerrainPipeline.PassInfo passInfo = pipeline.getPassInfo(pass);
final String name = "iris:celeritas-chunk-" + pass.getName();
final BlendModeOverride blendOverride = passInfo.blendModeOverride();
final List<BufferBlendOverride> bufferOverrides = passInfo.bufferBlendOverrides();
final Function<ShaderBindingContext, IrisCeleritasChunkShaderInterface> factory = context -> new IrisCeleritasChunkShaderInterface(
final Function<ShaderBindingContext, ChunkShaderInterface> factory = context -> new IrisCeleritasChunkShaderInterface(
((GlObject) context).handle(), context, pipeline, pass.isShadow(), blendOverride, bufferOverrides, pipeline.getCustomUniforms());
final ProgramBinaryCache.Key cacheKey = cacheKey(passInfo, vertexType);
@@ -130,7 +130,7 @@ public class IrisCeleritasChunkProgramOverrides {
builder.bindAttribute(attr.getName(), attrIndex++);
}
final GlProgram<IrisCeleritasChunkShaderInterface> program = builder.link(factory);
final GlProgram<ChunkShaderInterface> program = builder.link(factory);
if (cacheKey != null) {
ProgramBinaryCache.save(cacheKey, program.handle());
}
@@ -169,7 +169,7 @@ public class IrisCeleritasChunkProgramOverrides {
}
@Nullable
public GlProgram<? extends ChunkShaderInterface> getProgramOverride(TerrainRenderPass pass, RenderPassConfiguration<?> configuration) {
public GlProgram<ChunkShaderInterface> getProgramOverride(TerrainRenderPass pass, RenderPassConfiguration<?> configuration) {
// Check for shader pack reload
if (versionCounterForShaderReload != Iris.getPipelineManager().getVersionCounterForSodiumShaderReload()) {
versionCounterForShaderReload = Iris.getPipelineManager().getVersionCounterForSodiumShaderReload();
@@ -186,23 +186,13 @@ public class IrisCeleritasChunkProgramOverrides {
createShaders(celeritasPipeline, configuration);
}
if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) {
final boolean isShadow = ShadowRenderingState.areShadowsCurrentlyBeingRendered();
if (isShadow) {
if (celeritasPipeline != null && !celeritasPipeline.hasShadowPass()) {
throw new IllegalStateException("Shadow program requested, but shader pack has no shadow pass");
}
if (pass.isReverseOrder()) {
return programs.get(IrisTerrainPass.SHADOW_TRANSLUCENT);
}
return programs.get(pass.supportsFragmentDiscard() ? IrisTerrainPass.SHADOW_CUTOUT : IrisTerrainPass.SHADOW);
} else {
if (pass.supportsFragmentDiscard()) {
return programs.get(IrisTerrainPass.GBUFFER_CUTOUT);
} else if (pass.isReverseOrder()) {
return programs.get(IrisTerrainPass.GBUFFER_TRANSLUCENT);
} else {
return programs.get(IrisTerrainPass.GBUFFER_SOLID);
}
}
return programs.get(IrisTerrainPass.fromTerrainPass(pass, isShadow));
}
public void deleteShaders() {
@@ -241,20 +241,7 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface {
}
final boolean isShadow = ShadowRenderingState.areShadowsCurrentlyBeingRendered();
final IrisTerrainPass irisPass;
if (isShadow) {
if (pass.isReverseOrder()) {
irisPass = IrisTerrainPass.SHADOW_TRANSLUCENT;
} else {
irisPass = pass.supportsFragmentDiscard() ? IrisTerrainPass.SHADOW_CUTOUT : IrisTerrainPass.SHADOW;
}
} else if (pass.isReverseOrder()) {
irisPass = IrisTerrainPass.GBUFFER_TRANSLUCENT;
} else if (pass.supportsFragmentDiscard()) {
irisPass = IrisTerrainPass.GBUFFER_CUTOUT;
} else {
irisPass = IrisTerrainPass.GBUFFER_SOLID;
}
final IrisTerrainPass irisPass = IrisTerrainPass.fromTerrainPass(pass, isShadow);
final GlFramebuffer framebuffer = pipeline.getPassInfo(irisPass).framebuffer();
if (framebuffer != null) {
@@ -40,7 +40,7 @@ public class IrisCeleritasShaderProvider implements IrisShaderProvider {
@Override
@Nullable
public GlProgram<? extends ChunkShaderInterface> getShaderOverride(TerrainRenderPass pass) {
public GlProgram<ChunkShaderInterface> getShaderOverride(TerrainRenderPass pass) {
if (!isShadersEnabled() || renderPassConfiguration == null) {
return null;
}
@@ -41,10 +41,10 @@ public enum IrisTerrainPass {
return SHADOW_TRANSLUCENT;
}
return pass.supportsFragmentDiscard() ? SHADOW_CUTOUT : SHADOW;
} else if (pass.supportsFragmentDiscard()) {
return GBUFFER_CUTOUT;
} else if (pass.isReverseOrder()) {
return GBUFFER_TRANSLUCENT;
} else if (pass.supportsFragmentDiscard()) {
return GBUFFER_CUTOUT;
} else {
return GBUFFER_SOLID;
}
@@ -93,6 +93,7 @@ public final class ComputeProgram extends GlResource {
public static void unbind() {
ProgramUniforms.clearActiveUniforms();
ProgramSamplers.clearActiveSamplers();
GLStateManager.glUseProgram(0);
}
@@ -18,6 +18,7 @@ import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import org.jetbrains.annotations.Nullable;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
public class ProgramBuilder extends ProgramUniforms.Builder implements SamplerHolder, ImageHolder {
private final int program;
@@ -196,17 +197,17 @@ public class ProgramBuilder extends ProgramUniforms.Builder implements SamplerHo
}
@Override
public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) {
public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier<GlSampler> sampler, String... names) {
return samplers.addDefaultSampler(type, texture, notifier, sampler, names);
}
@Override
public boolean addDynamicSampler(TextureType type, IntSupplier texture, GlSampler sampler, String... names) {
public boolean addDynamicSampler(TextureType type, IntSupplier texture, Supplier<GlSampler> sampler, String... names) {
return samplers.addDynamicSampler(type, texture, sampler, names);
}
@Override
public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) {
public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier<GlSampler> sampler, String... names) {
return samplers.addDynamicSampler(type, texture, notifier, sampler, names);
}
@@ -19,6 +19,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
public class ProgramSamplers {
private static ProgramSamplers active;
@@ -39,23 +40,25 @@ public class ProgramSamplers {
active = this;
if (initializer != null) {
for (GlUniform1iCall call : initializer) {
RenderSystem.uniform1i(call.getLocation(), call.getValue());
int activeTexture = GLStateManager.getActiveTextureUnit();
try {
if (initializer != null) {
for (GlUniform1iCall call : initializer) {
RenderSystem.uniform1i(call.getLocation(), call.getValue());
}
initializer = null;
}
initializer = null;
for (int i = 0, n = samplerBindings.size(); i < n; i++) {
samplerBindings.get(i).update();
}
} catch (RuntimeException | Error e) {
clearActiveSamplers();
throw e;
} finally {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + activeTexture);
}
// We need to keep the active texture intact, since if we mess it up
// in the middle of RenderType setup, bad things will happen.
int activeTexture = GLStateManager.getActiveTextureUnit();
for (int i = 0, n = samplerBindings.size(); i < n; i++) {
samplerBindings.get(i).update();
}
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + activeTexture);
}
public void removeListeners() {
@@ -70,6 +73,7 @@ public class ProgramSamplers {
if (active != null) {
active.removeListeners();
}
RenderSystem.unbindAllSamplers();
}
public static Builder builder(int program, Set<Integer> reservedTextureUnits) {
@@ -148,31 +152,30 @@ public class ProgramSamplers {
}
@Override
public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) {
public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier<GlSampler> sampler, String... names) {
if (nextUnit != 0) {
// TODO: Relax this restriction!
throw new IllegalStateException("Texture unit 0 is already used.");
}
if (notifier != null) {
notifiersToReset.add(notifier);
}
return addDynamicSampler(type, texture, sampler, true, notifier, names);
}
@Override
public boolean addDynamicSampler(TextureType type, IntSupplier texture, GlSampler sampler, String... names) {
public boolean addDynamicSampler(TextureType type, IntSupplier texture, Supplier<GlSampler> sampler, String... names) {
return addDynamicSampler(type, texture, sampler, false, null, names);
}
@Override
public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) {
notifiersToReset.add(notifier);
public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier<GlSampler> sampler, String... names) {
return addDynamicSampler(type, texture, sampler, false, notifier, names);
}
private boolean addDynamicSampler(TextureType type, IntSupplier texture, GlSampler sampler, boolean used, ValueUpdateNotifier notifier, String... names) {
private boolean addDynamicSampler(TextureType type, IntSupplier texture, Supplier<GlSampler> sampler, boolean used, ValueUpdateNotifier notifier, String... names) {
if (notifier != null) {
notifiersToReset.add(notifier);
}
for (String name : names) {
int location = RenderSystem.getUniformLocation(program, name);
@@ -236,26 +239,22 @@ public class ProgramSamplers {
this.deactivatedOverrides = deactivatedOverrides.build();
}
private IntSupplier getOverride(IntSupplier existing, String... names) {
private TextureAccess getOverride(String... names) {
for (String name : names) {
if (customTextureIds.containsKey(name) && !deactivatedOverrides.contains(name)) {
return customTextureIds.get(name).getTextureId();
return customTextureIds.get(name);
}
}
return existing;
return null;
}
@Override
public void addExternalSampler(int textureUnit, String... names) {
IntSupplier override = getOverride(null, names);
TextureAccess override = getOverride(names);
if (override != null) {
if (textureUnit == 0) {
samplerHolder.addDefaultSampler(override, names);
} else {
samplerHolder.addDynamicSampler(override, names);
}
addOverride(override, textureUnit == 0, names);
} else {
samplerHolder.addExternalSampler(textureUnit, names);
}
@@ -267,21 +266,34 @@ public class ProgramSamplers {
}
@Override
public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) {
texture = getOverride(texture, names);
return samplerHolder.addDefaultSampler(type, texture, notifier, sampler, names);
public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier<GlSampler> sampler, String... names) {
return addSampler(type, texture, notifier, sampler, true, names);
}
@Override
public boolean addDynamicSampler(TextureType type, IntSupplier texture, GlSampler sampler, String... names) {
texture = getOverride(texture, names);
return samplerHolder.addDynamicSampler(type, texture, sampler, names);
public boolean addDynamicSampler(TextureType type, IntSupplier texture, Supplier<GlSampler> sampler, String... names) {
return addSampler(type, texture, null, sampler, false, names);
}
@Override
public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) {
texture = getOverride(texture, names);
return samplerHolder.addDynamicSampler(type, texture, notifier, sampler, names);
public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier<GlSampler> sampler, String... names) {
return addSampler(type, texture, notifier, sampler, false, names);
}
private boolean addSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier<GlSampler> sampler, boolean defaultSampler, String... names) {
final TextureAccess override = getOverride(names);
if (override != null) {
return addOverride(override, defaultSampler, names);
}
return defaultSampler
? samplerHolder.addDefaultSampler(type, texture, notifier, sampler, names)
: samplerHolder.addDynamicSampler(type, texture, notifier, sampler, names);
}
private boolean addOverride(TextureAccess override, boolean defaultSampler, String... names) {
return defaultSampler
? samplerHolder.addDefaultSampler(override.getType(), override.getTextureId(), null, null, names)
: samplerHolder.addDynamicSampler(override.getType(), override.getTextureId(), null, names);
}
}
}
@@ -7,8 +7,10 @@ import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL30;
import java.util.function.Supplier;
public class GlSampler extends GlObject {
public GlSampler(boolean linear, boolean mipmapped, boolean shadow, boolean hardwareShadow) {
public GlSampler(boolean linear, boolean linearMips, boolean mipmapped, boolean shadow, boolean hardwareShadow, boolean clamp) {
if (!RenderSystem.supportsSamplerObjects()) {
this.setHandle(0);
return;
@@ -16,13 +18,16 @@ public class GlSampler extends GlObject {
this.setHandle(RenderSystem.genSampler());
RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_MIN_FILTER, linear ? GL11.GL_LINEAR : GL11.GL_NEAREST);
RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_MAG_FILTER, linear ? GL11.GL_LINEAR : GL11.GL_NEAREST);
RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_WRAP_S, clamp ? GL12.GL_CLAMP_TO_EDGE : GL11.GL_REPEAT);
RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_WRAP_T, clamp ? GL12.GL_CLAMP_TO_EDGE : GL11.GL_REPEAT);
if (mipmapped) {
RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_MIN_FILTER, linear ? GL11.GL_LINEAR_MIPMAP_LINEAR : GL11.GL_NEAREST_MIPMAP_NEAREST);
RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_MIN_FILTER, linearMips
? (linear ? GL11.GL_LINEAR_MIPMAP_LINEAR : GL11.GL_NEAREST_MIPMAP_LINEAR)
: (linear ? GL11.GL_LINEAR_MIPMAP_NEAREST : GL11.GL_NEAREST_MIPMAP_NEAREST));
} else {
RenderSystem.samplerParameteri(getId(), GL11.GL_TEXTURE_MIN_FILTER, linear ? GL11.GL_LINEAR : GL11.GL_NEAREST);
}
if (hardwareShadow) {
@@ -38,4 +43,9 @@ public class GlSampler extends GlObject {
public int getId() {
return handle();
}
public static int idOf(Supplier<GlSampler> supplier) {
final GlSampler sampler = supplier == null ? null : supplier.get();
return sampler == null ? 0 : sampler.getId();
}
}
@@ -5,20 +5,21 @@ import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
public class SamplerBinding {
private final Runnable updateListener = this::updateSampler;
private final TextureType textureType;
private final int textureUnit;
private final IntSupplier texture;
private final int sampler;
private final Supplier<GlSampler> sampler;
private final ValueUpdateNotifier notifier;
public SamplerBinding(TextureType type, int textureUnit, IntSupplier texture, GlSampler sampler, ValueUpdateNotifier notifier) {
public SamplerBinding(TextureType type, int textureUnit, IntSupplier texture, Supplier<GlSampler> sampler, ValueUpdateNotifier notifier) {
this.textureType = type;
this.textureUnit = textureUnit;
this.texture = texture;
this.sampler = sampler == null ? 0 : sampler.getId();
this.sampler = sampler;
this.notifier = notifier;
}
@@ -31,7 +32,7 @@ public class SamplerBinding {
}
private void updateSampler() {
RenderSystem.bindSamplerToUnit(textureUnit, sampler);
RenderSystem.bindSamplerToUnit(textureUnit, GlSampler.idOf(sampler));
RenderSystem.bindTextureToUnit(textureType.getGlType(), textureUnit, texture.getAsInt());
}
}
@@ -4,6 +4,7 @@ import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
public interface SamplerHolder {
void addExternalSampler(int textureUnit, String... names);
@@ -20,7 +21,7 @@ public interface SamplerHolder {
return addDefaultSampler(TextureType.TEXTURE_2D, texture, null, null, names);
}
boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names);
boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier<GlSampler> sampler, String... names);
default boolean addDynamicSampler(IntSupplier texture, String... names) {
return addDynamicSampler(TextureType.TEXTURE_2D, texture, null, names);
@@ -30,11 +31,11 @@ public interface SamplerHolder {
return addDynamicSampler(type, texture, null, names);
}
boolean addDynamicSampler(TextureType type, IntSupplier texture, GlSampler sampler, String... names);
boolean addDynamicSampler(TextureType type, IntSupplier texture, Supplier<GlSampler> sampler, String... names);
default boolean addDynamicSampler(IntSupplier texture, ValueUpdateNotifier notifier, String... names) {
return addDynamicSampler(TextureType.TEXTURE_2D, texture, notifier, null, names);
}
boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names);
boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier<GlSampler> sampler, String... names);
}
@@ -9,6 +9,7 @@ import com.google.common.primitives.Ints;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import lombok.Getter;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix3f;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix4f;
import org.joml.Matrix3f;
@@ -25,6 +26,7 @@ import com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility;
import com.gtnewhorizons.angelica.rendering.tesr.TesrInstancingPipeline;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions;
import net.coderbot.iris.Iris;
import net.coderbot.iris.block_rendering.BlockMaterialMapping;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
@@ -52,6 +54,7 @@ import net.coderbot.iris.gl.program.Program;
import net.coderbot.iris.gl.program.ProgramBuilder;
import net.coderbot.iris.gl.program.ProgramImages;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.sampler.GlSampler;
import net.coderbot.iris.gl.sampler.SamplerHolder;
import net.coderbot.iris.gl.state.FogMode;
import com.gtnewhorizons.angelica.glsm.texture.DepthBufferFormat;
@@ -232,6 +235,13 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private boolean shouldBindPBR;
private int currentNormalTexture;
private int currentSpecularTexture;
@Getter
private GlSampler normalSampler;
@Getter
private GlSampler specularSampler;
private TextureFormat samplerFormat;
private int samplerAnisotropy = -1;
private boolean samplerBreaksAnisotropy;
private PackDirectives packDirectives;
private final Set<FeatureFlags> activeFeatures;
private final ProgramFallbackResolver resolver;
@@ -377,7 +387,9 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
BlockRenderingSettings.INSTANCE.setAmbientOcclusionLevel(programs.getPackDirectives().getAmbientOcclusionLevel());
BlockRenderingSettings.INSTANCE.setDisableDirectionalShading(shouldDisableDirectionalShading());
BlockRenderingSettings.INSTANCE.setUseSeparateAo(programs.getPackDirectives().shouldUseSeparateAo());
BlockRenderingSettings.INSTANCE.setBreaksAnisotropy(programs.getPackDirectives().breaksAnisotropy());
BlockRenderingSettings.INSTANCE.setUseExtendedVertexFormat(true);
updatePbrSamplers(TextureFormatLoader.getFormat(), SodiumGameOptions.resolvedAnisotropicFiltering());
// Don't clobber anything in texture unit 0. It probably won't cause issues, but we're just being cautious here.
GLStateManager.glActiveTexture(GL13.GL_TEXTURE2);
@@ -2293,6 +2305,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return;
}
updatePbrSamplers(TextureFormatLoader.getFormat(), SodiumGameOptions.resolvedAnisotropicFiltering());
isRenderingFullScreenPass = false;
isRenderingWorld = true;
isBeforeTranslucent = true;
@@ -2517,6 +2531,18 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return currentSpecularTexture;
}
void updatePbrSamplers(TextureFormat format, int anisotropy) {
final boolean breaksAnisotropy = BlockRenderingSettings.INSTANCE.breaksAnisotropy();
if (samplerFormat == format && samplerAnisotropy == anisotropy && samplerBreaksAnisotropy == breaksAnisotropy) {
return;
}
normalSampler = IrisSamplers.getPbrSampler(format, PBRType.NORMAL, anisotropy);
specularSampler = IrisSamplers.getPbrSampler(format, PBRType.SPECULAR, anisotropy);
samplerFormat = format;
samplerAnisotropy = anisotropy;
samplerBreaksAnisotropy = breaksAnisotropy;
}
@Override
public void onBindTexture(int id) {
if (shouldBindPBR && isRenderingWorld) {
@@ -2536,12 +2562,6 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
BatchStateGuard.suspend();
try {
final TextureFormat textureFormat = TextureFormatLoader.getFormat();
if (textureFormat != null) {
textureFormat.setupTextureParameters(PBRType.NORMAL, pbrHolder.getNormalTexture());
textureFormat.setupTextureParameters(PBRType.SPECULAR, pbrHolder.getSpecularTexture());
}
PBRTextureManager.notifyPBRTexturesChanged();
} finally {
BatchStateGuard.resume();
@@ -28,6 +28,7 @@ public class FixedFunctionWorldRenderingPipeline implements WorldRenderingPipeli
public FixedFunctionWorldRenderingPipeline() {
BlockRenderingSettings.INSTANCE.setDisableDirectionalShading(shouldDisableDirectionalShading());
BlockRenderingSettings.INSTANCE.setUseSeparateAo(false);
BlockRenderingSettings.INSTANCE.setBreaksAnisotropy(false);
BlockRenderingSettings.INSTANCE.setAmbientOcclusionLevel(1.0f);
BlockRenderingSettings.INSTANCE.setUseExtendedVertexFormat(false);
BlockRenderingSettings.INSTANCE.setBlockTypeIds(null);
@@ -27,6 +27,7 @@ import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
/**
* SDL-GPU only allows image writes from compute, so a gbuffers/shadow vertex shader that writes images gets a compute
@@ -105,7 +106,7 @@ final class VertexWriteReplays {
final List<String> samplerNames;
final int[] samplerUnits;
final IntSupplier[] samplerTextures;
final int[] samplerObjects;
final IntSupplier[] samplerObjects;
ResourceCollector(List<String> imageNames, List<String> samplerNames) {
this.imageNames = imageNames;
@@ -114,7 +115,7 @@ final class VertexWriteReplays {
this.samplerUnits = new int[samplerNames.size()];
Arrays.fill(samplerUnits, -1);
this.samplerTextures = new IntSupplier[samplerNames.size()];
this.samplerObjects = new int[samplerNames.size()];
this.samplerObjects = new IntSupplier[samplerNames.size()];
}
@Override
@@ -142,17 +143,17 @@ final class VertexWriteReplays {
}
@Override
public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) {
public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier<GlSampler> sampler, String... names) {
return addDynamicSampler(type, texture, notifier, sampler, names);
}
@Override
public boolean addDynamicSampler(TextureType type, IntSupplier texture, GlSampler sampler, String... names) {
public boolean addDynamicSampler(TextureType type, IntSupplier texture, Supplier<GlSampler> sampler, String... names) {
return addDynamicSampler(type, texture, null, sampler, names);
}
@Override
public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, GlSampler sampler, String... names) {
public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpdateNotifier notifier, Supplier<GlSampler> sampler, String... names) {
boolean used = false;
for (String name : names) {
final int index = samplerNames.indexOf(name);
@@ -160,7 +161,7 @@ final class VertexWriteReplays {
used = true;
if (unassigned(index)) {
samplerTextures[index] = texture;
samplerObjects[index] = sampler != null ? sampler.getId() : 0;
samplerObjects[index] = () -> GlSampler.idOf(sampler);
}
}
return used;
@@ -3,7 +3,9 @@ package net.coderbot.iris.samplers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.rendering.TextureSamplers;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.gl.image.GlImage;
import net.coderbot.iris.gl.sampler.GlSampler;
@@ -11,12 +13,15 @@ import net.coderbot.iris.gl.sampler.SamplerHolder;
import net.coderbot.iris.gl.state.StateUpdateNotifiers;
import net.coderbot.iris.gl.texture.TextureAccess;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.rendertarget.RenderTarget;
import net.coderbot.iris.rendertarget.RenderTargets;
import net.coderbot.iris.shaderpack.PackRenderTargetDirectives;
import net.coderbot.iris.shaderpack.PackShadowDirectives;
import net.coderbot.iris.shadows.ShadowRenderTargets;
import net.coderbot.iris.texture.format.TextureFormat;
import net.coderbot.iris.texture.pbr.PBRType;
import net.minecraft.client.renderer.texture.AbstractTexture;
import java.util.Set;
@@ -39,6 +44,7 @@ public class IrisSamplers {
private static GlSampler SHADOW_SAMPLER_NEAREST;
private static GlSampler SHADOW_SAMPLER_LINEAR;
private static GlSampler MIPPED_NEAREST_NEAREST;
private IrisSamplers() {
// no construction allowed
@@ -49,8 +55,23 @@ public class IrisSamplers {
// Leave as null - callers handle null gracefully
return;
}
SHADOW_SAMPLER_NEAREST = new GlSampler(false, false, true, true);
SHADOW_SAMPLER_LINEAR = new GlSampler(true, false, true, true);
SHADOW_SAMPLER_NEAREST = new GlSampler(false, false, false, true, true, true);
SHADOW_SAMPLER_LINEAR = new GlSampler(true, true, false, true, true, true);
MIPPED_NEAREST_NEAREST = new GlSampler(false, false, true, false, false, true);
}
public static GlSampler getTerrainSampler(int anisotropy) {
if (BlockRenderingSettings.INSTANCE.breaksAnisotropy()) {
anisotropy = 1;
}
return TextureSamplers.getTerrainSampler(false, anisotropy);
}
public static GlSampler getPbrSampler(TextureFormat format, PBRType type, int anisotropy) {
if (format != null && !format.canInterpolateValues(type)) {
return MIPPED_NEAREST_NEAREST;
}
return getTerrainSampler(anisotropy);
}
public static void addRenderTargetSamplers(SamplerHolder samplers, Supplier<ImmutableSet<Integer>> flipped,
@@ -94,8 +115,8 @@ public class IrisSamplers {
// Add the DH depth textures (stub implementation returns 0 until DH is integrated)
if (pipeline != null) {
samplers.addDynamicSampler(TextureType.TEXTURE_2D, () -> pipeline.getDHCompat().getDepthTex(), (GlSampler) null, "dhDepthTex", "dhDepthTex0");
samplers.addDynamicSampler(TextureType.TEXTURE_2D, () -> pipeline.getDHCompat().getDepthTexNoTranslucent(), (GlSampler) null, "dhDepthTex1");
samplers.addDynamicSampler(TextureType.TEXTURE_2D, () -> pipeline.getDHCompat().getDepthTex(), "dhDepthTex", "dhDepthTex0");
samplers.addDynamicSampler(TextureType.TEXTURE_2D, () -> pipeline.getDHCompat().getDepthTexNoTranslucent(), "dhDepthTex1");
}
}
@@ -137,13 +158,13 @@ public class IrisSamplers {
final GlSampler sampler1 = separateHardwareSamplers ? null : (shadowRenderTargets.isHardwareFiltered(1) ? (shadowRenderTargets.isLinearFiltered(1) ? SHADOW_SAMPLER_LINEAR : SHADOW_SAMPLER_NEAREST) : null);
if (waterShadowEnabled) {
samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, sampler0, "shadowtex0", "watershadow");
if (samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, sampler1, "shadowtex1", "shadow")) {
samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, () -> sampler0, "shadowtex0", "watershadow");
if (samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, () -> sampler1, "shadowtex1", "shadow")) {
usage |= USAGE_SHADOWTEX1;
}
} else {
samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, sampler0, "shadowtex0", "shadow");
if (samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, sampler1, "shadowtex1")) {
samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, () -> sampler0, "shadowtex0", "shadow");
if (samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, () -> sampler1, "shadowtex1")) {
usage |= USAGE_SHADOWTEX1;
}
}
@@ -176,12 +197,12 @@ public class IrisSamplers {
// Hardware-filtered shadow samplers for separate HW sampler access
if (shadowRenderTargets.isHardwareFiltered(0) && separateHardwareSamplers) {
final GlSampler hwSampler0 = shadowRenderTargets.isLinearFiltered(0) ? SHADOW_SAMPLER_LINEAR : SHADOW_SAMPLER_NEAREST;
samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, hwSampler0, "shadowtex0HW");
samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, () -> hwSampler0, "shadowtex0HW");
}
if (shadowRenderTargets.isHardwareFiltered(1) && separateHardwareSamplers) {
final GlSampler hwSampler1 = shadowRenderTargets.isLinearFiltered(1) ? SHADOW_SAMPLER_LINEAR : SHADOW_SAMPLER_NEAREST;
if (samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, hwSampler1, "shadowtex1HW")) {
if (samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, () -> hwSampler1, "shadowtex1HW")) {
usage |= USAGE_SHADOWTEX1;
}
}
@@ -207,8 +228,12 @@ public class IrisSamplers {
samplers.addDynamicSampler(whitePixel::getGlTextureId, "lightmap");
}
samplers.addDynamicSampler(pipeline::getCurrentNormalTexture, StateUpdateNotifiers.normalTextureChangeNotifier, "normals");
samplers.addDynamicSampler(pipeline::getCurrentSpecularTexture, StateUpdateNotifiers.specularTextureChangeNotifier, "specular");
if (pipeline instanceof DeferredWorldRenderingPipeline deferred) {
samplers.addDynamicSampler(TextureType.TEXTURE_2D, pipeline::getCurrentNormalTexture,
StateUpdateNotifiers.normalTextureChangeNotifier, deferred::getNormalSampler, "normals");
samplers.addDynamicSampler(TextureType.TEXTURE_2D, pipeline::getCurrentSpecularTexture,
StateUpdateNotifiers.specularTextureChangeNotifier, deferred::getSpecularSampler, "specular");
}
}
public static int addWorldDepthSamplers(SamplerHolder samplers, RenderTargets renderTargets) {
@@ -41,6 +41,7 @@ public class PackDirectives {
private boolean weatherParticles;
private boolean rainDepth;
private boolean separateAo;
private boolean breaksAnisotropy;
private boolean voxelizeLightBlocks;
private boolean separateEntityDraws;
private boolean frustumCulling;
@@ -89,6 +90,7 @@ public class PackDirectives {
weatherParticles = properties.getWeatherParticles().orElse(true);
rainDepth = properties.getRainDepth().orElse(false);
separateAo = properties.getSeparateAo().orElse(false);
breaksAnisotropy = properties.getBreaksAnisotropy().orElse(false);
voxelizeLightBlocks = properties.getVoxelizeLightBlocks().orElse(false);
separateEntityDraws = properties.getSeparateEntityDraws().orElse(false);
frustumCulling = properties.getFrustumCulling().orElse(true);
@@ -111,6 +113,7 @@ public class PackDirectives {
this(supportedRenderTargets, new PackShadowDirectives(directives.getShadowDirectives()));
cloudSetting = directives.cloudSetting;
separateAo = directives.separateAo;
breaksAnisotropy = directives.breaksAnisotropy;
voxelizeLightBlocks = directives.voxelizeLightBlocks;
separateEntityDraws = directives.separateEntityDraws;
frustumCulling = directives.frustumCulling;
@@ -166,6 +169,10 @@ public class PackDirectives {
return separateAo;
}
public boolean breaksAnisotropy() {
return breaksAnisotropy;
}
public boolean shouldVoxelizeLightBlocks() {
return voxelizeLightBlocks;
}
@@ -87,6 +87,7 @@ public class ShaderProperties {
@Getter private OptionalBoolean concurrentCompute = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean beaconBeamDepth = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean separateAo = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean breaksAnisotropy = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean voxelizeLightBlocks = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean separateEntityDraws = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean frustumCulling = OptionalBoolean.DEFAULT;
@@ -221,6 +222,7 @@ public class ShaderProperties {
handleBooleanDirective(key, value, "allowConcurrentCompute", bool -> concurrentCompute = bool);
handleBooleanDirective(key, value, "beacon.beam.depth", bool -> beaconBeamDepth = bool);
handleBooleanDirective(key, value, "separateAo", bool -> separateAo = bool);
handleBooleanDirective(key, value, "breaksAnisotropy", bool -> breaksAnisotropy = bool);
handleBooleanDirective(key, value, "voxelizeLightBlocks", bool -> voxelizeLightBlocks = bool);
handleBooleanDirective(key, value, "separateEntityDraws", bool -> separateEntityDraws = bool);
handleBooleanDirective(key, value, "frustum.culling", bool -> frustumCulling = bool);
@@ -113,7 +113,7 @@ public class PBRAtlasTexture extends AutoClosableAbstractTexture {
protected void uploadSprite(TextureAtlasSprite sprite) {
final int gutter = ((SpriteExtension) sprite).angelica$getGutterWidth();
if (sprite.animationMetadata.getFrameCount() > 1) {
if (sprite.animationMetadata.getFrameCount() > 0) {
final AnimationMetadataSection metadata = sprite.animationMetadata;
final int frameCount = sprite.getFrameCount();
for (int frame = sprite.frameCounter; frame >= 0; frame--) {