The Mergening (#13)

* ThreadedTessellator -> RenderBlocks instance Tessellator
* Plus a CME workaround until I can figure out why it's happening
* One inject with multiple methods instead of two injects
* Add AF's Tessellator#reset mixin
Fixes screen flashing when chunks are being built
* Thread Saftey
* Make each tesselator use its own ByteBuffer
* Don't make RecyclingList a static variable 🤦
* Add some additions via ITessellatorInstance
* Stop using builtin updateRenderers
* Remove a few unused things in MixinTessellator
* Remove useless casting due to implementing the interface
* Overwrite some more rendering methods to ensure they're not used
* Implement IBlockAccess on WorldSlice
* Currently just proxies to the World... need to get it to use the local cache
* Make WorldSlice use its copied values instead of using the world
* block, meta, and light.  Still need TODO biome
* Finish making WorldSlice thread safe
* Remove last unsafe this.world accesses
* Copy biomeData
* Implement getTileEntity(), and getBiomeGenForCoords()
* Remove unused 1.16+ classes - Biome, Colorizer, and ColorBlender related
* Cache worldHeight instead of asking the provider every time
* Debug Screen updates
* Disable Culling for now (until it works)
* Tessellator Updates
* Use one instance on the main thread, and individual instances on every other thread
* Prevent draw() and buffer.reset() on non singleton instance
* Misc cleanup, maybe better growBuffer?
* Fixing splash screen and GUI issues by excluding SplashProgress from GLStateManager transformer
* Update docs
* Fixing a one line in SodiumWorldRenderer that allows the game setting for the distance at which entities will render. Hope it's not too bad mitch :)
* TileEntites now render
* Less silly transparency
* Removing clamp implementation because I missed the one in mathhelper
* Initial sodium entity smooth lighting
* Fix entity smooth lighting
* Fix lerp uses and use render layers properly (#17)
* Remove some uses of blockstate + patch FluidState
* Fix lerp
* Enable Sodium fluid rendering
* Update FluidRenderer.java
* Rewind buffers when copying
* Fix multidraw
* Force cutout on all non-translucent blocks
* Let vanilla handle render pass state
* Rewrite render layer check to use Forge 1.7 hook
* Fix skylight handling
* Fix flickering
* Clone TEs correctly
* Fixing entityDistMulti (I think)
* Fix TEs rendering on the wrong pass
* Buff max render distance to 32
Pretty useless since the integrated server stalls instantly, but our renderer supports it
* Fix fog
* Fix render distance changes being ignored
* Implement entity culling
* Block face culling
* Re-enable occlusion culling
* Fix x/z coordinate mixup when indexing biome arrays
Partially fixes wrong biome colors, but at chunk edges it's still wrong because
neighboring chunks aren't accessed
* Make a copy of biome data
The old code seemed to work fine but this should be safer
* Make CompatMemoryUtil#memReallocDirect preserve buffer position
LWJGL3's MemoryUtil#memRealloc does this, see its javadoc.
Fixes screen flashing and this error getting printed when indirect buffer grows:
GL_INVALID_OPERATION error generated. Bound draw indirect buffer is not large enough.
* Use biome data of neighboring chunk sections
Fixes wrong colors at chunk edges
* Re-enable fog culling
* Tile entity culling
* Remove some unneeded Sodium code
* Massive code cleanup
* Avoids errors when usin lwjglxdebug
* Bump hodgepodge dep
* Add AngelicaConfig
* Add Mixin to disable MC's builtin checkGLError
* Add configs for iris/sodium
* Iris work
* Move some StateNotifiers to GLStateManager
* Remove some redundant mixins based on sodium/angelica work and rendering state captures
* Add Iris DebugScreenHandler
* rm archaicfix's occlusion renderer and threaded updates
* Implemented Sodium's GUI and a couple of setting fixes (#20)
* Ported Sodium's GUI
* Correct AO
* Fixed Vignette
* Re-enable DirectMemoryAccess
* Adds some code from lwjgl3 in CompatMemoryUtil.java
* Re-add *Unsafe classes
* Remove MixinWorldRenderer
* Add NEID (mixin pr) support
* Only shadow runtime module of antlr4
Reduces jar size by 11 mb
* Update NotFine
* Make LongHashMap actually perform like a hash map
* Options GUI Fixes and some option implementations (#22)
* Correct useNoErrorGLContext option
* Added translucency sorting option
* Implemented Particle Culling
gives real fps boost, however, it's not as big as i thought

* Begin implementing animateOnlyVisibleTextures
* Correct Donation page opening
* Fixed Shift + P
Now it uses NotFine's GUI, but it think that NotFine's GUI should be rewrited for using other config options
* Correct URL's for Linux
* second code cleanup in particle culling
* Fix incorrect TE map population
* Add optional assertMainThread behind `-Dangelica.assertMainThread=true`
* Add back air optimization, but only apply to vanilla air
* Implement more options (#23)
* Combine free regions in GlBufferArena
* Clear global block entity list when initializing renderer
* AF, CompileStubs, and SplashProgress
Remove most of ArchaicFix
* Move a few mixins over to angelica
* Disable if org.lwjgl.util.Debug is set
* Only enable Iris/lwjgl debug callbacks if org.lwjgl.util.Debug is set
* Rewrite Tessellator hacks - now using a ThreadLocal instead of only patching RenderBlocks
* Reenable AF mixins, switch to cached debug var, disable incompatible mixins
* Remove AF deps and a late mixin that was missed
* Add Iris Sodium Compat impl
* Fix Sodium GLProgram to use ResourceLocation instead of Identifier
* Start applying Iris -> Sodium Mixins
* Make NotFine menu open if holding shift
* Fixed Tessellators in production env
* Finish Sodium Fluid Renderer (#24)
* Init and pass Sodium LightPipelines
* Remove registry lookup and refactor WorldUtil
* Hook up lighting pipeline
* Patch fluid velocity
* It's alive! Sodium Fluid Renderer is alive!
* Fix face culling not taking third person camera offset into account
* rewrite ACTEntityRenderer to stop transforming ALL the classes
* use ClassConstantPoolParser in TessellatorTransformer to speed up search for Tessellator references
* use ClassConstantPoolParser in GLStateManagerTransformer to speed up search for class references
* rewrite GLStateManagerTransformer and TessellatorTransformer
* merge GLStateManagerTransfor and TessellatorTransformer into one Transformer
* Fixed smooth lighting rendering
* Iris block_id Mixins & BlockStateIdMap initial impl for 1.7.10
* Fix running with lwjgl debug flag & Cleanup old ShadersMod transformers
* Initialize GLStateManager via Mixins instead of all in the static block
* Clean up chunk load/unload tracking, fix chunks rendering without neighbors sometimes
* Fix occlusion culler not re-running after important uploads

Backport of https://github.com/CaffeineMC/sodium-fabric/pull/755

* Add chunks to queues without going through occlusion culler

Partially reverts the previous chunk tracking commit, because
that logic will reintroduce https://github.com/CaffeineMC/sodium-fabric/issues/605

As long as we only rebuild with neighbors present, we shouldn't
see the visual seams
* Extremely primitive synchronization approach for ISBRH
* Use factory for Spdium menu createElement outputs
This will allow NotFine to use Sodium menu elements and vice versa in a future commit.
* Splash Screen Compat
* Separate remaining NamedState enums
* NotFine but it loads Sodium pages
* Hook up NotFine optimizations
* Hook up some NotFine features
* copy over hud caching code from hodgepodge
* backport glstatemanager mixin
* Track thread that currently owns the GL Context in addition to the main thread.
* First pass over FontRenderer, 1300->1400 FPS on my GPU when showing F3
Done:
 - A batching vertex buffer builder for font output
 - Reduction in drawcalls from 1-3 per character to 1 per font atlas switch
 - Mixin to draw the entire F3 screen in one batch, instead of separate batches per line
TODO:
 - Switch drawing to a VBO
 - Cache string meshes across frames
 - Cache string width calculations used for layouts
 - Multidraw to reduce draw calls even further
* Add JVM flag to bypass GL state caching
* Push/Pop Attrib Hacks -- to be evolved later
* Fix FontRenderer+SplashScreen combo
* HUDCaching tweaks
* Add license
* Jabba Compat, and reset tesselator state even if the chunk render thread blows up
* Initial Xaero's World Map + Minimap Support
* Disable Fastcraft & Optifine if present
* Iris Progress
* Wire up more Iris mixins, informing pipeline stages.  Still not rendering anything visible.
* Don't try to transform the server
* Avoid running biome generator on client in singleplayer
* Call world biome retrieval methods instead of copying array directly (#25)
* Shaders now do something!
* Shadow Pass work
* First shadow pass renders; however it moves all around when moving the camera...
* Second shadow pass not running because it makes everything very very dark instead of just rendering translucents
* Actually use the ShadowRenderer Model View when running the shadow pass...
* Enable Sodium SmoothLightPipeline & Iris useSeparateAo
* Avoid repeatedly copying biome data on each Y level (#27)
* Celestial Rotation fixes
* Water progress
* Uniforms audit
* Lightmap workaround
* PBR compiling, stuck on Normal and Specular textures being added in
* Shaderpack selection "works"; ShaderOptions TODO
* Hud caching angelica (#28)
* Potential hud-caching fix
* Shader Options almost working
** Clicking on everything doesn't yet work, and the visuals are slightly off
* Entity shadows seem to be working
* Move glint fix to Mixin
* Rework mouse handling for ShaderPackConfig
* Stop centering shader options vertically
* Angelica pbr (#31)
* Only use Sodium light pipeline if useSeparateAo is on
Sodium pipeline is still very buggy, so isolate it to Iris-only
for now
* Fix region sorting for translucency
* Open Shaderpack now works on Linux
* RM Shadersmod
* Initial iris scrollbar clicking
* Punt unsupported ISBRHs to the main thread
* Delete the ISBRH lock, shouldn't be needed anymore
* Render GT blocks on main thread
* Require CCC 1.2.0+
* Depend on CCC 1.2
* Fix TESRs not being tracked for blocks rendered on main thread
* Cut down number of runtime dependencies, enable CoreTweaks in dev by default
* Add modern F3 background
* Pull over some hodgepodge mixins


---------

Co-authored-by: makamys <[email protected]>
Co-authored-by: embeddedt <[email protected]>
Co-authored-by: rjnasers <[email protected]>
Co-authored-by: ah-OOG-ah <[email protected]>
Co-authored-by: Ryan Nasers <[email protected]>
Co-authored-by: Rad <[email protected]>
Co-authored-by: Bogdan <[email protected]>
Co-authored-by: Caedis <[email protected]>
Co-authored-by: jss2a98aj <[email protected]>
Co-authored-by: Alexdoru <[email protected]>
Co-authored-by: Raven Szewczyk <[email protected]>
Co-authored-by: mist475 <[email protected]>
Co-authored-by: Ryan Nasers <[email protected]>
This commit is contained in:
942 files changed
+65828 -8640

No files matched your search

@@ -0,0 +1,680 @@
package net.coderbot.iris.pipeline;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import com.gtnewhorizons.angelica.compat.toremove.MatrixStack;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.rendering.RenderingState;
import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.IrisRenderSystem;
import net.coderbot.iris.shaderpack.OptionalBoolean;
import net.coderbot.iris.shaderpack.PackDirectives;
import net.coderbot.iris.shaderpack.PackShadowDirectives;
import net.coderbot.iris.shaderpack.ProgramSource;
import net.coderbot.iris.shadow.ShadowMatrices;
import net.coderbot.iris.shadows.CullingDataCache;
import net.coderbot.iris.shadows.ShadowRenderTargets;
import net.coderbot.iris.shadows.frustum.BoxCuller;
import net.coderbot.iris.shadows.frustum.CullEverythingFrustum;
import net.coderbot.iris.shadows.frustum.FrustumHolder;
import net.coderbot.iris.shadows.frustum.advanced.AdvancedShadowCullingFrustum;
import net.coderbot.iris.shadows.frustum.fallback.BoxCullingFrustum;
import net.coderbot.iris.shadows.frustum.fallback.NonCullingFrustum;
import net.coderbot.iris.uniforms.CameraUniforms;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import net.coderbot.iris.uniforms.CelestialUniforms;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.renderer.culling.Frustrum;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.entity.Entity;
import net.minecraft.profiler.Profiler;
import net.minecraft.tileentity.TileEntity;
import org.joml.Matrix4f;
import org.joml.Vector3d;
import org.joml.Vector3f;
import org.joml.Vector4f;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.ARBTextureSwizzle;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL30;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
public class ShadowRenderer {
public static final Matrix4f MODELVIEW = new Matrix4f();
public static FloatBuffer MODELVIEW_BUFFER = BufferUtils.createFloatBuffer(16);
public static final Matrix4f PROJECTION = new Matrix4f();
public static List<TileEntity> visibleTileEntities;
public static boolean ACTIVE = false;
private final float halfPlaneLength;
private final float renderDistanceMultiplier;
private final float entityShadowDistanceMultiplier;
private final int resolution;
private final float intervalSize;
private final Float fov;
private final ShadowRenderTargets targets;
private final OptionalBoolean packCullingState;
private boolean packHasVoxelization;
private final boolean shouldRenderTerrain;
private final boolean shouldRenderTranslucent;
private final boolean shouldRenderEntities;
private final boolean shouldRenderPlayer;
private final boolean shouldRenderBlockEntities;
private final float sunPathRotation;
// private final RenderBuffers buffers;
// private final RenderBuffersExt renderBuffersExt;
private final List<MipmapPass> mipmapPasses = new ArrayList<>();
private final String debugStringOverall;
private FrustumHolder terrainFrustumHolder;
private FrustumHolder entityFrustumHolder;
private String debugStringTerrain = "(unavailable)";
private int renderedShadowEntities = 0;
private int renderedShadowTileEntities = 0;
private Profiler profiler;
public ShadowRenderer(ProgramSource shadow, PackDirectives directives, ShadowRenderTargets shadowRenderTargets) {
this.profiler = Minecraft.getMinecraft().mcProfiler;
final PackShadowDirectives shadowDirectives = directives.getShadowDirectives();
this.halfPlaneLength = shadowDirectives.getDistance();
this.renderDistanceMultiplier = shadowDirectives.getDistanceRenderMul();
this.entityShadowDistanceMultiplier = shadowDirectives.getEntityShadowDistanceMul();
this.resolution = shadowDirectives.getResolution();
this.intervalSize = shadowDirectives.getIntervalSize();
this.shouldRenderTerrain = shadowDirectives.shouldRenderTerrain();
this.shouldRenderTranslucent = shadowDirectives.shouldRenderTranslucent();
this.shouldRenderEntities = shadowDirectives.shouldRenderEntities();
this.shouldRenderPlayer = shadowDirectives.shouldRenderPlayer();
this.shouldRenderBlockEntities = shadowDirectives.shouldRenderBlockEntities();
debugStringOverall = "half plane = " + halfPlaneLength + " meters @ " + resolution + "x" + resolution;
this.terrainFrustumHolder = new FrustumHolder();
this.entityFrustumHolder = new FrustumHolder();
this.fov = shadowDirectives.getFov();
this.targets = shadowRenderTargets;
if (shadow != null) {
// Assume that the shader pack is doing voxelization if a geometry shader is detected.
// Also assume voxelization if image load / store is detected.
this.packHasVoxelization = shadow.getGeometrySource().isPresent();
this.packCullingState = shadowDirectives.getCullingState();
} else {
this.packHasVoxelization = false;
this.packCullingState = OptionalBoolean.DEFAULT;
}
this.sunPathRotation = directives.getSunPathRotation();
// this.buffers = new RenderBuffers();
//
// if (this.buffers instanceof RenderBuffersExt) {
// this.renderBuffersExt = (RenderBuffersExt) buffers;
// } else {
// this.renderBuffersExt = null;
// }
configureSamplingSettings(shadowDirectives);
}
public void setUsesImages(boolean usesImages) {
this.packHasVoxelization = packHasVoxelization || usesImages;
}
public static MatrixStack createShadowModelView(float sunPathRotation, float intervalSize) {
// Determine the camera position
final Vector3d cameraPos = CameraUniforms.getUnshiftedCameraPosition();
final double cameraX = cameraPos.x;
final double cameraY = cameraPos.y;
final double cameraZ = cameraPos.z;
// Set up our modelview matrix stack
final MatrixStack modelView = new MatrixStack();
ShadowMatrices.createModelViewMatrix(modelView, getShadowAngle(), intervalSize, sunPathRotation, cameraX, cameraY, cameraZ);
return modelView;
}
private static WorldClient getLevel() {
return Objects.requireNonNull(Minecraft.getMinecraft().theWorld);
}
private static float getSkyAngle() {
return Minecraft.getMinecraft().theWorld.getCelestialAngle(CapturedRenderingState.INSTANCE.getTickDelta());
}
private static float getSunAngle() {
final float skyAngle = getSkyAngle();
if (skyAngle < 0.75F) {
return skyAngle + 0.25F;
} else {
return skyAngle - 0.75F;
}
}
private static float getShadowAngle() {
float shadowAngle = getSunAngle();
if (!CelestialUniforms.isDay()) {
shadowAngle -= 0.5F;
}
return shadowAngle;
}
private void configureSamplingSettings(PackShadowDirectives shadowDirectives) {
final ImmutableList<PackShadowDirectives.DepthSamplingSettings> depthSamplingSettings =
shadowDirectives.getDepthSamplingSettings();
final ImmutableList<PackShadowDirectives.SamplingSettings> colorSamplingSettings =
shadowDirectives.getColorSamplingSettings();
GLStateManager.glActiveTexture(GL13.GL_TEXTURE4);
configureDepthSampler(targets.getDepthTexture().getTextureId(), depthSamplingSettings.get(0));
configureDepthSampler(targets.getDepthTextureNoTranslucents().getTextureId(), depthSamplingSettings.get(1));
for (int i = 0; i < colorSamplingSettings.size(); i++) {
int glTextureId = targets.get(i).getMainTexture();
configureSampler(glTextureId, colorSamplingSettings.get(i));
}
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
}
private final IntBuffer swizzleBuf = BufferUtils.createIntBuffer(4);
private void configureDepthSampler(int glTextureId, PackShadowDirectives.DepthSamplingSettings settings) {
if (settings.getHardwareFiltering()) {
// We have to do this or else shadow hardware filtering breaks entirely!
IrisRenderSystem.texParameteri(glTextureId, GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_COMPARE_MODE, GL30.GL_COMPARE_REF_TO_TEXTURE);
}
// Workaround for issues with old shader packs like Chocapic v4.
// They expected the driver to put the depth value in z, but it's supposed to only
// be available in r. So we set up the swizzle to fix that.
swizzleBuf.rewind();
swizzleBuf.put(new int[] { GL11.GL_RED, GL11.GL_RED, GL11.GL_RED, GL11.GL_ONE }).rewind();
IrisRenderSystem.texParameteriv(glTextureId, GL11.GL_TEXTURE_2D, ARBTextureSwizzle.GL_TEXTURE_SWIZZLE_RGBA, swizzleBuf);
configureSampler(glTextureId, settings);
}
private void configureSampler(int glTextureId, PackShadowDirectives.SamplingSettings settings) {
if (settings.getMipmap()) {
final int filteringMode = settings.getNearest() ? GL11.GL_NEAREST_MIPMAP_NEAREST : GL11.GL_LINEAR_MIPMAP_LINEAR;
mipmapPasses.add(new MipmapPass(glTextureId, filteringMode));
}
if (!settings.getNearest()) {
// Make sure that things are smoothed
IrisRenderSystem.texParameteri(glTextureId, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
IrisRenderSystem.texParameteri(glTextureId, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
} else {
IrisRenderSystem.texParameteri(glTextureId, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
IrisRenderSystem.texParameteri(glTextureId, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
}
}
private void generateMipmaps() {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE4);
for (MipmapPass mipmapPass : mipmapPasses) {
setupMipmappingForTexture(mipmapPass.getTexture(), mipmapPass.getTargetFilteringMode());
}
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
}
private void setupMipmappingForTexture(int texture, int filteringMode) {
IrisRenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D);
IrisRenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, filteringMode);
}
private FrustumHolder createShadowFrustum(float renderMultiplier, FrustumHolder holder) {
// TODO: Cull entities / block entities with Advanced Frustum Culling even if voxelization is detected.
String distanceInfo;
String cullingInfo;
if ((packCullingState == OptionalBoolean.FALSE || packHasVoxelization) && packCullingState != OptionalBoolean.TRUE) {
double distance = halfPlaneLength * renderMultiplier;
String reason;
if (packCullingState == OptionalBoolean.FALSE) {
reason = "(set by shader pack)";
} else /*if (packHasVoxelization)*/ {
reason = "(voxelization detected)";
}
if (distance <= 0 || distance > Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16) {
distanceInfo = Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16
+ " blocks (capped by normal render distance)";
cullingInfo = "disabled " + reason;
return holder.setInfo(new NonCullingFrustum(), distanceInfo, cullingInfo);
} else {
distanceInfo = distance + " blocks (set by shader pack)";
cullingInfo = "distance only " + reason;
BoxCuller boxCuller = new BoxCuller(distance);
holder.setInfo(new BoxCullingFrustum(boxCuller), distanceInfo, cullingInfo);
}
} else {
BoxCuller boxCuller;
double distance = halfPlaneLength * renderMultiplier;
String setter = "(set by shader pack)";
if (renderMultiplier < 0) {
// TODO: GUI
// distance = IrisVideoSettings.shadowDistance * 16;
distance = 32 * 16;
setter = "(set by user)";
}
if (distance >= Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16) {
distanceInfo = Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16
+ " blocks (capped by normal render distance)";
boxCuller = null;
} else {
distanceInfo = distance + " blocks " + setter;
if (distance == 0.0) {
cullingInfo = "no shadows rendered";
holder.setInfo(new CullEverythingFrustum(), distanceInfo, cullingInfo);
}
boxCuller = new BoxCuller(distance);
}
cullingInfo = "Advanced Frustum Culling enabled";
Vector4f shadowLightPosition = new CelestialUniforms(sunPathRotation).getShadowLightPositionInWorldSpace();
Vector3f shadowLightVectorFromOrigin =
new Vector3f(shadowLightPosition.x(), shadowLightPosition.y(), shadowLightPosition.z());
shadowLightVectorFromOrigin.normalize();
return holder.setInfo(new AdvancedShadowCullingFrustum(RenderingState.INSTANCE.getModelViewMatrix(), RenderingState.INSTANCE.getProjectionMatrix(),
shadowLightVectorFromOrigin, boxCuller), distanceInfo, cullingInfo);
}
return holder;
}
private void setupGlState(Matrix4f projMatrix) {
// Set up our projection matrix and load it into the legacy matrix stack
IrisRenderSystem.setupProjectionMatrix(projMatrix);
// Disable backface culling
// This partially works around an issue where if the front face of a mountain isn't visible, it casts no
// shadow.
//
// However, it only partially resolves issues of light leaking into caves.
//
// TODO: Better way of preventing light from leaking into places where it shouldn't
GLStateManager.disableCull();
}
private void restoreGlState() {
// Restore backface culling
GLStateManager.enableCull();
// Make sure to unload the projection matrix
IrisRenderSystem.restoreProjectionMatrix();
}
private void copyPreTranslucentDepth() {
profiler.endStartSection("translucent depth copy");
targets.copyPreTranslucentDepth();
}
private void renderEntities(EntityRenderer levelRenderer, Frustrum frustum, Object bufferSource, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float tickDelta) {
// TODO: Render
// EntityRenderDispatcher dispatcher = levelRenderer.getEntityRenderDispatcher();
int shadowEntities = 0;
profiler.startSection("cull");
List<Entity> renderedEntities = new ArrayList<>(32);
// TODO: I'm sure that this can be improved / optimized.
// TODO: Render
// TODO: Entity culling
for (Entity entity : getLevel().loadedEntityList) {
if (false/*!dispatcher.shouldRender(entity, frustum, cameraX, cameraY, cameraZ) || entity.isSpectator()*/) {
continue;
}
renderedEntities.add(entity);
}
profiler.endStartSection("sort");
// TODO: Render
// Sort the entities by type first in order to allow vanilla's entity batching system to work better.
renderedEntities.sort(Comparator.comparingInt(entity -> entity.getClass().hashCode()));
profiler.endStartSection("build geometry");
// TODO: Render
GL11.glPushMatrix();
MODELVIEW_BUFFER.clear().rewind();
modelView.peek().getModel().get(MODELVIEW_BUFFER);
GL11.glLoadMatrix(MODELVIEW_BUFFER);
for (Entity entity : renderedEntities) {
RenderManager.instance.renderEntitySimple(entity, tickDelta);//(entity, cameraX, cameraY, cameraZ, tickDelta, modelView, bufferSource);
shadowEntities++;
}
GL11.glPopMatrix();
renderedShadowEntities = shadowEntities;
profiler.endSection();
}
private void renderPlayerEntity(EntityRenderer levelRenderer, Frustrum frustum, Object bufferSource, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float tickDelta) {
// TODO: Render
// EntityRenderDispatcher dispatcher = levelRenderer.getEntityRenderDispatcher();
profiler.startSection("cull");
Entity player = Minecraft.getMinecraft().thePlayer;
// if (!dispatcher.shouldRender(player, frustum, cameraX, cameraY, cameraZ) || player.isSpectator()) {
// return;
// }
profiler.endStartSection("build geometry");
int shadowEntities = 0;
// if (!player.getPassengers().isEmpty()) {
// for (int i = 0; i < player.getPassengers().size(); i++) {
// levelRenderer.invokeRenderEntity(player.getPassengers().get(i), cameraX, cameraY, cameraZ, tickDelta, modelView, bufferSource);
// shadowEntities++;
// }
// }
//
// if (player.getVehicle() != null) {
// levelRenderer.invokeRenderEntity(player.getVehicle(), cameraX, cameraY, cameraZ, tickDelta, modelView, bufferSource);
// shadowEntities++;
// }
//
// levelRenderer.invokeRenderEntity(player, cameraX, cameraY, cameraZ, tickDelta, modelView, bufferSource);
shadowEntities++;
renderedShadowEntities = shadowEntities;
profiler.endSection();
}
private void renderTileEntities(Object bufferSource, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float partialTicks, boolean hasEntityFrustum) {
profiler.startSection("build blockentities");
int shadowTileEntities = 0;
BoxCuller culler = null;
if (hasEntityFrustum) {
culler = new BoxCuller(halfPlaneLength * (renderDistanceMultiplier * entityShadowDistanceMultiplier));
culler.setPosition(cameraX, cameraY, cameraZ);
}
for (TileEntity tileEntity : visibleTileEntities) {
if (hasEntityFrustum && (culler.isCulled(tileEntity.xCoord - 1, tileEntity.yCoord - 1, tileEntity.zCoord - 1, tileEntity.xCoord + 1, tileEntity.yCoord + 1, tileEntity.zCoord + 1))) {
continue;
}
modelView.push();
modelView.translate(tileEntity.xCoord - cameraX, tileEntity.yCoord - cameraY, tileEntity.zCoord - cameraZ);
TileEntityRendererDispatcher.instance.renderTileEntity(tileEntity, partialTicks);
modelView.pop();
shadowTileEntities++;
}
renderedShadowTileEntities = shadowTileEntities;
profiler.endSection();
}
public void renderShadows(EntityRenderer levelRenderer, Camera playerCamera) {
final Minecraft mc = Minecraft.getMinecraft();
final RenderGlobal rg = mc.renderGlobal;
// We have to re-query this each frame since this changes based on whether the profiler is active
// If the profiler is inactive, it will return InactiveProfiler.INSTANCE
this.profiler = Minecraft.getMinecraft().mcProfiler;
Minecraft client = Minecraft.getMinecraft();
profiler.endStartSection("shadows");
ACTIVE = true;
// NB: We store the previous player buffers in order to be able to allow mods rendering entities in the shadow pass (Flywheel) to use the shadow buffers instead.
// TODO: Render
// RenderBuffers playerBuffers = levelRenderer.getRenderBuffers();
// levelRenderer.setRenderBuffers(buffers);
visibleTileEntities = new ArrayList<>();
// Create our camera
final MatrixStack modelView = createShadowModelView(this.sunPathRotation, this.intervalSize);
MODELVIEW.set(modelView.peek().getModel());
final Matrix4f shadowProjection;
if (this.fov != null) {
// If FOV is not null, the pack wants a perspective based projection matrix. (This is to support legacy packs)
shadowProjection = ShadowMatrices.createPerspectiveMatrix(this.fov);
} else {
shadowProjection = ShadowMatrices.createOrthoMatrix(halfPlaneLength);
}
PROJECTION.set(shadowProjection);
profiler.startSection("terrain_setup");
if (levelRenderer instanceof CullingDataCache) {
((CullingDataCache) levelRenderer).saveState();
}
profiler.startSection("initialize frustum");
terrainFrustumHolder = createShadowFrustum(renderDistanceMultiplier, terrainFrustumHolder);
// Determine the player camera position
final Vector3d cameraPos = CameraUniforms.getUnshiftedCameraPosition();
final double cameraX = cameraPos.x();
final double cameraY = cameraPos.y();
final double cameraZ = cameraPos.z();
// Center the frustum on the player camera position
terrainFrustumHolder.getFrustum().setPosition(cameraX, cameraY, cameraZ);
profiler.endSection();
// Always schedule a terrain update
// TODO: Only schedule a terrain update if the sun / moon is moving, or the shadow map camera moved.
// We have to ensure that we don't regenerate clouds every frame, since that's what needsUpdate ends up doing.
// This took up to 10% of the frame time before we applied this fix! That's really bad!
// boolean regenerateClouds = levelRenderer.shouldRegenerateClouds();
// ((LevelRenderer) levelRenderer).needsUpdate();
// levelRenderer.setShouldRegenerateClouds(regenerateClouds);
// Execute the vanilla terrain setup / culling routines using our shadow frustum.
mc.renderGlobal.clipRenderersByFrustum(terrainFrustumHolder.getFrustum(), playerCamera.getPartialTicks());
// levelRenderer.invokeSetupRender(playerCamera, terrainFrustumHolder.getFrustum(), false, levelRenderer.getFrameId(), false);
// Don't forget to increment the frame counter! This variable is arbitrary and only used in terrain setup,
// and if it's not incremented, the vanilla culling code will get confused and think that it's already seen
// chunks during traversal, and break rendering in concerning ways.
// levelRenderer.setFrameId(levelRenderer.getFrameId() + 1);
profiler.endStartSection("terrain");
setupGlState(PROJECTION);
// Render all opaque terrain unless pack requests not to
if (shouldRenderTerrain) {
rg.sortAndRender(mc.thePlayer, 0, playerCamera.getPartialTicks());
// levelRenderer.invokeRenderChunkLayer(RenderLayer.solid(), modelView, cameraX, cameraY, cameraZ);
// levelRenderer.invokeRenderChunkLayer(RenderLayer.cutout(), modelView, cameraX, cameraY, cameraZ);
// levelRenderer.invokeRenderChunkLayer(RenderLayer.cutoutMipped(), modelView, cameraX, cameraY, cameraZ);
}
profiler.endStartSection("entities");
// Get the current tick delta. Normally this is the same as client.getTickDelta(), but when the game is paused,
// it is set to a fixed value.
final float tickDelta = CapturedRenderingState.INSTANCE.getTickDelta();
// Create a constrained shadow frustum for entities to avoid rendering faraway entities in the shadow pass,
// if the shader pack has requested it. Otherwise, use the same frustum as for terrain.
boolean hasEntityFrustum = false;
if (entityShadowDistanceMultiplier == 1.0F || entityShadowDistanceMultiplier < 0.0F) {
entityFrustumHolder.setInfo(terrainFrustumHolder.getFrustum(), terrainFrustumHolder.getDistanceInfo(), terrainFrustumHolder.getCullingInfo());
} else {
hasEntityFrustum = true;
entityFrustumHolder = createShadowFrustum(renderDistanceMultiplier * entityShadowDistanceMultiplier, entityFrustumHolder);
}
Frustrum entityShadowFrustum = entityFrustumHolder.getFrustum();
entityShadowFrustum.setPosition(cameraX, cameraY, cameraZ);
// Render nearby entities
//
// Note: We must use a separate BuilderBufferStorage object here, or else very weird things will happen during
// rendering.
// if (renderBuffersExt != null) {
// renderBuffersExt.beginLevelRendering();
// }
// if (buffers instanceof DrawCallTrackingRenderBuffers) {
// ((DrawCallTrackingRenderBuffers) buffers).resetDrawCounts();
// }
// BufferSource bufferSource = buffers.bufferSource();
if (shouldRenderEntities) {
renderEntities(levelRenderer, entityShadowFrustum, null, modelView, cameraX, cameraY, cameraZ, tickDelta);
} else if (shouldRenderPlayer) {
// renderPlayerEntity(levelRenderer, entityShadowFrustum, bufferSource, modelView, cameraX, cameraY, cameraZ, tickDelta);
}
if (shouldRenderBlockEntities) {
// renderTileEntities(bufferSource, modelView, cameraX, cameraY, cameraZ, tickDelta, hasEntityFrustum);
}
profiler.endStartSection("draw entities");
// NB: Don't try to draw the translucent parts of entities afterwards. It'll cause problems since some
// shader packs assume that everything drawn afterwards is actually translucent and should cast a colored
// shadow...
// bufferSource.endBatch();
copyPreTranslucentDepth();
profiler.endStartSection("translucent terrain");
// TODO: Prevent these calls from scheduling translucent sorting...
// It doesn't matter a ton, since this just means that they won't be sorted in the getNormal rendering pass.
// Just something to watch out for, however...
if (shouldRenderTranslucent) {
// TODO: Render
// TODO -- This makes everything look... weird
// rg.sortAndRender(mc.thePlayer, 1, playerCamera.getPartialTicks());
// levelRenderer.invokeRenderChunkLayer(RenderLayer.translucent(), modelView, cameraX, cameraY, cameraZ);
}
// Note: Apparently tripwire isn't rendered in the shadow pass.
// worldRenderer.invokeRenderType(RenderType.getTripwire(), modelView, cameraX, cameraY, cameraZ);
// if (renderBuffersExt != null) {
// renderBuffersExt.endLevelRendering();
// }
// TODO: Render
debugStringTerrain = SodiumWorldRenderer.getInstance().getChunksDebugString();
profiler.endStartSection("generate mipmaps");
generateMipmaps();
profiler.endStartSection("restore gl state");
restoreGlState();
if (levelRenderer instanceof CullingDataCache) {
((CullingDataCache) levelRenderer).restoreState();
}
// TODO: Render
// levelRenderer.setRenderBuffers(playerBuffers);
ACTIVE = false;
profiler.endSection();
profiler.endStartSection("updatechunks");
}
public void addDebugText(List<String> messages) {
messages.add("[" + Iris.MODNAME + "] Shadow Maps: " + debugStringOverall);
messages.add("[" + Iris.MODNAME + "] Shadow Distance Terrain: " + terrainFrustumHolder.getDistanceInfo() + " Entity: " + entityFrustumHolder.getDistanceInfo());
messages.add("[" + Iris.MODNAME + "] Shadow Culling Terrain: " + terrainFrustumHolder.getCullingInfo() + " Entity: " + entityFrustumHolder.getCullingInfo());
messages.add("[" + Iris.MODNAME + "] Shadow Terrain: " + debugStringTerrain + (shouldRenderTerrain ? "" : " (no terrain) ") + (shouldRenderTranslucent ? "" : "(no translucent)"));
messages.add("[" + Iris.MODNAME + "] Shadow Entities: " + getEntitiesDebugString());
messages.add("[" + Iris.MODNAME + "] Shadow Block Entities: " + getTileEntitiesDebugString());
// if (buffers instanceof DrawCallTrackingRenderBuffers drawCallTracker && (shouldRenderEntities || shouldRenderPlayer)) {
// messages.add("[" + Iris.MODNAME + "] Shadow Entity Batching: " + BatchingDebugMessageHelper.getDebugMessage(drawCallTracker));
// }
}
private String getEntitiesDebugString() {
return (shouldRenderEntities || shouldRenderPlayer) ? (renderedShadowEntities + "/" + Minecraft.getMinecraft().theWorld.loadedEntityList.size()) : "disabled by pack";
}
private String getTileEntitiesDebugString() {
return shouldRenderBlockEntities ? (renderedShadowTileEntities + "/" + Minecraft.getMinecraft().theWorld.loadedTileEntityList.size()) : "disabled by pack";
}
private static class MipmapPass {
private final int texture;
private final int targetFilteringMode;
public MipmapPass(int texture, int targetFilteringMode) {
this.texture = texture;
this.targetFilteringMode = targetFilteringMode;
}
public int getTexture() {
return texture;
}
public int getTargetFilteringMode() {
return targetFilteringMode;
}
}
}