Compare commits

..
Author SHA1 Message Date
Connor Colenso 8c8d346560 Add a particle API for mods that size or draw particles themselves
A render scale per particle for the ones the instancer batches straight from their fields, and the pack's
particle program for particles drawn outside the effect renderer. Any number of mods can add a scale source,
the factors multiply.
2026-11-16 16:21:20 +00:00
Connor Colenso e59e4662f2 Let a terrain draw use its own model space as the pack's block grid
Packs pick parts of some blocks by where a pixel sits inside its world block (cauldron water, end portal
frame eyes, brewing stands), which goes wrong for geometry drawn turned or off the grid. While a local grid
is on, the camera and matrix uniforms describe a world where the draw's model space is the block grid. View
space, clip space and the shadow map come out the same. Not on the SDL GPU backend.

The remapping is one table in LocalGridFrame, applied where the custom uniform inputs are built, so the Iris
uniform classes stay as they are. Custom uniforms the pack builds from remapped ones get evaluated again too,
and smooth() smooths from the frame's starting value when it's called twice in one frame so it doesn't step
twice.

beginLocalGrid hands back a LocalGrid to close, and warns once if the modelview was left changed. Also adds the
at_midBlock location to TerrainRendering for packs that don't need the grid.
2026-11-16 16:21:20 +00:00
Connor Colenso 6dda240a34 Add positional dynamic lights for things that aren't entities
Mods can make a light at any position, move it and change it, and it lights terrain and entities like a held
torch. Also a way to look up lights near a point and Angelica's falloff.

A light can be set to show under a shaderpack without the shader force option (setLitUnderShaderpacks), for
lights that stand in for real blocks a pack can't light itself. Entity and held item lights still need shader
force, and dynamic lights turned off still means off.

A light can also reach further than a held torch, or less far (setReach, 0-15). It falls off like block light
then, so 15 is what a real block of that luminance gives. Fractions work, for a lamp in something drawn smaller
than life. The default stays the old 7.75 block torch falloff. A positional light only tracks the chunk sections
its light gets into, up to 27 at reach 15, so a longer reach rebuilds more when it moves. A change in reach
under 0.1 doesn't rebuild anything, like a move under 0.1 blocks.

Switching dynamic lights, shader force or the pack now rebuilds the sections the lights were in. Before that a
light that went dark stayed in the terrain until something else rebuilt it, and with a pack on that would leave
entity lights behind next to the ones that stay lit. A light that sat still also never came back.

The per section source filter now counts the cells a block outside the section too (14.8 from the middle
instead of 13.9), the same cells the section tracking rebuilds for.
2026-11-16 16:21:20 +00:00
Connor Colenso 9aea999a86 Add shadow casters so mod geometry can draw into the shadow map
Casters run in the shadow pass with the solid shadows and again after translucent terrain, so geometry drawn
from a TESR or the world draw stage can shadow like terrain.
2026-11-15 22:21:54 +00:00
Connor Colenso 72657e5cfb Add a world draw stage for mod geometry inside the world pass
RenderWorldLastEvent comes after the pack's composite passes, so anything drawn there misses its lighting,
fog and shadows. Drawers registered here run right after block entities, once per Forge pass.
2026-11-15 22:21:54 +00:00
Connor Colenso 30a0291cca Add a terrain API for mods that bake blocks outside the chunk mesher
TerrainRendering lets geometry drawn outside the chunk renderer (moving structures, previews) use the
pack's terrain programs, materials, layer overrides and AO and shading settings, and bake the same way the
mesher does. TerrainLighter runs the mesher's smooth and flat light pipelines over any block access.
Vanilla AO can be turned off per thread while baking.
2026-11-15 22:21:54 +00:00
39 changed files with 1805 additions and 45 deletions

No files matched your search

@@ -0,0 +1,61 @@
package com.gtnewhorizons.angelica.api.dynamiclights;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.dynamiclights.PositionalLightSource;
public final class DynamicLightsApi {
private DynamicLightsApi() {}
/** True when dynamic lights are on (the setting is on, and there's no shaderpack or shader force is on). */
public static boolean isEnabled() {
return DynamicLights.isEnabled();
}
/**
* True when lights made with this {@link PositionalLight#setLitUnderShaderpacks} setting give light right now. With
* true that's whenever dynamic lights are on, shaderpack or not.
*/
public static boolean isEnabled(boolean litUnderShaderpacks) {
return DynamicLights.isEnabled(litUnderShaderpacks);
}
/** A new light, off until it gets a luminance. */
public static PositionalLight createLight() {
return new PositionalLightSource();
}
/**
* Calls the visitor for every dynamic light within radius blocks of the point that gives light right now, entities
* included. Positional lights are passed as themselves, other lights as null. Under a shaderpack without shader
* force that's only the lights lit under shaderpacks.
*/
public static void forEachLightNear(double x, double y, double z, double radius, LightVisitor visitor) {
if (!DynamicLights.isActive()) return;
DynamicLights.get().forEachSourceNear(x, y, z, radius, source -> visitor.visit(
source instanceof PositionalLight light ? light : null,
source.angelica$getDynamicLightX(),
source.angelica$getDynamicLightY(),
source.angelica$getDynamicLightZ(),
source.angelica$getLuminance()));
}
/** How bright a held torch reach dynamic light of this luminance is at this distance, 0 past 7.75 blocks. */
public static double lightLevelAt(int luminance, double distance) {
return DynamicLights.falloff(luminance, distance);
}
/**
* How bright a dynamic light of this luminance and reach (see {@link PositionalLight#setReach}) is at this distance.
* Other lights from {@link #forEachLightNear} come with null and light like {@link PositionalLight#TORCH_REACH}.
*/
public static double lightLevelAt(int luminance, float reach, double distance) {
return DynamicLights.falloff(luminance, reach, distance);
}
@FunctionalInterface
public interface LightVisitor {
void visit(PositionalLight light, double x, double y, double z, int luminance);
}
}
@@ -0,0 +1,54 @@
package com.gtnewhorizons.angelica.api.dynamiclights;
/**
* A dynamic light at a position, for moving things that aren't entities. Make one with
* {@link DynamicLightsApi#createLight}. Lights terrain and entities like a held torch, so only while dynamic lights are
* on (see {@link #setLitUnderShaderpacks} for shaderpacks). Main thread only.
*/
public interface PositionalLight {
/** Moves the light. Cheap enough to call every frame, chunks only rebuild once it's moved a bit. */
void setPosition(double x, double y, double z);
/** Brightness 0-15. 0 switches it off. */
void setLuminance(int luminance);
double getX();
double getY();
double getZ();
int getLuminance();
/**
* Under a shaderpack dynamic lights only show with the player's shader force option, since packs do their own
* held item and entity light. A light that stands in for real blocks (a rendered structure's lamps) has nothing
* else to light the world round it, so set this and it lights things under a pack too, like it does without one.
* Dynamic lights turned off still means off. False by default.
*/
void setLitUnderShaderpacks(boolean lit);
boolean isLitUnderShaderpacks();
/** {@link #setReach} for Angelica's held torch falloff, the default. */
float TORCH_REACH = -1;
/**
* How far it lights at full brightness, 0-15, like block light: a luminance 15 light falls 15 / reach levels a
* block, so 15 lights exactly like a real block of that luminance and smaller reaches fade out sooner. Dimmer lights
* get as far as their luminance allows. {@link #TORCH_REACH} (the default) lights like a held torch instead,
* straight down to nothing at 7.75 blocks whatever the luminance. Fractions are fine, e.g. for a lamp in something
* drawn at an eighth of its size. Like a move under 0.1 blocks, a change under 0.1 doesn't rebuild the terrain it
* lights.
* <p>
* Further costs more: a moving light rebuilds every chunk section its light gets into, up to 27 at reach 15 against
* 8 or so for a torch, and never more than 8 at reach 7 or less.
*/
void setReach(float reach);
float getReach();
/** Switches it off for good and drops it from Angelica's lights. */
void remove();
}
@@ -0,0 +1,4 @@
@API(owner = "angelica", provides = "angelica|dynamiclights", apiVersion = "1")
package com.gtnewhorizons.angelica.api.dynamiclights;
import cpw.mods.fml.common.API;
@@ -0,0 +1,72 @@
package com.gtnewhorizons.angelica.api.particles;
import net.coderbot.iris.layer.GbufferPrograms;
import net.minecraft.client.particle.EntityFX;
import java.util.Arrays;
/** For mods that draw particles themselves or change their size. */
public final class ParticleRendering {
private ParticleRendering() {}
/** A size factor per particle, 1 for a normal one. */
@FunctionalInterface
public interface RenderScale {
float of(EntityFX fx);
}
private static final RenderScale[] NO_SCALES = new RenderScale[0];
// Swapped for a new array on every change, so the per particle read is one field and a length check
private static volatile RenderScale[] renderScales = NO_SCALES;
/**
* Scales the particles Angelica batches straight from their fields without calling {@code renderParticle}, which
* is the ones that don't override it plus the vanilla and BoP ones it knows. Particles that do go through
* {@code renderParticle} keep whatever size that gives, so scale those there. Every source added gets asked about
* every batched particle and the factors multiply, so return 1 for particles that aren't yours.
*/
public static synchronized void addRenderScale(RenderScale source) {
for (RenderScale existing : renderScales) {
if (existing == source) return;
}
final RenderScale[] next = Arrays.copyOf(renderScales, renderScales.length + 1);
next[next.length - 1] = source;
renderScales = next;
}
public static synchronized void removeRenderScale(RenderScale source) {
final RenderScale[] old = renderScales;
for (int i = 0; i < old.length; i++) {
if (old[i] != source) continue;
final RenderScale[] next = new RenderScale[old.length - 1];
System.arraycopy(old, 0, next, 0, i);
System.arraycopy(old, i + 1, next, i, old.length - i - 1);
renderScales = next.length == 0 ? NO_SCALES : next;
return;
}
}
/** The size factor for this particle from every {@link #addRenderScale} source, 1 without any. */
public static float renderScale(EntityFX fx) {
final RenderScale[] sources = renderScales;
if (sources.length == 0) return 1;
float scale = 1;
for (RenderScale source : sources) scale *= source.of(fx);
return scale;
}
/**
* Particles drawn outside the effect renderer (e.g. a mod's own list) get the pack's particle program between this
* and {@link #endParticleDraw}, like the world's particles. Pass the returned token to the end call. Nests. Without
* a pack nothing changes.
*/
public static int beginParticleDraw() {
return GbufferPrograms.beginParticles();
}
public static void endParticleDraw(int token) {
GbufferPrograms.endParticles(token);
}
}
@@ -0,0 +1,4 @@
@API(owner = "angelica", provides = "angelica|particles", apiVersion = "1")
package com.gtnewhorizons.angelica.api.particles;
import cpw.mods.fml.common.API;
@@ -0,0 +1,20 @@
package com.gtnewhorizons.angelica.api.shadows;
/**
* Draws extra geometry into the shaderpack shadow map, for things that should cast shadows but aren't terrain or
* entities. RenderWorldLastEvent geometry never gets there, and TESRs only do when the pack shadows block entities.
* Register with {@link ShadowCasters#register}.
*/
@FunctionalInterface
public interface ShadowCaster {
/**
* Called once per shadow pass for each stage, with the shadow modelview loaded and the block entity shadow program
* bound. Positions are relative to the camera position passed in, so translate by worldX - cameraX etc. Put back
* any GL state you change.
*
* @param stage {@link ShadowStage#SOLID} with the other solid shadows, {@link ShadowStage#TRANSLUCENT} after
* translucent terrain for things the pack should tint light through instead of blocking it
*/
void renderShadow(ShadowStage stage, double cameraX, double cameraY, double cameraZ, float partialTicks);
}
@@ -0,0 +1,44 @@
package com.gtnewhorizons.angelica.api.shadows;
import com.gtnewhorizons.angelica.AngelicaMod;
import net.coderbot.iris.pipeline.ShadowRenderer;
import java.util.concurrent.CopyOnWriteArrayList;
/** Where {@link ShadowCaster}s are registered. Main thread only. */
public final class ShadowCasters {
private static final CopyOnWriteArrayList<ShadowCaster> CASTERS = new CopyOnWriteArrayList<>();
private ShadowCasters() {}
public static void register(ShadowCaster caster) {
CASTERS.addIfAbsent(caster);
}
public static void unregister(ShadowCaster caster) {
CASTERS.remove(caster);
}
/** True while the shaderpack shadow pass is drawing, e.g. to skip work in a TESR that also feeds a caster. */
public static boolean isRenderingShadows() {
return ShadowRenderer.ACTIVE;
}
public static boolean hasCasters() {
return !CASTERS.isEmpty();
}
/** Internal, called by the shadow renderer with its state set up. A caster that throws is dropped. */
public static void renderAll(ShadowStage stage, double cameraX, double cameraY, double cameraZ,
float partialTicks) {
for (ShadowCaster caster : CASTERS) {
try {
caster.renderShadow(stage, cameraX, cameraY, cameraZ, partialTicks);
} catch (Throwable t) {
AngelicaMod.LOGGER.error("Shadow caster {} threw, removing it", caster, t);
CASTERS.remove(caster);
}
}
}
}
@@ -0,0 +1,8 @@
package com.gtnewhorizons.angelica.api.shadows;
public enum ShadowStage {
/** After the shadow pass's entities and tile entities, before translucent depth is split off. */
SOLID,
/** After translucent terrain. Only runs when the pack draws translucent shadows. */
TRANSLUCENT
}
@@ -0,0 +1,4 @@
@API(owner = "angelica", provides = "angelica|shadows", apiVersion = "1")
package com.gtnewhorizons.angelica.api.shadows;
import cpw.mods.fml.common.API;
@@ -0,0 +1,108 @@
package com.gtnewhorizons.angelica.api.terrain;
import com.gtnewhorizons.angelica.rendering.celeritas.VertexArrayQuadView;
import com.gtnewhorizons.angelica.rendering.celeritas.light.LightDataCache;
import com.gtnewhorizons.angelica.rendering.celeritas.light.VanillaDiffuseProvider;
import net.minecraft.client.Minecraft;
import net.minecraft.world.IBlockAccess;
import org.embeddedt.embeddium.impl.model.light.LightPipeline;
import org.embeddedt.embeddium.impl.model.light.data.LightDataAccess;
import org.embeddedt.embeddium.impl.model.light.data.QuadLightData;
import org.embeddedt.embeddium.impl.model.light.flat.FlatLightPipeline;
import org.embeddedt.embeddium.impl.model.light.smooth.SmoothLightPipeline;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFlags;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
import org.embeddedt.embeddium.impl.util.QuadUtil;
/**
* Per-vertex AO and lightmap for block quads, worked out like the chunk mesher lights terrain (same light pipeline and
* light data) but over any block access. For mods baking block geometry outside the chunk renderer.
* <p>
* Not thread safe, use one per thread. Light data is cached per 16 block region, so quads from the same region in a
* row are cheapest. The cache doesn't notice world changes, call {@link #reset} before each bake.
*/
public final class TerrainLighter {
private final LightDataCache cache = new LightDataCache();
private final SmoothLightPipeline smooth;
private final FlatLightPipeline flat;
private final ChunkVertexEncoder.Vertex[] vertices = ChunkVertexEncoder.Vertex.uninitializedQuad();
private final VertexArrayQuadView quad = new VertexArrayQuadView(vertices);
private final QuadLightData out = new QuadLightData();
private int regionX = Integer.MIN_VALUE, regionY, regionZ;
// The last fluid quad, to spot the back face vanilla draws straight after it
private ModelQuadFacing fluidLightFace;
private final float[] fluidXyz = new float[12];
private static final int[] REVERSED = { 0, 3, 2, 1 };
public TerrainLighter(IBlockAccess world) {
cache.setWorld(world);
smooth = new SmoothLightPipeline(cache, VanillaDiffuseProvider.INSTANCE, true);
flat = new FlatLightPipeline(cache, VanillaDiffuseProvider.INSTANCE, true);
}
/** Drops the cached light data so the next quad reads the world again. Call it before each bake. */
public void reset() {
regionX = Integer.MIN_VALUE;
fluidLightFace = null;
}
/**
* Lights one quad of the block at x, y, z.
*
* @param xyz the four corners as x y z, in the block access's coordinates and the quad's vertex order
* @param shade also multiply in the face's directional shading, like terrain unless the pack turns it off.
* False gives AO alone
* @param fluid the block is a fluid (see {@code TerrainRendering.isFluid}). Lit like the mesher lights fluids,
* where the back face vanilla draws right after each face gets its light from the same side as
* the front. Pass a block's quads in the order they were made. Only use the light for fluids,
* the mesher gives them no AO
* @param brightness out, per vertex AO (times shading if asked), 0 to 1
* @param light out, per vertex lightmap, {@code sky << 16 | block}, each 0-240
*/
public void light(float[] xyz, int x, int y, int z, boolean shade, boolean fluid, float[] brightness,
int[] light) {
final int rx = x & ~15, ry = y & ~15, rz = z & ~15;
if (rx != regionX || ry != regionY || rz != regionZ) {
regionX = rx;
regionY = ry;
regionZ = rz;
cache.reset(rx, ry, rz);
}
smooth.reset();
flat.reset();
for (int i = 0; i < 4; i++) {
vertices[i].x = xyz[i * 3];
vertices[i].y = xyz[i * 3 + 1];
vertices[i].z = xyz[i * 3 + 2];
}
final boolean flippedCopy = fluid && fluidLightFace != null && isReversedFluidQuad(xyz);
quad.setup(QuadUtil.calculateNormal(vertices), x, y, z, fluid ? ModelQuadFlags.IS_VANILLA_SHADED : 0,
flippedCopy ? fluidLightFace : null);
// Same rule as the mesher, smooth lighting on and the block doesn't give off light
final boolean smoothLighting = Minecraft.getMinecraft().gameSettings.ambientOcclusion != 0
&& LightDataAccess.unpackLU(cache.get(x, y, z)) == 0;
final LightPipeline pipeline = smoothLighting ? smooth : flat;
pipeline.calculate(quad, x, y, z, out, quad.getCullFace(), quad.getLightFace(), shade, true);
System.arraycopy(out.br, 0, brightness, 0, 4);
System.arraycopy(out.lm, 0, light, 0, 4);
if (fluid && !flippedCopy) {
fluidLightFace = quad.getLightFace();
System.arraycopy(xyz, 0, fluidXyz, 0, 12);
} else if (!fluid) {
fluidLightFace = null;
}
}
private boolean isReversedFluidQuad(float[] xyz) {
for (int i = 0; i < 4; i++) {
final int src = REVERSED[i] * 3;
if (xyz[i * 3] != fluidXyz[src] || xyz[i * 3 + 1] != fluidXyz[src + 1]
|| xyz[i * 3 + 2] != fluidXyz[src + 2]) {
return false;
}
}
return true;
}
}
@@ -0,0 +1,340 @@
package com.gtnewhorizons.angelica.api.terrain;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.api.glstate.GLState;
import com.gtnewhorizons.angelica.api.shaders.ShaderPacks;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import com.gtnewhorizons.angelica.rendering.BlockMaterialAttribute;
import com.gtnewhorizons.angelica.rendering.StateAwareTessellator;
import com.gtnewhorizons.angelica.rendering.celeritas.BlockRenderLayer;
import com.gtnewhorizons.angelica.utils.AnimationsRenderUtils;
import com.prupe.mcpatcher.mal.block.RenderBlocksUtils;
import net.coderbot.iris.Iris;
import net.coderbot.iris.block_rendering.BlockMaterialMapping;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.gl.shader.ProgramCreator;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.coderbot.iris.pipeline.WorldRenderingPhase;
import net.coderbot.iris.shadows.ShadowRenderingState;
import net.coderbot.iris.uniforms.LocalGridFrame;
import net.minecraft.block.Block;
import net.minecraft.block.BlockDoublePlant;
import net.minecraft.block.BlockDynamicLiquid;
import net.minecraft.block.BlockStaticLiquid;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.world.IBlockAccess;
import org.joml.Matrix4f;
import java.util.Map;
/**
* For mods that bake block geometry outside the chunk renderer (moving structures, in-world previews) and want it to
* look like terrain, shaderpacks included.
* <p>
* Under a shaderpack terrain gets the pack's terrain programs, its block.properties materials (mc_Entity) and the
* pack's own AO and directional shading. Draw between {@link #beginTerrainDraw} and {@link #endTerrainDraw} to get the
* terrain programs, and use the getters here to bake the way the pack wants. Without a shaderpack nothing changes.
*/
public final class TerrainRendering {
private static int terrainDrawDepth;
private static boolean terrainDrawPushed;
private static int localGridId;
private TerrainRendering() {}
/**
* Draws until {@link #endTerrainDraw} use the pack's terrain program instead of the one for the current phase
* (entities, block entities). Main thread, end it in a finally block. Nests, the outermost call picks the program.
*
* @param translucent true for render pass 1 geometry (glass, water), false for solid and cutout
*/
public static void beginTerrainDraw(boolean translucent) {
if (terrainDrawDepth++ > 0) return;
terrainDrawPushed = ShaderPacks.isInUse();
if (terrainDrawPushed) {
GbufferPrograms.pushOverridePhase(translucent ? WorldRenderingPhase.TERRAIN_TRANSLUCENT : WorldRenderingPhase.TERRAIN_CUTOUT);
}
}
public static void endTerrainDraw() {
if (terrainDrawDepth == 0) return;
// While the terrain program is still bound, so it gets the real uniforms back
if (terrainDrawDepth == 1) endLocalGrid();
if (--terrainDrawDepth > 0) return;
if (terrainDrawPushed) GbufferPrograms.popOverridePhase();
terrainDrawPushed = false;
}
/** Internal, start of each frame. Ends a terrain draw that never got ended (e.g. the caller threw). */
public static void resetForFrame() {
if (terrainDrawDepth == 0) return;
AngelicaMod.LOGGER.warn("A terrain draw was never ended, ending it");
LocalGridFrame.end();
if (terrainDrawPushed) GbufferPrograms.popOverridePhase();
terrainDrawPushed = false;
terrainDrawDepth = 0;
}
/**
* Call inside {@link #beginTerrainDraw}, in a try-with-resources. Until the grid is closed or the terrain draw
* ends, the pack sees the current modelview's model space as the world. For geometry drawn rotated or off the block
* grid: packs pick out parts of some blocks by where a pixel is inside its world block (cauldron water, end portal
* frame eyes), and off the grid that lands in the wrong spot.
* <p>
* Only the uniforms a pack works out world space from change (camera, matrices, upPosition, eyePosition and the
* like), plus the pack's own custom uniforms made from them. View space and shadows come out the same. Model space
* up counts as up. Draws in between must use the modelview it was started with.
* <p>
* Does nothing without a pack, in the shadow pass, on the SDL GPU backend, if a grid is already on or if the
* modelview can't be inverted. Packs that go by at_midBlock instead get it right from the vertex data alone, see
* {@link #getMidBlockAttributeLocation}.
*
* @return the grid, {@link LocalGrid#isActive} says whether it's on
*/
public static LocalGrid beginLocalGrid() {
if (!terrainDrawPushed || LocalGridFrame.isActive() || BackendManager.RENDER_BACKEND.isSDLGPU()
|| ShadowRenderingState.areShadowsCurrentlyBeingRendered()) {
return LocalGrid.OFF;
}
final Matrix4f modelView = GLState.getModelViewMatrix(new Matrix4f());
if (!LocalGridFrame.begin(modelView)) return LocalGrid.OFF;
refreshBoundUniforms();
return new LocalGrid(++localGridId, modelView);
}
private static void endLocalGrid() {
if (!LocalGridFrame.isActive()) return;
LocalGridFrame.end();
refreshBoundUniforms();
}
// The camera and matrix uniforms are only worked out once a frame, so work them out again and push them to the
// terrain program (binding it first if it's still pending)
private static void refreshBoundUniforms() {
GLSMHooks.resolvePendingProgram();
if (Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline drp) {
drp.refreshUniforms(LocalGridFrame.UNIFORMS);
}
}
/**
* True when the pack wants AO in the vertex color's alpha instead of multiplied into the color, so it can apply it
* itself. Put the AO from {@link TerrainLighter} in alpha when this is set.
*/
public static boolean usesSeparateAo() {
return ShaderPacks.isInUse() && BlockRenderingSettings.INSTANCE.shouldUseSeparateAo();
}
/**
* True when the chunk mesher runs its own light pipeline over terrain, the same one {@link TerrainLighter} runs. It
* only relights the faces {@link #isSmoothLit} marks (and fluids under a pack), everything else keeps the light it
* was baked with. AO goes in the color's alpha when {@link #usesSeparateAo}, multiplied into the color otherwise.
*/
public static boolean usesTerrainLighting() {
return ShaderPacks.isInUse() || BlockRenderingSettings.INSTANCE.shouldUseSeparateAo()
|| ClientProxy.options().quality.useCeleritasSmoothLighting;
}
/** True when the pack does its own directional shading, so terrain is baked without vanilla's per-face shading. */
public static boolean disablesDirectionalShading() {
return ShaderPacks.isInUse() && BlockRenderingSettings.INSTANCE.shouldDisableDirectionalShading();
}
/**
* The Forge render pass the pack moves this block to (e.g. {@code layer.translucent} in block.properties), or -1 if
* it doesn't move it or there's no pack. The chunk mesher only draws a moved block in that pass, so do the same.
*/
public static int getRenderPassOverride(Block block) {
if (!ShaderPacks.isInUse()) return -1;
final Map<Block, BlockRenderLayer> overrides = BlockRenderingSettings.INSTANCE.getBlockTypeIds();
if (overrides == null) return -1;
final BlockRenderLayer layer = overrides.get(block);
return layer == null ? -1 : layer.toVanillaPass();
}
/** The pack's block.properties id for this block, -1 if it's unmapped or there's no pack. */
public static int getBlockMaterialId(Block block, int metadata) {
return ShaderPacks.isInUse() ? BlockMaterialAttribute.blockMaterialId(block, metadata) : -1;
}
/**
* The id the chunk mesher gives this block where it stands, which isn't always the plain lookup. A fluid with no
* entry uses its still or flowing twin's, grass under snow gets the pack's snowy entry and the top half of a double
* plant is looked up as the plant its bottom half says. -1 if it's unmapped or there's no pack.
*/
public static int getBlockMaterialId(IBlockAccess world, Block block, int metadata, int x, int y, int z) {
if (!ShaderPacks.isInUse()) return -1;
if (isFluid(block)) {
int id = BlockMaterialAttribute.blockMaterialId(block, metadata);
if (id == -1) {
Block twin = null;
if (block instanceof BlockStaticLiquid) twin = Block.getBlockById(Block.getIdFromBlock(block) - 1);
else if (block instanceof BlockDynamicLiquid) twin = Block.getBlockById(Block.getIdFromBlock(block) + 1);
if (twin != null) id = BlockMaterialAttribute.blockMaterialId(twin, metadata);
}
return id;
}
int effectiveMeta = metadata;
if (BlockRenderingSettings.INSTANCE.hasSnowyEntries()
&& BlockRenderingSettings.INSTANCE.getSnowyBlocks().contains(block)
&& RenderBlocksUtils.isSnowCovered(world, x, y, z)) {
effectiveMeta |= BlockMaterialMapping.SNOWY_META_BIT;
} else if (block instanceof BlockDoublePlant doublePlant && BlockDoublePlant.func_149887_c(metadata)) {
effectiveMeta = 0x8 | (doublePlant.func_149885_e(world, x, y, z) & 7);
}
return BlockMaterialAttribute.blockMaterialId(block, effectiveMeta);
}
/**
* What the chunk mesher counts as a fluid, water or lava material. Under a pack it lights fluid quads with its
* light pipeline but leaves out the AO, pass that on to {@link TerrainLighter#light}.
*/
public static boolean isFluid(Block block) {
final Material material = block.getMaterial();
return material == Material.water || material == Material.lava;
}
/**
* While on, RenderBlocks draws into this tessellator like it does for the chunk mesher. Pass the one it draws into
* ({@code Tessellator.instance} on the main thread). Standard blocks that would take vanilla's smooth lighting path
* are drawn flat instead, with no AO or face shading, and their vertices get marked (see {@link #isSmoothLit}).
* Light those with {@link TerrainLighter} and leave the rest alone, that's all the mesher does. Only kicks in when
* the mesher would do it too: smooth lighting with Celeritas smooth lighting on, or a pack using separate AO. Turn
* it off again in a finally block.
*/
public static void setMeshing(Tessellator tessellator, boolean meshing) {
((StateAwareTessellator) tessellator).angelica$setCeleritasMeshing(meshing);
}
/**
* True while the vertices being added are from a face the chunk mesher would relight (see {@link #setMeshing}),
* vanilla's smooth lighting path or a renderer that asked for the same. Check it per vertex as they're added.
*/
public static boolean isSmoothLit(Tessellator tessellator) {
return ((StateAwareTessellator) tessellator).angelica$isAppliedAo();
}
/** True while the vertices being added are from a renderer that wants no directional shading on them. */
public static boolean hasNoDirectionalShading(Tessellator tessellator) {
return ((StateAwareTessellator) tessellator).angelica$isNoDirectionalShading();
}
/**
* Vertex attribute location the pack's programs read mc_Entity from. Bake two shorts per vertex here, the material
* id and 0 (1 for fluids, like the mesher). Only bind it while a shaderpack is in use.
*/
public static int getMaterialAttributeLocation() {
return ProgramCreator.MC_ENTITY;
}
/**
* Vertex attribute location the pack's programs read mc_midTexCoord from, the middle of the vertex's sprite. Packs
* use it for sprite bounds (e.g. POM). Two floats per vertex. Only bind it while a shaderpack is in use, and
* between {@link #beginOwnExtendedAttributes} and {@link #endOwnExtendedAttributes}.
*/
public static int getMidTexCoordAttributeLocation() {
return ProgramCreator.MC_MID_TEX_COORD;
}
/**
* Vertex attribute location the pack's programs read at_tangent from. Four floats per vertex, xyz plus w for the
* handedness. Same rules as {@link #getMidTexCoordAttributeLocation}.
*/
public static int getTangentAttributeLocation() {
return ProgramCreator.AT_TANGENT;
}
/**
* Vertex attribute location the pack's programs read at_midBlock from. Four bytes per vertex, not normalized: the
* offset from the vertex to the middle of its block times 64, then the block's light emission (0-15). Bake the
* offset in model space and packs that use it get blocks right even off the grid, no {@link #beginLocalGrid}
* needed. Only bind it while a shaderpack is in use.
*/
public static int getMidBlockAttributeLocation() {
return ProgramCreator.AT_MIDBLOCK;
}
/**
* Angelica fills in mc_midTexCoord and at_tangent itself for client array draws out of a VBO, guessing from the
* buffer layout, and binds that over whatever the draw set. Draws until {@link #endOwnExtendedAttributes} bring
* their own and are left alone. Nests, main thread.
*/
public static void beginOwnExtendedAttributes() {
FfpExtendedAttribs.beginInternalDraw();
}
public static void endOwnExtendedAttributes() {
FfpExtendedAttribs.endInternalDraw();
}
/**
* Angelica only animates sprites it saw drawn this frame, and geometry baked once and drawn from a buffer never
* goes through the tessellator again. This records the sprites used on this thread until it's closed.
* Call {@link SpriteCapture#markUsed} each frame the baked geometry is drawn. Close it on the same thread, in a
* finally block.
*/
public static SpriteCapture captureSprites() {
return new SpriteCapture(AnimationsRenderUtils.captureSprites());
}
/** See {@link #beginLocalGrid}. */
public static final class LocalGrid implements AutoCloseable {
private static final LocalGrid OFF = new LocalGrid(0, null);
private static boolean warnedModelView;
private final int id;
private final Matrix4f modelView;
private LocalGrid(int id, Matrix4f modelView) {
this.id = id;
this.modelView = modelView;
}
public boolean isActive() {
return id != 0 && id == localGridId && LocalGridFrame.isActive();
}
/** Ends it. Does nothing if it never started or the terrain draw already ended it. */
@Override
public void close() {
if (!isActive()) return;
// The one rule callers can break without noticing. Only catches a modelview left changed, not one changed
// and put back, but that's cheap enough to always check
if (!warnedModelView && !GLState.getModelViewMatrix(new Matrix4f()).equals(modelView, 1e-4f)) {
warnedModelView = true;
AngelicaMod.LOGGER.warn("Modelview changed during a local grid, draws in it have to use the one it "
+ "started with", new Throwable());
}
endLocalGrid();
}
}
/** See {@link #captureSprites}. */
public static final class SpriteCapture implements AutoCloseable {
private final AnimationsRenderUtils.SpriteCapture capture;
private SpriteCapture(AnimationsRenderUtils.SpriteCapture capture) {
this.capture = capture;
}
/** Marks the recorded sprites as drawn this frame so they keep animating. */
public void markUsed() {
capture.markUsed();
}
/** Stops recording. The sprites recorded so far stay. */
@Override
public void close() {
capture.close();
}
}
}
@@ -0,0 +1,4 @@
@API(owner = "angelica", provides = "angelica|terrain", apiVersion = "1")
package com.gtnewhorizons.angelica.api.terrain;
import cpw.mods.fml.common.API;
@@ -0,0 +1,59 @@
package com.gtnewhorizons.angelica.api.world;
import com.gtnewhorizons.angelica.AngelicaMod;
import net.minecraftforge.client.MinecraftForgeClient;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* A spot in the world pass for mods that draw their own world geometry (moving structures, previews, effects).
* <p>
* Forge's {@code RenderWorldLastEvent} fires after Angelica has run the pack's composite and final passes, so anything
* drawn there misses the pack's lighting, fog and shadows. Drawers registered here run right after block entities,
* once per Forge render pass, with the pack's block entity program active like for a TESR. Without a pack they still
* run there.
* <p>
* The modelview is the camera's like for TESRs, so draw relative to the camera
* ({@code TileEntityRendererDispatcher.staticPlayerX/Y/Z}). Put back any GL state you change. Main thread only.
*/
public final class WorldDrawStage {
/** Draws world geometry for one Forge render pass. */
@FunctionalInterface
public interface Drawer {
/**
* @param pass Forge render pass, 0 for solid and cutout, 1 for translucent. Same as
* {@code MinecraftForgeClient.getRenderPass()}
* @param partialTicks the frame's partial ticks
*/
void draw(int pass, float partialTicks);
}
private static final CopyOnWriteArrayList<Drawer> drawers = new CopyOnWriteArrayList<>();
private WorldDrawStage() {}
public static void register(Drawer drawer) {
drawers.addIfAbsent(drawer);
}
public static void unregister(Drawer drawer) {
drawers.remove(drawer);
}
/** Internal, called by Angelica's renderer after block entities. */
public static void run(float partialTicks) {
if (drawers.isEmpty()) return;
final int pass = MinecraftForgeClient.getRenderPass();
for (Drawer drawer : drawers) {
try {
drawer.draw(pass, partialTicks);
} catch (Throwable t) {
// One broken drawer shouldn't take the frame down or spam the log every frame
drawers.remove(drawer);
AngelicaMod.LOGGER.error("World drawer {} threw, removed it", drawer, t);
}
}
}
}
@@ -0,0 +1,4 @@
@API(owner = "angelica", provides = "angelica|world", apiVersion = "1")
package com.gtnewhorizons.angelica.api.world;
import cpw.mods.fml.common.API;
@@ -22,7 +22,7 @@ public final class AngelicaEntries {
}
public static void dynamicLights(DebugScreenDisplayer displayer, DebugContext context) {
if (!DynamicLights.configEnabled || !DynamicLights.isEnabled()) return;
if (!DynamicLights.configEnabled || !DynamicLights.isActive()) return;
final DynamicLights lights = DynamicLights.get();
final DebugFact fact = displayer.fact(DebugGroup.ANGELICA, "Dynamic Lights");
fact.value(lights.getLightSourcesCount()).text(" sources, ").value(lights.getLastUpdateCount()).text(" updated");
@@ -40,6 +40,7 @@ import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
import java.util.function.Predicate;
public class DynamicLights {
@@ -53,18 +54,50 @@ public class DynamicLights {
public static final boolean configEnabled = AngelicaConfig.enableDynamicLights;
private static final double MAX_RADIUS = 7.75;
private static final double MAX_RADIUS_SQUARED = MAX_RADIUS * MAX_RADIUS;
private final Set<IDynamicLightSource> dynamicLightSources = new ObjectOpenHashSet<>();
private IDynamicLightSource[] lightSourceArray = new IDynamicLightSource[0];
private static final IDynamicLightSource[] NO_SOURCES = new IDynamicLightSource[0];
private IDynamicLightSource[] lightSourceArray = NO_SOURCES;
// The sources that light things under a shaderpack without shader force, see isActive
private IDynamicLightSource[] shaderpackSourceArray = NO_SOURCES;
private final ReentrantReadWriteLock lightSourcesLock = new ReentrantReadWriteLock();
private volatile int lightSourceCount = 0;
private volatile int shaderpackSourceCount = 0;
private final ChunkRebuildManager chunkRebuildManager = new ChunkRebuildManager();
private long lastUpdate = System.currentTimeMillis();
private int lastUpdateCount = 0;
// Which sources gave light at the last update: 0 none, 1 the ones lit under shaderpacks, 2 all of them
private int litState = -1;
/** Must be called under write lock. */
private void rebuildLightSourceArray() {
this.lightSourceArray = this.dynamicLightSources.toArray(new IDynamicLightSource[0]);
this.lightSourceArray = this.dynamicLightSources.toArray(NO_SOURCES);
int count = 0;
for (IDynamicLightSource source : this.lightSourceArray) {
if (source.angelica$isLitUnderShaderpacks()) count++;
}
final IDynamicLightSource[] shaderpackSources = new IDynamicLightSource[count];
int i = 0;
for (IDynamicLightSource source : this.lightSourceArray) {
if (source.angelica$isLitUnderShaderpacks()) shaderpackSources[i++] = source;
}
this.shaderpackSourceArray = shaderpackSources;
this.shaderpackSourceCount = count;
}
/** The sources that give light right now. Call under the read lock. */
private IDynamicLightSource[] activeSources() {
if (isEnabled()) return this.lightSourceArray;
return configEnabled && Mode.isEnabled() ? this.shaderpackSourceArray : NO_SOURCES;
}
/** A tracked source changed whether it's lit under shaderpacks. */
public void onShaderpackLitChanged(IDynamicLightSource lightSource) {
this.lightSourcesLock.writeLock().lock();
try {
if (this.dynamicLightSources.contains(lightSource)) rebuildLightSourceArray();
} finally {
this.lightSourcesLock.writeLock().unlock();
}
}
public static DynamicLights get() {
@@ -81,6 +114,22 @@ public class DynamicLights {
(ShaderForce || !IrisApi.getInstance().isShaderPackInUse());
}
/**
* True when a light that's lit under shaderpacks (or not, see {@link IDynamicLightSource#angelica$isLitUnderShaderpacks})
* gives light right now. Those only skip the shaderpack check, dynamic lights turned off still means off.
*/
public static boolean isEnabled(boolean litUnderShaderpacks) {
return isEnabled() || litUnderShaderpacks && configEnabled && Mode.isEnabled();
}
/**
* True when any light gives light right now: all of them ({@link #isEnabled()}), or only the ones lit under
* shaderpacks when a pack turned the rest off. What the light pipeline checks before it does any dynamic light work.
*/
public static boolean isActive() {
return isEnabled() || configEnabled && Mode.isEnabled() && get().shaderpackSourceCount > 0;
}
public boolean hasLightSources() {
return lightSourceCount > 0;
}
@@ -99,7 +148,13 @@ public class DynamicLights {
* @param renderer the renderer
*/
public void updateAll(@NotNull IDynamicLightWorldRenderer renderer) {
if (!isEnabled())
final int state = isEnabled() ? 2 : configEnabled && Mode.isEnabled() ? 1 : 0;
if (state != this.litState) {
if (this.litState != -1) relightAll(renderer);
this.litState = state;
}
if (!isActive())
return;
final long now = System.currentTimeMillis();
@@ -129,7 +184,7 @@ public class DynamicLights {
}
this.lightSourcesLock.readLock().lock();
for (var lightSource : this.lightSourceArray) {
for (var lightSource : activeSources()) {
// Entity type filter
if (!EntityLightConfig.isEntityTypeEnabled(lightSource)) {
continue;
@@ -151,6 +206,23 @@ public class DynamicLights {
}
}
/**
* The player switched dynamic lights, shader force or the shaderpack, so which sources give light changed. The
* sections they lit rebuild, and every source starts over on its next update. Without this a light that went dark
* stays in the terrain until something else rebuilds it, and one that sits still never comes back.
*/
private void relightAll(@NotNull IDynamicLightWorldRenderer renderer) {
this.lightSourcesLock.readLock().lock();
try {
for (IDynamicLightSource source : this.lightSourceArray) {
source.angelica$scheduleTrackedChunksRebuild(renderer);
source.angelica$resetDynamicLight();
}
} finally {
this.lightSourcesLock.readLock().unlock();
}
}
public int getLastUpdateCount() {
return this.lastUpdateCount;
}
@@ -245,7 +317,7 @@ public class DynamicLights {
}
}
this.lightSourceCount = 0;
this.lightSourceArray = new IDynamicLightSource[0];
rebuildLightSourceArray();
this.lightSourcesLock.writeLock().unlock();
}
@@ -282,7 +354,7 @@ public class DynamicLights {
public double getDynamicLightLevel(int x, int y, int z) {
double result = 0;
this.lightSourcesLock.readLock().lock();
for (var lightSource : this.lightSourceArray) {
for (var lightSource : activeSources()) {
result = maxDynamicLightLevel(x, y, z, lightSource, result);
}
this.lightSourcesLock.readLock().unlock();
@@ -296,7 +368,7 @@ public class DynamicLights {
public double getDynamicLightLevel(double x, double y, double z) {
double result = 0;
this.lightSourcesLock.readLock().lock();
for (var lightSource : this.lightSourceArray) {
for (var lightSource : activeSources()) {
result = maxDynamicLightLevelExact(x, y, z, lightSource, result);
}
this.lightSourcesLock.readLock().unlock();
@@ -317,14 +389,11 @@ public class DynamicLights {
final double dz = z - lightSource.angelica$getDynamicLightZ() + 0.5;
final double distanceSquared = dx * dx + dy * dy + dz * dz;
// 7.75 because else we would have to update more chunks and that's not a good idea.
// 15 (max range for blocks) would be too much and a bit cheaty.
if (distanceSquared <= MAX_RADIUS_SQUARED) {
final double multiplier = 1.0 - Math.sqrt(distanceSquared) / MAX_RADIUS;
final double lightLevel = multiplier * (double) luminance;
if (lightLevel > currentLightLevel) {
return lightLevel;
}
// Held torch reach is 7.75 because else we would have to update more chunks and that's not a good idea.
// Lights that ask for more get it (see angelica$getReach), and rebuild more chunks for it.
final double lightLevel = levelAt(lightSource, luminance, distanceSquared);
if (lightLevel > currentLightLevel) {
return lightLevel;
}
}
return currentLightLevel;
@@ -342,12 +411,9 @@ public class DynamicLights {
final double dz = z - lightSource.angelica$getDynamicLightZ();
final double distanceSquared = dx * dx + dy * dy + dz * dz;
if (distanceSquared <= MAX_RADIUS_SQUARED) {
final double multiplier = 1.0 - Math.sqrt(distanceSquared) / MAX_RADIUS;
final double lightLevel = multiplier * (double) luminance;
if (lightLevel > currentLightLevel) {
return lightLevel;
}
final double lightLevel = levelAt(lightSource, luminance, distanceSquared);
if (lightLevel > currentLightLevel) {
return lightLevel;
}
}
return currentLightLevel;
@@ -370,7 +436,7 @@ public class DynamicLights {
}
public static int addDynamicLight(IBlockAccess world, int x, int y, int z, int lightmap) {
if (!isEnabled()) return lightmap;
if (!isActive()) return lightmap;
final DynamicLights dl = get();
if (!dl.hasLightSources()) return lightmap;
final double dynamicLightLevel = dl.getDynamicLightLevel(x, y, z);
@@ -378,27 +444,81 @@ public class DynamicLights {
return lightmap;
}
/**
* Calls the consumer for every lit light source within radius of the point. Runs on a snapshot of the sources, so
* the consumer may add or remove lights.
*/
public void forEachSourceNear(double x, double y, double z, double radius, Consumer<IDynamicLightSource> consumer) {
final IDynamicLightSource[] sources;
this.lightSourcesLock.readLock().lock();
try {
sources = activeSources();
} finally {
this.lightSourcesLock.readLock().unlock();
}
final double radiusSq = radius * radius;
for (IDynamicLightSource source : sources) {
if (source.angelica$getLuminance() <= 0) continue;
final double dx = source.angelica$getDynamicLightX() - x;
final double dy = source.angelica$getDynamicLightY() - y;
final double dz = source.angelica$getDynamicLightZ() - z;
if (dx * dx + dy * dy + dz * dz <= radiusSq) consumer.accept(source);
}
}
/** Light level of a source of this luminance at this distance, with the held torch reach. */
public static double falloff(int luminance, double distance) {
return falloff(luminance, -1, distance);
}
/**
* Light level of a source of this luminance and reach (see {@link IDynamicLightSource#angelica$getReach}) at this
* distance.
*/
public static double falloff(int luminance, float reach, double distance) {
if (luminance <= 0 || reach == 0) return 0;
// Held torch: straight down to 0 at 7.75 blocks, whatever the luminance
if (reach < 0) return distance > MAX_RADIUS ? 0 : (1.0 - distance / MAX_RADIUS) * luminance;
// Like block light: down 15 / reach levels a block, so 15 is vanilla
return Math.max(0, luminance - distance * 15.0 / reach);
}
/** How far the source's light gets at its current luminance, 0 when it's dark. */
public static double reachOf(@NotNull IDynamicLightSource source) {
final int luminance = source.angelica$getLuminance();
if (luminance <= 0) return 0;
final float reach = source.angelica$getReach();
return reach < 0 ? MAX_RADIUS : reach * luminance / 15.0;
}
private static double levelAt(@NotNull IDynamicLightSource source, int luminance, double distanceSquared) {
final double reach = reachOf(source);
if (distanceSquared >= reach * reach) return 0;
return falloff(luminance, source.angelica$getReach(), Math.sqrt(distanceSquared));
}
public List<IDynamicLightSource> getSourcesForChunk(int chunkMinX, int chunkMinY, int chunkMinZ) {
// Chunk center
final double centerX = chunkMinX + 8.0;
final double centerY = chunkMinY + 8.0;
final double centerZ = chunkMinZ + 8.0;
// Max distance from chunk center to any corner is sqrt(3) * 8 ≈ 13.86
// Add MAX_RADIUS to get the search radius (13.86 + 7.75)^2 ≈ 467
final double searchRadiusSq = 470.0; // Slightly padded for safety
// Smooth lighting reads the cells a block outside the section too, and the middle of the furthest of those is
// sqrt(3) * 8.5 ≈ 14.72 from the chunk center. Plus the source's reach (7.75 for a held torch), slightly padded
// for safety
List<IDynamicLightSource> result = null;
this.lightSourcesLock.readLock().lock();
try {
for (var source : this.lightSourceArray) {
for (var source : activeSources()) {
final double dx = source.angelica$getDynamicLightX() - centerX;
final double dy = source.angelica$getDynamicLightY() - centerY;
final double dz = source.angelica$getDynamicLightZ() - centerZ;
final double distSq = dx * dx + dy * dy + dz * dz;
final double searchRadius = 14.8 + reachOf(source);
if (distSq <= searchRadiusSq) {
if (distSq <= searchRadius * searchRadius) {
if (result == null) {
result = new ArrayList<>();
}
@@ -416,7 +536,7 @@ public class DynamicLights {
int accum = 0;
this.lightSourcesLock.readLock().lock();
try {
for (var lightSource : this.lightSourceArray) {
for (var lightSource : activeSources()) {
accum = accumulateSourceRGB(x, y, z, lightSource, accum);
}
} finally {
@@ -446,9 +566,8 @@ public class DynamicLights {
final double dz = z - source.angelica$getDynamicLightZ();
final double distSq = dx * dx + dy * dy + dz * dz;
if (distSq > MAX_RADIUS_SQUARED) return accum;
final double multiplier = 1.0 - Math.sqrt(distSq) / MAX_RADIUS;
final double multiplier = levelAt(source, luminance, distSq) / luminance;
if (multiplier <= 0) return accum;
final int r = (int) (BlockLightProvider.unpackR(rgb) * multiplier);
final int g = (int) (BlockLightProvider.unpackG(rgb) * multiplier);
final int b = (int) (BlockLightProvider.unpackB(rgb) * multiplier);
@@ -44,6 +44,24 @@ public interface IDynamicLightSource {
return DynamicLights.isEnabled() && DynamicLights.get().containsLightSource(this);
}
/**
* Whether this gives light under a shaderpack without the player's shader force option, for lights that stand in
* for real blocks a pack has no other way to light. False for entities and held items, the pack does those.
*/
default boolean angelica$isLitUnderShaderpacks() {
return false;
}
/**
* How far a luminance 15 light of this source gets, 0-15, falling 15 / reach levels a block like block light (15
* is vanilla). -1 for Angelica's held torch falloff, straight down to 0 at 7.75 blocks. The source has to track and
* rebuild every chunk section its light gets into (plus a block, smooth lighting reads the cells next to a face),
* see {@link DynamicLights#reachOf}.
*/
default float angelica$getReach() {
return -1;
}
/**
* Sets whether the dynamic light is enabled or not.
* <p>
@@ -0,0 +1,202 @@
package com.gtnewhorizons.angelica.dynamiclights;
import com.gtnewhorizon.gtnhlib.blockpos.BlockPos;
import com.gtnewhorizon.gtnhlib.blockpos.IBlockPos;
import com.gtnewhorizons.angelica.api.dynamiclights.PositionalLight;
import it.unimi.dsi.fastutil.longs.LongIterator;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import net.minecraft.util.MathHelper;
import org.jetbrains.annotations.NotNull;
/**
* {@link PositionalLight} for mods. Tracks chunks like entity lights do (see MixinEntity), but only the sections its
* light gets into, worked out from its reach: 8 or fewer up to reach 7, mostly 8 for a held torch, up to 27 for a long
* one. Plus the ones it left.
*/
public final class PositionalLightSource implements IDynamicLightSource, PositionalLight {
private volatile double x, y, z;
private volatile int luminance;
private volatile boolean litUnderShaderpacks;
private volatile float reach = TORCH_REACH;
private boolean removed;
private int lastLuminance;
private float lastReach = TORCH_REACH;
private double prevX, prevY, prevZ;
private LongOpenHashSet tracked = new LongOpenHashSet();
private LongOpenHashSet prevTracked = new LongOpenHashSet();
@Override
public void setPosition(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
// Also adds it back after a world unload drops Angelica's lights
syncTracking();
}
@Override
public void setLuminance(int luminance) {
if (removed) return;
this.luminance = Math.max(0, Math.min(15, luminance));
syncTracking();
}
@Override
public double getX() {
return x;
}
@Override
public double getY() {
return y;
}
@Override
public double getZ() {
return z;
}
@Override
public int getLuminance() {
return luminance;
}
@Override
public void setLitUnderShaderpacks(boolean lit) {
if (litUnderShaderpacks == lit) return;
litUnderShaderpacks = lit;
DynamicLights.get().onShaderpackLitChanged(this);
// It may have just gone dark (or lit) under a pack. Redo its chunks either way, the next update puts the light
// back in where it still counts
angelica$resetDynamicLight();
final IDynamicLightWorldRenderer renderer = DynamicLights.getActiveRenderer();
if (renderer != null) angelica$scheduleTrackedChunksRebuild(renderer);
}
@Override
public void setReach(float reach) {
// Anything under 0 (or NaN) is the held torch
this.reach = reach >= 0 ? Math.min(15, reach) : TORCH_REACH;
}
@Override
public float getReach() {
return reach;
}
@Override
public float angelica$getReach() {
return reach;
}
@Override
public boolean isLitUnderShaderpacks() {
return litUnderShaderpacks;
}
@Override
public boolean angelica$isLitUnderShaderpacks() {
return litUnderShaderpacks;
}
@Override
public void remove() {
if (removed) return;
removed = true;
luminance = 0;
syncTracking();
}
// In Angelica's lights while lit and out of them otherwise, dynamic lights on or not. DynamicLights.updateTracking
// only removes while they're on, and re-adds on every call while they're off
private void syncTracking() {
final DynamicLights lights = DynamicLights.get();
final boolean lit = luminance > 0;
if (lit == lights.containsLightSource(this)) return;
angelica$resetDynamicLight();
if (lit) lights.addLightSource(this);
else lights.removeLightSource(this);
}
@Override
public double angelica$getDynamicLightX() {
return x;
}
@Override
public double angelica$getDynamicLightY() {
return y;
}
@Override
public double angelica$getDynamicLightZ() {
return z;
}
@Override
public void angelica$resetDynamicLight() {
lastLuminance = 0;
}
@Override
public int angelica$getLuminance() {
return luminance;
}
@Override
public void angelica$dynamicLightTick() {}
@Override
public boolean angelica$updateDynamicLight(@NotNull IDynamicLightWorldRenderer renderer) {
final double x = this.x, y = this.y, z = this.z;
final int luminance = this.luminance;
final float reach = this.reach;
// Small changes in reach count like small moves, a structure being scaled changes it every frame
if (Math.abs(x - prevX) <= 0.1 && Math.abs(y - prevY) <= 0.1 && Math.abs(z - prevZ) <= 0.1
&& luminance == lastLuminance && Math.abs(reach - lastReach) <= 0.1) {
return false;
}
prevX = x;
prevY = y;
prevZ = z;
lastLuminance = luminance;
lastReach = reach;
final LongOpenHashSet newTracked = prevTracked;
newTracked.clear();
// Every section the light gets into, plus a block: smooth lighting on a face reads the cells in front of it,
// which can be in the next section. Reach is at most 15, so never past the sections right next to this one
final double far = DynamicLights.reachOf(this) + 1;
if (far > 1) {
final int cx = MathHelper.floor_double(x) >> 4, cy = MathHelper.floor_double(y) >> 4,
cz = MathHelper.floor_double(z) >> 4;
final int x0 = x - (cx << 4) < far ? -1 : 0, x1 = ((cx + 1) << 4) - x < far ? 1 : 0;
final int y0 = y - (cy << 4) < far ? -1 : 0, y1 = ((cy + 1) << 4) - y < far ? 1 : 0;
final int z0 = z - (cz << 4) < far ? -1 : 0, z1 = ((cz + 1) << 4) - z < far ? 1 : 0;
for (int dx = x0; dx <= x1; dx++) {
for (int dy = y0; dy <= y1; dy++) {
for (int dz = z0; dz <= z1; dz++) track(renderer, new BlockPos(cx + dx, cy + dy, cz + dz), newTracked);
}
}
}
// Whatever's left in the old set is out of range now
angelica$scheduleTrackedChunksRebuild(renderer);
prevTracked = tracked;
tracked = newTracked;
return true;
}
private void track(IDynamicLightWorldRenderer renderer, IBlockPos chunk, LongOpenHashSet newTracked) {
DynamicLights.scheduleChunkRebuild(renderer, chunk);
DynamicLights.updateTrackedChunks(chunk, tracked, newTracked);
}
@Override
public void angelica$scheduleTrackedChunksRebuild(@NotNull IDynamicLightWorldRenderer renderer) {
final LongIterator it = tracked.iterator();
while (it.hasNext()) DynamicLights.scheduleChunkRebuildForRemoval(renderer, it.nextLong());
}
}
@@ -304,7 +304,7 @@ public final class TracyFramePlots {
Tracy.plotInt(P_QUEUE_TASKS_RAN, AngelicaRenderQueue.getLastFrameTasksRan());
Tracy.plotInt(P_QUEUE_TIME_NS, AngelicaRenderQueue.getLastFrameTimeNs());
if (DynamicLights.isEnabled()) {
if (DynamicLights.isActive()) {
final DynamicLights dl = DynamicLights.get();
Tracy.plotInt(P_DYN_LIGHT_SOURCES, dl.getLightSourcesCount());
Tracy.plotInt(P_DYN_UPDATES, dl.getLastUpdateCount());
@@ -15,6 +15,15 @@ public interface StateAwareTessellator {
void angelica$setAppliedAo(boolean flag);
void angelica$setNoDirectionalShading(boolean flag);
/// The state the next vertex gets. False for tessellators that don't track it.
default boolean angelica$isAppliedAo() {
return false;
}
default boolean angelica$isNoDirectionalShading() {
return false;
}
/// Sets whether we're doing terrain meshing as part of celeritas -- collects additional information.
///
/// Enables per-vertex AO state collection into [#angelica$getVertexStates()].
@@ -112,7 +112,7 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
}
public void setupDynamicLights(int chunkOriginX, int chunkOriginY, int chunkOriginZ) {
if (DynamicLights.isEnabled()) {
if (DynamicLights.isActive()) {
this.dynamicLightsInstance = DynamicLights.get();
this.chunkLightSources = dynamicLightsInstance.getSourcesForChunk(chunkOriginX, chunkOriginY, chunkOriginZ);
} else {
@@ -298,7 +298,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
IrisShaderProviderHolder.shouldUseFaceCulling());
}
if (DynamicLights.isEnabled() && DynamicLights.FrustumCullingEnabled) {
if (DynamicLights.isActive() && DynamicLights.FrustumCullingEnabled) {
DynamicLights.get().processChunkRebuilds(viewport);
}
}
@@ -331,7 +331,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
super.setupShadowTerrain(playerViewport, shadowViewport, cameraState, frame, spectator);
if (DynamicLights.isEnabled() && DynamicLights.FrustumCullingEnabled) {
if (DynamicLights.isActive() && DynamicLights.FrustumCullingEnabled) {
DynamicLights.get().processChunkRebuilds(shadowViewport);
}
@@ -227,7 +227,7 @@ public class WorldSlice implements IBlockAccessExtended, FLBlockAccess, LiquidLo
Arrays.fill(this.biomeData, null);
// Pre-filter dynamic light sources for this chunk section
if (DynamicLights.isEnabled()) {
if (DynamicLights.isActive()) {
this.dynamicLightsInstance = DynamicLights.get();
this.chunkLightSources = dynamicLightsInstance.getSourcesForChunk(this.origin.getMinX(), this.origin.getMinY(), this.origin.getMinZ());
} else {
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.rendering.particles;
import com.gtnewhorizons.angelica.rendering.RenderFailures;
import com.gtnewhorizons.angelica.api.particles.ParticleRendering;
import com.gtnewhorizons.angelica.client.rendering.DeferredDrawBatcher;
import com.gtnewhorizons.angelica.glsm.GLSMAttribStack;
import com.gtnewhorizons.angelica.glsm.GLSMBuffers;
@@ -138,6 +139,8 @@ public final class ParticleInstancer {
STATE.sample();
SCRATCH.brightness = runTessellator.brightness;
if (!descriptor.describe(fx, partialTicks, SCRATCH, STATE)) return;
// Drawn from its fields, so a mod's size factor goes on here. The capture path below gets it from renderParticle
SCRATCH.half *= ParticleRendering.renderScale(fx);
runTessellator.color = SCRATCH.colorABGR;
runTessellator.hasColor = true;
@@ -30,6 +30,12 @@ public class SmoothFloat {
private float cachedHalfLifeDown;
private float cachedDecayDown;
// What the accumulator was at the start of this frame. Custom uniforms can be evaluated again mid-frame (see
// LocalGridFrame), and each of those calls has to smooth from the same point instead of stepping again.
private int frame = -1;
private float frameStartAccumulator;
private boolean frameStartHasInitialValue;
/**
* Computes an exponential decay factor based on the given decay constant and time value
*
@@ -58,6 +64,16 @@ public class SmoothFloat {
* Takes one value from the unsmoothed value sequence, and smooths it into our accumulator
*/
public float updateAndGet(float value, float halfLifeUp, float halfLifeDown) {
final int now = SystemTimeUniforms.COUNTER.getAsInt();
if (now != frame) {
frame = now;
frameStartAccumulator = accumulator;
frameStartHasInitialValue = hasInitialValue;
} else {
accumulator = frameStartAccumulator;
hasInitialValue = frameStartHasInitialValue;
}
if (halfLifeUp != cachedHalfLifeUp) {
cachedHalfLifeUp = halfLifeUp;
if (halfLifeUp == 0.0f) {
@@ -967,6 +967,15 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return current;
}
/** Evaluates these built-in uniforms again and pushes them to the bound pass, see LocalGridFrame. */
public void refreshUniforms(String[] names) {
customUniforms.refreshInputs(names);
if (current != null && current.liveProgram != null
&& GLSMPrograms.getActiveProgram() == current.liveProgram.getProgramId()) {
current.pushCustomUniforms();
}
}
public int getActivePassProgramId() {
if (current == null) return -1;
final Program p = current.boundProgram();
@@ -1497,6 +1506,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
}
void pushCustomUniforms() {
DeferredWorldRenderingPipeline.this.customUniforms.push(liveProgram == program ? this : liveProgram);
}
private void bindSelected() {
final Program selected = select(activeInstancing, GLSMRasterizer.clipEmulationActive());
liveProgram = selected;
@@ -1,6 +1,8 @@
package net.coderbot.iris.pipeline;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.api.shadows.ShadowCasters;
import com.gtnewhorizons.angelica.api.shadows.ShadowStage;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil;
import com.gtnewhorizons.angelica.compat.toremove.MatrixStack;
@@ -869,6 +871,24 @@ public class ShadowRenderer {
profiler.endSection();
}
private void renderShadowCasters(ShadowStage stage, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float partialTicks) {
if (!ShadowCasters.hasCasters()) return;
try (GLDebug.Scope s = GLDebug.scope("shadow:casters")) {
GLSMMatrices.glPushMatrix();
MODELVIEW_BUFFER.clear().rewind();
modelView.peek().getModel().get(MODELVIEW_BUFFER);
GLSMMatrices.glLoadMatrix(MODELVIEW_BUFFER);
GbufferPrograms.beginBlockEntities();
GbufferPrograms.setBlockEntityDefaults();
try {
ShadowCasters.renderAll(stage, cameraX, cameraY, cameraZ, partialTicks);
} finally {
GbufferPrograms.endBlockEntities();
GLSMMatrices.glPopMatrix();
}
}
}
public void renderShadows(EntityRenderer levelRenderer, Camera playerCamera) {
final Minecraft mc = Minecraft.getMinecraft();
final RenderGlobal rg = mc.renderGlobal;
@@ -1027,6 +1047,9 @@ public class ShadowRenderer {
}
}
// Mod geometry that should shadow like terrain, so not tied to the pack's block entity shadow setting
renderShadowCasters(ShadowStage.SOLID, modelView, entityX, entityY, entityZ, tickDelta);
profiler.endStartSection("iris_shadow_draw_entities");
// NB: Don't try to draw the translucent parts of entities afterwards. It'll cause problems since some
@@ -1044,6 +1067,7 @@ public class ShadowRenderer {
try (GLDebug.Scope s = GLDebug.scope("shadow:translucent")) {
rg.sortAndRender(mc.renderViewEntity, 1, playerCamera.getPartialTicks());
}
renderShadowCasters(ShadowStage.TRANSLUCENT, modelView, entityX, entityY, entityZ, tickDelta);
}
// Note: Apparently tripwire isn't rendered in the shadow pass.
@@ -29,6 +29,7 @@ public class CameraUniforms {
public static void addCameraUniforms(UniformHolder uniforms, FrameUpdateNotifier notifier) {
final CameraPositionTracker tracker = new CameraPositionTracker(notifier);
LocalGridFrame.trackCamera(tracker);
uniforms
.uniform1f(ONCE, "near", () -> 0.05)
@@ -0,0 +1,260 @@
package net.coderbot.iris.uniforms;
import org.joml.Matrix3d;
import org.joml.Matrix4f;
import org.joml.Matrix4fc;
import org.joml.Vector3d;
import org.joml.Vector3dc;
import org.joml.Vector3f;
import org.joml.Vector3fc;
import org.joml.Vector3ic;
import org.joml.Vector4f;
import org.joml.Vector4fc;
import java.util.HashMap;
import java.util.Map;
import java.util.function.DoubleSupplier;
import java.util.function.DoubleUnaryOperator;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
/**
* Lets a draw's own model space stand in for the world's block grid, for geometry drawn rotated or off the grid
* (structures, previews).
* <p>
* Packs pick out parts of some blocks by where a pixel is inside its world block, {@code fract(playerPos +
* cameraPosition)}, e.g. the water in a cauldron or the eye of an end portal frame. Off the grid that cuts through the
* block in the wrong place. While this is active the uniforms describe a world where the draw's model coordinates are
* world coordinates, moved by whole blocks to stay near the real position. View space, clip space and the shadow map
* come out exactly the same, so only what a pack works out in world space changes.
* <p>
* Every uniform that changes is in the remap tables below, keyed by name. The custom uniform input holder wraps those
* suppliers when it's built (see the wrap methods), so the uniform classes themselves don't know about any of this. A
* new world space uniform only needs a line here. The uniforms are worked out once a frame, so starting or ending this
* works them out again and pushes them to the bound program, see {@link #UNIFORMS}.
*/
public final class LocalGridFrame {
private static final Map<String, UnaryOperator<Vector3d>> VEC3D = new HashMap<>();
private static final Map<String, UnaryOperator<Vector3fc>> VEC3F = new HashMap<>();
private static final Map<String, UnaryOperator<Vector3ic>> VEC3I = new HashMap<>();
private static final Map<String, UnaryOperator<Vector4fc>> VEC4F = new HashMap<>();
private static final Map<String, UnaryOperator<Matrix4fc>> MATRIX = new HashMap<>();
private static final Map<String, DoubleUnaryOperator> DOUBLE = new HashMap<>();
/** Every uniform that changes under the frame. */
public static final String[] UNIFORMS;
private static boolean active;
private static CameraUniforms.CameraPositionTracker tracker;
// Model to player space is T = V^-1 * M, linear part L and translation t. Everything below comes from that
private static final Matrix4f postfix = new Matrix4f();
private static final Matrix4f postfixInverse = new Matrix4f();
private static final Matrix3d linearInverse = new Matrix3d();
private static final Vector3d eye = new Vector3d();
private static final Vector3d modelCamera = new Vector3d();
private static final Vector3d modelOrigin = new Vector3d();
private static final Vector4f up = new Vector4f();
// What the remaps hand back. Like the suppliers they wrap (CameraUniforms and MatrixUniforms keep scratch objects
// too), a value is only good until the next remap runs. The cached uniforms in the input holder all copy it
// straight away, anything new that takes a wrapped supplier has to do the same
private static final Matrix4f scratch = new Matrix4f();
private static final Vector3d current = new Vector3d();
private static final Vector3d previous = new Vector3d();
private static final Vector3d point = new Vector3d();
private static final Vector3d offset = new Vector3d();
private static final Vector3d direction = new Vector3d();
private static final Vector3f offset3f = new Vector3f();
private static final Vector4f offset4f = new Vector4f();
static {
// World positions. The shifted ones keep Iris's shift, the unshifted ones read the real camera directly
VEC3D.put("cameraPosition", LocalGridFrame::camera);
DOUBLE.put("eyeAltitude", y -> Math.rint(y + modelOrigin.y) + modelCamera.y);
VEC3D.put("previousCameraPosition", real -> tracker == null ? real
: previousCamera(tracker.getCurrentCameraPosition(), real));
VEC3I.put("cameraPositionInt", real -> CameraUniforms.getCameraPositionInt(unshiftedCamera()));
VEC3F.put("cameraPositionFract", real -> CameraUniforms.getCameraPositionFract(unshiftedCamera()));
VEC3I.put("previousCameraPositionInt", real -> tracker == null ? real
: CameraUniforms.getCameraPositionInt(unshiftedPreviousCamera()));
VEC3F.put("previousCameraPositionFract", real -> tracker == null ? real
: CameraUniforms.getCameraPositionFract(unshiftedPreviousCamera()));
VEC3D.put("eyePosition", real -> worldPosition(CameraUniforms.getUnshiftedCameraPosition(), real));
// Offsets from the unshifted camera
VEC3D.put("relativeEyePosition", LocalGridFrame::offset);
VEC3D.put("relativeVehiclePosition", LocalGridFrame::offset);
// -256 on every axis means nothing is selected
VEC3F.put("currentSelectedBlockPos", real -> real.x() == -256.0f && real.y() == -256.0f && real.z() == -256.0f
? real : offset3f.set(offset(point.set(real.x(), real.y(), real.z()))));
// w is 0 when there's no bolt
VEC4F.put("lightningBoltPosition", real -> {
if (real.w() == 0.0f) return real;
final Vector3d moved = offset(point.set(real.x(), real.y(), real.z()));
return offset4f.set((float) moved.x, (float) moved.y, (float) moved.z, real.w());
});
// Directions in the world
VEC3D.put("playerLookVector", LocalGridFrame::direction);
VEC3D.put("playerBodyVector", LocalGridFrame::direction);
VEC3D.put("vehicleLookVector", LocalGridFrame::direction);
// View space, so only up changes
VEC4F.put("upPosition", real -> up);
// Matrices that take world space positions relative to the camera
MATRIX.put("gbufferModelView", LocalGridFrame::modelView);
MATRIX.put("gbufferPreviousModelView", LocalGridFrame::modelView);
MATRIX.put("shadowModelView", LocalGridFrame::modelView);
MATRIX.put("gbufferModelViewInverse", LocalGridFrame::modelViewInverse);
MATRIX.put("shadowModelViewInverse", LocalGridFrame::modelViewInverse);
UNIFORMS = Stream.of(VEC3D, VEC3F, VEC3I, VEC4F, MATRIX, DOUBLE).flatMap(m -> m.keySet().stream())
.toArray(String[]::new);
}
private LocalGridFrame() {}
public static boolean isActive() {
return active;
}
/** The pipeline's camera tracker, for the uniforms that need the camera rather than their own value. */
static void trackCamera(CameraUniforms.CameraPositionTracker cameraTracker) {
tracker = cameraTracker;
}
/**
* @param drawModelView the modelview the geometry is drawn with
* @return false when it can't be done (a modelview that can't be inverted)
*/
public static boolean begin(Matrix4fc drawModelView) {
final Matrix4f view = new Matrix4f(MatrixUniforms.getGbufferModelView());
final Matrix4f viewInverse = new Matrix4f(view).invert();
final Matrix4f model = new Matrix4f(viewInverse).mul(drawModelView);
if (!Float.isFinite(model.determinant()) || Math.abs(model.determinant3x3()) < 1e-8f) return false;
// The camera's eye in player space, and in model space
eye.set(viewInverse.m30(), viewInverse.m31(), viewInverse.m32());
final Matrix3d linear = new Matrix3d(model.m00(), model.m01(), model.m02(), model.m10(), model.m11(),
model.m12(), model.m20(), model.m21(), model.m22());
linearInverse.set(linear).invert();
modelOrigin.set(model.m30(), model.m31(), model.m32());
modelCamera.set(eye).sub(modelOrigin);
linearInverse.transform(modelCamera);
// gbufferModelView' = V * translate(eye) * L, so V' * (p - camera) lands where M * p does
postfix.identity().translate((float) eye.x, (float) eye.y, (float) eye.z)
.mul(new Matrix4f().set3x3(model));
postfix.invert(postfixInverse);
// Model space up in view space, 100 long like the real upPosition
final Vector3f modelUp = model.transformDirection(new Vector3f(0, 1, 0)).normalize(100);
view.transformDirection(modelUp);
up.set(modelUp, 0);
active = true;
return true;
}
public static void end() {
active = false;
}
// The wrap methods are for the custom uniform input holder, each hands back the supplier with the remap applied
// while the frame is active, or the same supplier if that uniform doesn't change
public static Supplier<Vector3d> wrap3d(String name, Supplier<Vector3d> real) {
return wrap(VEC3D.get(name), real);
}
public static Supplier<Vector3fc> wrap3f(String name, Supplier<Vector3fc> real) {
return wrap(VEC3F.get(name), real);
}
public static Supplier<Vector3ic> wrap3i(String name, Supplier<Vector3ic> real) {
return wrap(VEC3I.get(name), real);
}
public static Supplier<Vector4fc> wrap4f(String name, Supplier<Vector4fc> real) {
return wrap(VEC4F.get(name), real);
}
public static Supplier<Matrix4fc> wrapMatrix(String name, Supplier<Matrix4fc> real) {
return wrap(MATRIX.get(name), real);
}
public static DoubleSupplier wrapDouble(String name, DoubleSupplier real) {
final DoubleUnaryOperator remap = DOUBLE.get(name);
if (remap == null) return real;
return () -> active ? remap.applyAsDouble(real.getAsDouble()) : real.getAsDouble();
}
private static <T> Supplier<T> wrap(UnaryOperator<T> remap, Supplier<T> real) {
if (remap == null) return real;
return () -> active ? remap.apply(real.get()) : real.get();
}
/** Where the model origin really is, rounded to whole blocks, so the frame's world stays near the real one. */
private static Vector3d shift(Vector3dc realCamera, Vector3d dest) {
return dest.set(
Math.rint(realCamera.x() + modelOrigin.x),
Math.rint(realCamera.y() + modelOrigin.y),
Math.rint(realCamera.z() + modelOrigin.z));
}
/** cameraPosition (or its unshifted twin) for a real one. */
private static Vector3d camera(Vector3d realCamera) {
return shift(realCamera, current).add(modelCamera);
}
private static Vector3d unshiftedCamera() {
return camera(CameraUniforms.getUnshiftedCameraPosition());
}
private static Vector3d unshiftedPreviousCamera() {
final Vector3d realPrevious = tracker.getPreviousCameraPositionUnshifted();
return previousCamera(CameraUniforms.getUnshiftedCameraPosition(), realPrevious);
}
/** previousCameraPosition, from the camera's last step turned into model space. */
private static Vector3d previousCamera(Vector3d realCamera, Vector3d realPrevious) {
previous.set(realCamera).sub(realPrevious);
linearInverse.transform(previous);
return previous.negate().add(camera(realCamera));
}
/** A real world position (eyePosition) moved into the frame's world, against the unshifted camera. */
private static Vector3d worldPosition(Vector3dc realCamera, Vector3dc realPosition) {
point.set(realPosition).sub(realCamera).sub(modelOrigin);
linearInverse.transform(point);
return shift(realCamera, current).add(point);
}
/**
* An offset from the unshifted camera (relativeEyePosition and co), as the same offset in the frame's world. Works
* out to {@link #worldPosition} minus the unshifted cameraPosition.
*/
private static Vector3d offset(Vector3d realOffset) {
return linearInverse.transform(offset.set(realOffset).sub(eye));
}
/** A world space direction turned into model space, same length. */
private static Vector3d direction(Vector3d real) {
final double length = real.length();
if (length == 0) return real;
return linearInverse.transform(direction.set(real)).normalize(length);
}
/** gbufferModelView, gbufferPreviousModelView or shadowModelView for a real one. */
private static Matrix4fc modelView(Matrix4fc real) {
return scratch.set(real).mul(postfix);
}
/** Their inverses, (R * P)^-1 = P^-1 * R^-1 for the real inverse. */
private static Matrix4fc modelViewInverse(Matrix4fc realInverse) {
return scratch.set(postfixInverse).mul(realInverse);
}
}
@@ -22,7 +22,7 @@ public final class MatrixUniforms {
}
private static final Matrix4f GBUFFER_MODELVIEW_SCRATCH = new Matrix4f();
private static Matrix4fc getGbufferModelView() {
static Matrix4fc getGbufferModelView() {
final Matrix4fc raw = RenderingState.INSTANCE.getModelViewMatrix();
final Entity view = Minecraft.getMinecraft().renderViewEntity;
if (view == null) {
@@ -8,6 +8,7 @@ import net.coderbot.iris.gl.uniform.FloatSupplier;
import net.coderbot.iris.gl.uniform.UniformHolder;
import com.gtnewhorizons.angelica.glsm.shader.UniformType;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.uniforms.LocalGridFrame;
import net.coderbot.iris.uniforms.custom.cached.BooleanCachedUniform;
import net.coderbot.iris.uniforms.custom.cached.CachedUniform;
import net.coderbot.iris.uniforms.custom.cached.Float2VectorCachedUniform;
@@ -94,7 +95,8 @@ public class CustomUniformFixedInputUniformsHolder {
@Override
public Builder uniform1f(UniformUpdateFrequency updateFrequency, String name, DoubleSupplier value) {
return this.put(name, new FloatCachedUniform(name, updateFrequency, () -> (float) value.getAsDouble()));
final DoubleSupplier wrapped = LocalGridFrame.wrapDouble(name, value);
return this.put(name, new FloatCachedUniform(name, updateFrequency, () -> (float) wrapped.getAsDouble()));
}
@Override
@@ -119,11 +121,13 @@ public class CustomUniformFixedInputUniformsHolder {
@Override
public Builder uniform3f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3fc> value) {
value = LocalGridFrame.wrap3f(name, value);
return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, value));
}
@Override
public Builder uniform3i(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3ic> value) {
value = LocalGridFrame.wrap3i(name, value);
return this.put(name, new Int3VectorCachedUniform(name, updateFrequency, value));
}
@@ -134,9 +138,10 @@ public class CustomUniformFixedInputUniformsHolder {
@Override
public Builder uniformTruncated3f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector4fc> value) {
final Supplier<Vector4fc> wrapped = LocalGridFrame.wrap4f(name, value);
Vector3f held = new Vector3f();
return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, () -> {
final Vector4fc vec = value.get();
final Vector4fc vec = wrapped.get();
held.set(vec.x(), vec.y(), vec.z());
return held;
}));
@@ -144,9 +149,10 @@ public class CustomUniformFixedInputUniformsHolder {
@Override
public UniformHolder uniform3d(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3d> value) {
final Supplier<Vector3d> wrapped = LocalGridFrame.wrap3d(name, value);
Vector3f held = new Vector3f();
return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, () -> {
Vector3d vec = value.get();
Vector3d vec = wrapped.get();
held.set(vec.x(), vec.y(), vec.z());
return held;
}));
@@ -154,9 +160,10 @@ public class CustomUniformFixedInputUniformsHolder {
@Override
public UniformHolder uniform4f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector4fc> value) {
final Supplier<Vector4fc> wrapped = LocalGridFrame.wrap4f(name, value);
Vector4f held = new Vector4f();
return this.put(name, new Float4VectorCachedUniform(name, updateFrequency, () -> {
final Vector4fc vec = value.get();
final Vector4fc vec = wrapped.get();
held.set(vec.x(), vec.y(), vec.z(), vec.w());
return held;
}));
@@ -175,6 +182,7 @@ public class CustomUniformFixedInputUniformsHolder {
@Override
public UniformHolder uniformMatrix(
UniformUpdateFrequency updateFrequency, String name, Supplier<Matrix4fc> value) {
value = LocalGridFrame.wrapMatrix(name, value);
return this.put(name, new Float4MatrixCachedUniform(name, updateFrequency, value));
}
@@ -48,6 +48,9 @@ public class CustomUniforms implements FunctionContext {
private final Object2LongOpenHashMap<Object> lastPushedGen = new Object2LongOpenHashMap<>();
private long generation;
private String[] refreshNames;
private CachedUniform[] refreshOrder;
private static final long PLOT_CUSTOM_PUSHED = Tracy.ENABLED ? Tracy.plotHandle("iris.customPushed") : 0;
private static final long PLOT_CUSTOM_SKIPPED = Tracy.ENABLED ? Tracy.plotHandle("iris.customSkipped") : 0;
private int pushedThisFrame;
@@ -254,6 +257,41 @@ public class CustomUniforms implements FunctionContext {
}
}
/**
* Evaluates these built-in uniforms again mid-frame, along with every custom uniform made from them, so the next
* push picks them up (see LocalGridFrame).
*/
public void refreshInputs(String[] names) {
if (names != refreshNames) {
refreshNames = names;
refreshOrder = readersInOrder(names);
}
for (CachedUniform uniform : refreshOrder) {
uniform.update();
}
generation++;
}
// The named inputs that are still used and every custom uniform that reads them, directly or not, in the order
// they're evaluated. uniformOrder is already sorted so each uniform comes after what it reads.
private CachedUniform[] readersInOrder(String[] names) {
final Set<CachedUniform> affected = new ObjectOpenHashSet<>();
for (String name : names) {
final CachedUniform uniform = this.inputHolder.getUniform(name);
if (uniform != null) affected.add(uniform);
}
final List<CachedUniform> ordered = new ObjectArrayList<>();
for (CachedUniform uniform : this.uniformOrder) {
if (!affected.contains(uniform)) {
final List<CachedUniform> dependencies = this.dependsOn.get(uniform);
if (dependencies == null || dependencies.stream().noneMatch(affected::contains)) continue;
affected.add(uniform);
}
ordered.add(uniform);
}
return ordered.toArray(new CachedUniform[0]);
}
public void push(Object pass) {
final PassUniforms pu = this.locationMap.get(pass);
if (pu == null) return;
@@ -15,7 +15,7 @@ public class MixinItemRenderer {
@Surround.Return
private int angelica$dynamiclights_renderItemInFirstPersonResult(int lightmap, WorldClient theWorld, int posX, int posY, int posZ){
if (DynamicLights.isEnabled()) {
if (DynamicLights.isActive()) {
final DynamicLights dl = DynamicLights.get();
if (dl.hasLightSources()) {
final double dynamicLightLevel = dl.getDynamicLightLevel(posX, posY, posZ);
@@ -189,7 +189,7 @@ public abstract class MixinLightDataAccess implements ExtLightDataAccess {
int brgb = provider.getBlockLightRGB(blockAccess, x, y, z);
final int srgb = provider.getSkyLightRGB(blockAccess, x, y, z);
if (DynamicLights.isEnabled()) {
if (DynamicLights.isActive()) {
final int dlRGB = DynamicLights.get().getDynamicLightRGB(x + 0.5, y + 0.5, z + 0.5);
if (dlRGB != 0) {
brgb = angelica$mergeMaxRGB(brgb, dlRGB);
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.mixins.early.celeritas.terrain;
import com.gtnewhorizons.angelica.client.rendering.AngelicaFogService;
import com.gtnewhorizons.angelica.api.world.WorldDrawStage;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil;
import com.gtnewhorizons.angelica.event.RenderChunkEvent;
@@ -284,6 +285,8 @@ public class MixinRenderGlobal implements IRenderGlobalExt {
}
final int blockEntitiesRendered = this.celeritas$renderer.renderBlockEntities(partialTicks);
if (Tracy.ENABLED) Tracy.plotInt(P_BLOCK_ENTITIES_RENDERED, blockEntitiesRendered);
// Mods drawing their own world geometry, still in the block entity phase so a shaderpack lights it
WorldDrawStage.run(partialTicks);
if (Iris.enabled) {
GbufferPrograms.endBlockEntities();
}
@@ -103,6 +103,16 @@ public class MixinTessellator implements StateAwareTessellator, BiomeBlendTessel
this.angelica$noDirectionalShading = flag;
}
@Override
public boolean angelica$isAppliedAo() {
return this.appliedAo;
}
@Override
public boolean angelica$isNoDirectionalShading() {
return this.angelica$noDirectionalShading;
}
@Override
public int[] angelica$getVertexStates() {
return this.vertexStates.elements();
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.mixins.early.shaders;
import com.gtnewhorizons.angelica.api.terrain.TerrainRendering;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.experimental.surround.Surround;
@@ -55,6 +56,8 @@ public abstract class MixinEntityRenderer implements IResourceManagerReloadListe
SystemTimeUniforms.TIMER.beginFrame(System.nanoTime());
Program.unbind();
// Before the frame's uniforms are worked out, so a stuck local grid can't leak into them
TerrainRendering.resetForFrame();
mc.mcProfiler.startSection("iris_prepare_pipeline");
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().preparePipeline(Iris.getCurrentDimensionName());
@@ -0,0 +1,81 @@
package com.gtnewhorizons.angelica.dynamiclights;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class DynamicLightsFalloffTest {
private static final double EPS = 1e-9;
@Test
void reachFifteenIsVanillaBlockLight() {
// A real block of luminance L lights L - distance
for (int luminance = 1; luminance <= 15; luminance++) {
for (int d = 0; d <= 16; d++) {
assertEquals(Math.max(0, luminance - d), DynamicLights.falloff(luminance, 15, d), EPS);
}
}
}
@Test
void shorterReachFadesSooner() {
assertEquals(15, DynamicLights.falloff(15, 5, 0), EPS);
assertEquals(6, DynamicLights.falloff(15, 5, 3), EPS);
assertEquals(0, DynamicLights.falloff(15, 5, 5), EPS);
assertEquals(0, DynamicLights.falloff(15, 5, 6), EPS);
}
@Test
void torchReachIsTheOldFalloff() {
assertEquals(15, DynamicLights.falloff(15, -1, 0), EPS);
assertEquals((1 - 4 / 7.75) * 15, DynamicLights.falloff(15, -1, 4), EPS);
assertEquals(0, DynamicLights.falloff(15, -1, 7.8), EPS);
assertEquals(DynamicLights.falloff(12, -1, 3), DynamicLights.falloff(12, 3), EPS);
}
@Test
void zeroReachOrLuminanceGivesNothing() {
assertEquals(0, DynamicLights.falloff(15, 0, 0), EPS);
assertEquals(0, DynamicLights.falloff(0, 15, 0), EPS);
}
@Test
void fractionalReach() {
// An eighth size glowstone: 15 / 1.875 = 8 levels a block
assertEquals(15, DynamicLights.falloff(15, 1.875f, 0), EPS);
assertEquals(7, DynamicLights.falloff(15, 1.875f, 1), EPS);
assertEquals(0, DynamicLights.falloff(15, 1.875f, 1.875), EPS);
assertEquals(0, DynamicLights.falloff(15, 1.875f, 2), EPS);
}
@Test
void reachOfFollowsLuminance() {
final PositionalLightSource light = new PositionalLightSource();
assertEquals(0, DynamicLights.reachOf(light), EPS);
light.setReach(15);
setLuminanceWithoutTracking(light, 15);
assertEquals(15, DynamicLights.reachOf(light), EPS);
setLuminanceWithoutTracking(light, 6);
assertEquals(6, DynamicLights.reachOf(light), EPS);
light.setReach(-1);
assertEquals(7.75, DynamicLights.reachOf(light), EPS);
light.setReach(99);
assertEquals(15, light.getReach(), EPS);
light.setReach(1.875f);
assertEquals(0.75, DynamicLights.reachOf(light), EPS);
light.setReach(-0.5f);
assertEquals(-1, light.getReach(), EPS);
}
// setLuminance adds the light to Angelica's lights, which needs a game. The field is all reachOf reads
private static void setLuminanceWithoutTracking(PositionalLightSource light, int luminance) {
try {
final java.lang.reflect.Field f = PositionalLightSource.class.getDeclaredField("luminance");
f.setAccessible(true);
f.setInt(light, luminance);
} catch (ReflectiveOperationException e) {
throw new AssertionError(e);
}
}
}
@@ -0,0 +1,166 @@
package com.gtnewhorizons.angelica.dynamiclights;
import com.gtnewhorizon.gtnhlib.util.CoordinatePacker;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** A positional light has to rebuild every chunk section its light shows up in, and the ones it leaves. */
class PositionalLightTrackingTest {
private static final float[] REACHES = { -1, 0.4f, 1, 1.875f, 5, 7, 7.5f, 8, 11, 15 };
private static final int[] LUMINANCES = { 1, 6, 11, 15 };
// Section middles, edges and corners, and either side of the middle where a torch reach just gets out both ways
private static final double[] OFFSETS = { 0, 0.05, 0.6, 3, 7.3, 8, 8.7, 13, 15.4, 15.95 };
private boolean frustumCulling;
@BeforeEach
void rebuildStraightAway() {
// Otherwise rebuilds queue up in the rebuild manager until a frame runs
frustumCulling = DynamicLights.FrustumCullingEnabled;
DynamicLights.FrustumCullingEnabled = false;
}
@AfterEach
void restore() {
DynamicLights.FrustumCullingEnabled = frustumCulling;
}
@Test
void rebuildsEverySectionTheLightGetsInto() {
for (float reach : REACHES) {
for (int luminance : LUMINANCES) {
for (double ox : OFFSETS) {
for (double oy : OFFSETS) {
for (double oz : OFFSETS) {
check(reach, luminance, -32 + ox, 64 + oy, 160 + oz);
}
}
}
}
}
}
private static void check(float reach, int luminance, double x, double y, double z) {
final PositionalLightSource light = new PositionalLightSource();
light.setReach(reach);
set(light, "luminance", luminance);
set(light, "x", x);
set(light, "y", y);
set(light, "z", z);
final Recorder rebuilt = new Recorder();
assertTrue(light.angelica$updateDynamicLight(rebuilt));
final String what = "reach " + reach + " luminance " + luminance + " at " + x + " " + y + " " + z;
final int cx = (int) Math.floor(x) >> 4, cy = (int) Math.floor(y) >> 4, cz = (int) Math.floor(z) >> 4;
for (int dx = -2; dx <= 2; dx++) {
for (int dy = -2; dy <= 2; dy++) {
for (int dz = -2; dz <= 2; dz++) {
final boolean tracked = rebuilt.sections.contains(CoordinatePacker.pack(cx + dx, cy + dy, cz + dz));
if (tracked) {
assertTrue(Math.max(Math.abs(dx), Math.max(Math.abs(dy), Math.abs(dz))) <= 1, what);
} else {
assertFalse(lights(light, cx + dx, cy + dy, cz + dz),
what + " misses section " + dx + " " + dy + " " + dz);
}
}
}
}
if (reach >= 0 && reach <= 7) assertTrue(rebuilt.sections.size() <= 8, what);
}
// What the mesher reads for a section: the light in the middle of each of its cells and the cells a block outside
// it (smooth lighting reads those for faces on the edge)
private static boolean lights(PositionalLightSource light, int sx, int sy, int sz) {
for (int x = -1; x <= 16; x++) {
for (int y = -1; y <= 16; y++) {
for (int z = -1; z <= 16; z++) {
if (DynamicLights.maxDynamicLightLevel((sx << 4) + x, (sy << 4) + y, (sz << 4) + z, light, 0) > 0) {
return true;
}
}
}
}
return false;
}
@Test
void rebuildsWhatItLeaves() {
final PositionalLightSource light = new PositionalLightSource();
light.setReach(5);
set(light, "luminance", 15);
set(light, "x", 8.0);
set(light, "y", 8.0);
set(light, "z", 8.0);
final Recorder first = new Recorder();
light.angelica$updateDynamicLight(first);
assertEquals(1, first.sections.size());
// Three sections along, nothing in common with where it was
set(light, "x", 56.0);
final Recorder second = new Recorder();
assertTrue(light.angelica$updateDynamicLight(second));
assertTrue(second.sections.contains(CoordinatePacker.pack(0, 0, 0)), "the section it left");
assertTrue(second.sections.contains(CoordinatePacker.pack(3, 0, 0)), "the section it went to");
assertEquals(2, second.sections.size());
}
@Test
void sittingStillRebuildsNothing() {
final PositionalLightSource light = new PositionalLightSource();
set(light, "luminance", 15);
set(light, "x", 8.0);
set(light, "y", 8.0);
set(light, "z", 8.0);
final Recorder rebuilt = new Recorder();
assertTrue(light.angelica$updateDynamicLight(rebuilt));
rebuilt.sections.clear();
assertFalse(light.angelica$updateDynamicLight(rebuilt));
assertTrue(rebuilt.sections.isEmpty());
// A new reach counts as a change
light.setReach(15);
assertTrue(light.angelica$updateDynamicLight(rebuilt));
assertEquals(27, rebuilt.sections.size());
// A tiny one doesn't, like a tiny move
rebuilt.sections.clear();
light.setReach(14.95f);
assertFalse(light.angelica$updateDynamicLight(rebuilt));
assertTrue(rebuilt.sections.isEmpty());
}
private static final class Recorder implements IDynamicLightWorldRenderer {
final LongOpenHashSet sections = new LongOpenHashSet();
@Override
public void scheduleRebuildForChunk(int x, int y, int z, boolean important) {
sections.add(CoordinatePacker.pack(x, y, z));
}
@Override
public boolean isActive() {
return true;
}
}
// The setters add the light to Angelica's lights, which needs a game. Tracking only reads the fields
private static void set(PositionalLightSource light, String field, Object value) {
try {
final Field f = PositionalLightSource.class.getDeclaredField(field);
f.setAccessible(true);
f.set(light, value);
} catch (ReflectiveOperationException e) {
throw new AssertionError(e);
}
}
}