Off thread safe blocks (#177)

* Whitelist carpentersblocks for off main thread rendering

* Add bounds checking to WorldSlice,

* Add preliminary `IThreadSafeISBRH` support

* Update TODO

* Adjust min y

* remove unnecessary try/catch

* * Keep track of what should be rendered on the main thread
* Update AngelicaBlockSafetyRegistry to handle vanilla blocks, and ISBHR's

* of -> set
This commit is contained in:
Jason Mitchell authored and GitHub committed 2024-01-12 18:31:01 -08:00
1 parent 537eb06b66
commit c211d90faf
9 files changed
+145 -58

No files matched your search

@@ -80,6 +80,9 @@ public class BlockPos extends Vector3i {
return l;
}
public BlockPos set(long packedPos) {
return set(unpackLongX(packedPos), unpackLongY(packedPos), unpackLongZ(packedPos));
}
public static int unpackLongX(long packedPos) {
return (int)(packedPos << 64 - BIT_SHIFT_X - SIZE_BITS_X >> 64 - SIZE_BITS_X);
@@ -0,0 +1,8 @@
package com.gtnewhorizons.angelica.interfaces;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
public interface IThreadSafeISBRH extends ISimpleBlockRenderingHandler {
IThreadSafeISBRH getThreadLocal();
}
@@ -87,7 +87,7 @@ public enum Mixins {
SODIUM(new Builder("Sodium").addTargetedMod(TargetedMod.VANILLA).setSide(Side.CLIENT)
.setPhase(Phase.EARLY).setApplyIf(() -> AngelicaConfig.enableSodium).addMixinClasses(
"sodium.MixinChunkProviderClient"
"sodium.MixinChunkProviderClient"
,"sodium.MixinBlock"
,"sodium.AccessorBiomeColorEvent"
,"sodium.MixinBiomeGenBase"
@@ -113,6 +113,7 @@ public enum Mixins {
,"sodium.MixinTileEntityRendererDispatcher"
,"sodium.MixinLongHashMap"
,"sodium.MixinRender"
,"sodium.MixinRenderingRegistry"
)
),
@@ -0,0 +1,32 @@
package com.gtnewhorizons.angelica.mixins.early.sodium;
import com.gtnewhorizons.angelica.interfaces.IThreadSafeISBRH;
import com.gtnewhorizons.angelica.mixins.interfaces.IRenderingRegistryExt;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import cpw.mods.fml.client.registry.RenderingRegistry;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import java.util.Map;
@Mixin(value = RenderingRegistry.class, remap = false)
public class MixinRenderingRegistry implements IRenderingRegistryExt {
@Shadow private Map<Integer, ISimpleBlockRenderingHandler> blockRenderers;
@Override
public ISimpleBlockRenderingHandler getISBRH(int modelId) {
return this.blockRenderers.get(modelId);
}
@WrapOperation(method = { "renderWorldBlock", "renderInventoryBlock", "renderItemAsFull3DBlock" }, at = @At(value="INVOKE", target="Ljava/util/Map;get(Ljava/lang/Object;)Ljava/lang/Object;"))
private Object getWrapped(Map<Integer, ISimpleBlockRenderingHandler> instance, Object modelId, Operation<ISimpleBlockRenderingHandler> original) {
final ISimpleBlockRenderingHandler res = original.call(instance, modelId);
if(res instanceof IThreadSafeISBRH isbhr) {
return isbhr.getThreadLocal();
}
return res;
}
}
@@ -0,0 +1,7 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
public interface IRenderingRegistryExt {
ISimpleBlockRenderingHandler getISBRH(int modelId);
}
@@ -1,5 +1,10 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizons.angelica.interfaces.IThreadSafeISBRH;
import com.gtnewhorizons.angelica.mixins.interfaces.IRenderingRegistryExt;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.versioning.ComparableVersion;
import it.unimi.dsi.fastutil.objects.Reference2BooleanMap;
import it.unimi.dsi.fastutil.objects.Reference2BooleanOpenHashMap;
import net.minecraft.block.Block;
@@ -7,41 +12,45 @@ import net.minecraft.block.Block;
import java.util.concurrent.locks.StampedLock;
public class AngelicaBlockSafetyRegistry {
private static final Reference2BooleanMap<Block> SAFETY_MAP = new Reference2BooleanOpenHashMap<>();
private static final Reference2BooleanMap<Block> BLOCK_SAFETY_MAP = new Reference2BooleanOpenHashMap<>();
private static final Reference2BooleanMap<Block> ISBRH_SAFETY_MAP = new Reference2BooleanOpenHashMap<>();
private static final StampedLock LOCK = new StampedLock();
public static boolean canBlockRenderOffThread(Block block) {
public static boolean canBlockRenderOffThread(Block block, boolean checkISBRH) {
final long stamp = LOCK.readLock();
final Reference2BooleanMap<Block> map = checkISBRH ? ISBRH_SAFETY_MAP : BLOCK_SAFETY_MAP;
boolean isOffThread, shouldPopulate;
try {
isOffThread = SAFETY_MAP.getBoolean(block);
isOffThread = map.getBoolean(block);
if (isOffThread) {
return true; // no need to check if 'false' was due to not being populated
}
shouldPopulate = !SAFETY_MAP.containsKey(block);
shouldPopulate = !map.containsKey(block);
} finally {
LOCK.unlock(stamp);
}
if(shouldPopulate) {
isOffThread = populateCanRenderOffThread(block);
isOffThread = populateCanRenderOffThread(block, map);
}
return isOffThread;
}
private static boolean populateCanRenderOffThread(Block block) {
final boolean canBeOffThread = !(block.getClass().getName().startsWith("gregtech."));
private static boolean populateCanRenderOffThread(Block block, Reference2BooleanMap<Block> map) {
@SuppressWarnings("deprecation")
final boolean canBeOffThread = map == ISBRH_SAFETY_MAP ? ((IRenderingRegistryExt)RenderingRegistry.instance()).getISBRH(block.getRenderType()) instanceof IThreadSafeISBRH : !(block.getClass().getName().startsWith("gregtech."));
final long stamp = LOCK.writeLock();
try {
SAFETY_MAP.put(block, canBeOffThread);
map.put(block, canBeOffThread);
} finally {
LOCK.unlock(stamp);
}
return canBeOffThread;
}
}
@@ -6,6 +6,7 @@ import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.mixins.interfaces.ITexturesCache;
import com.gtnewhorizons.angelica.rendering.AngelicaBlockSafetyRegistry;
import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue;
import it.unimi.dsi.fastutil.longs.LongArrayFIFOQueue;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import me.jellysquid.mods.sodium.client.render.chunk.ChunkGraphicsState;
import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderContainer;
@@ -89,7 +90,7 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
private boolean rendersOffThread(Block block) {
final int type = block.getRenderType();
return type < 42 && type != 22 && AngelicaBlockSafetyRegistry.canBlockRenderOffThread(block);
return (type < 42 && type != 22 && AngelicaBlockSafetyRegistry.canBlockRenderOffThread(block, false)) || AngelicaBlockSafetyRegistry.canBlockRenderOffThread(block, true);
}
private void handleRenderBlocksTextures(RenderBlocks rb, ChunkRenderData.Builder builder) {
@@ -104,7 +105,6 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
@Override
public ChunkBuildResult<T> performBuild(ChunkRenderCacheLocal cache, ChunkBuildBuffers buffers, CancellationSource cancellationSource) {
// COMPATIBLITY NOTE: Oculus relies on the LVT of this method being unchanged, at least in 16.5
final ChunkRenderData.Builder renderData = new ChunkRenderData.Builder();
final ChunkOcclusionDataBuilder occluder = new ChunkOcclusionDataBuilder();
final ChunkRenderBounds.Builder bounds = new ChunkRenderBounds.Builder();
@@ -120,9 +120,10 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
final int baseY = this.render.getOriginY();
final int baseZ = this.render.getOriginZ();
final BlockPos.Mutable pos = new BlockPos.Mutable();
final BlockPos pos = new BlockPos();
final BlockPos renderOffset = this.offset;
final LongArrayFIFOQueue mainThreadBlocks = new LongArrayFIFOQueue();
boolean hasMainThreadBlocks = false;
for (int relY = 0; relY < 16; relY++) {
@@ -160,6 +161,7 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
}
}
} else {
mainThreadBlocks.enqueue(pos.asLong());
hasMainThreadBlocks = true;
}
@@ -200,7 +202,7 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
if(hasMainThreadBlocks) {
// Render the other blocks on the main thread
try {
CompletableFuture.runAsync(() -> this.performMainBuild(cache, buffers, cancellationSource, bounds, renderData), AngelicaRenderQueue.executor()).get();
CompletableFuture.runAsync(() -> this.performMainBuild(cache, buffers, cancellationSource, bounds, renderData, mainThreadBlocks), AngelicaRenderQueue.executor()).get();
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
return null;
@@ -230,54 +232,51 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
/**
* Render the blocks that should be rendered on the main thread.
*
* TODO: Deduplicate this with the main method above.
*/
private void performMainBuild(ChunkRenderCacheLocal cache, ChunkBuildBuffers buffers, CancellationSource cancellationSource, ChunkRenderBounds.Builder bounds, ChunkRenderData.Builder renderData) {
private void performMainBuild(ChunkRenderCacheLocal cache, ChunkBuildBuffers buffers, CancellationSource cancellationSource, ChunkRenderBounds.Builder bounds, ChunkRenderData.Builder renderData, LongArrayFIFOQueue mainThreadBlocks) {
final WorldSlice slice = cache.getWorldSlice();
final BlockPos.Mutable pos = new BlockPos.Mutable();
final BlockPos pos = new BlockPos();
final int baseX = this.render.getOriginX();
final int baseY = this.render.getOriginY();
final int baseZ = this.render.getOriginZ();
final BlockPos renderOffset = this.offset;
final RenderBlocks rb = new RenderBlocks(slice.getWorld());
for (int relY = 0; relY < 16; relY++) {
while(!mainThreadBlocks.isEmpty()) {
final long longPos = mainThreadBlocks.dequeueLong();
if (cancellationSource.isCancelled()) {
return;
}
for (int relZ = 0; relZ < 16; relZ++) {
for (int relX = 0; relX < 16; relX++) {
final Block block = slice.getBlockRelative(relX + 16, relY + 16, relZ + 16);
pos.set(longPos);
final int relX = pos.getX() - baseX;
final int relY = pos.getY() - baseY;
final int relZ = pos.getZ() - baseZ;
final Block block = slice.getBlockRelative(relX + 16, relY + 16, relZ + 16);
// Only render blocks that need main thread assistance
if (block.getMaterial() == Material.air || rendersOffThread(block)) {
continue;
// Only render blocks that need main thread assistance
if (block.getMaterial() == Material.air || rendersOffThread(block)) {
continue;
}
// TODO: Collect data on which render types are hitting this code path most often so mods can be updated slowly
final int meta = slice.getBlockMetadataRelative(relX + 16, relY + 16, relZ + 16);
buffers.setRenderOffset(pos.x - renderOffset.getX(), pos.y - renderOffset.getY(), pos.z - renderOffset.getZ());
if(AngelicaConfig.enableIris) buffers.iris$setLocalPos(relX, relY, relZ);
// Do regular block rendering
for (BlockRenderPass pass : BlockRenderPass.VALUES) {
if (block.canRenderInPass(pass.ordinal()) && (!AngelicaConfig.enableSodiumFluidRendering || !(block instanceof IFluidBlock))) {
final long seed = MathUtil.hashPos(pos.x, pos.y, pos.z);
if(AngelicaConfig.enableIris) buffers.iris$setMaterialId(block, ExtendedDataHelper.BLOCK_RENDER_TYPE);
if (cache.getBlockRenderer().renderModel(slice.getWorld(), rb, block, meta, pos, buffers.get(pass), true, seed)) {
bounds.addBlock(relX, relY, relZ);
}
// TODO: Collect data on which render types are hitting this code path most often
// so mods can be updated slowly
final int meta = slice.getBlockMetadataRelative(relX + 16, relY + 16, relZ + 16);
pos.set(baseX + relX, baseY + relY, baseZ + relZ);
buffers.setRenderOffset(pos.x - renderOffset.getX(), pos.y - renderOffset.getY(), pos.z - renderOffset.getZ());
if(AngelicaConfig.enableIris) buffers.iris$setLocalPos(relX, relY, relZ);
// Do regular block rendering
for (BlockRenderPass pass : BlockRenderPass.VALUES) {
if (block.canRenderInPass(pass.ordinal()) && (!AngelicaConfig.enableSodiumFluidRendering || !(block instanceof IFluidBlock))) {
final long seed = MathUtil.hashPos(pos.x, pos.y, pos.z);
if(AngelicaConfig.enableIris) buffers.iris$setMaterialId(block, ExtendedDataHelper.BLOCK_RENDER_TYPE);
if (cache.getBlockRenderer().renderModel(slice.getWorld(), rb, block, meta, pos, buffers.get(pass), true, seed)) {
bounds.addBlock(relX, relY, relZ);
}
}
}
if(AngelicaConfig.enableIris) buffers.iris$resetBlockContext();
}
}
if(AngelicaConfig.enableIris) buffers.iris$resetBlockContext();
}
handleRenderBlocksTextures(rb, renderData);
@@ -95,6 +95,7 @@ public class FluidRenderer {
int posZ = pos.z;
Fluid fluid = ((IFluidBlock) block).getFluid();
if(fluid == null) return false;
// Check for occluded sides; if everything is occluded, don't render
boolean sfUp = this.isFluidOccluded(world, posX, posY, posZ, ForgeDirection.UP, fluid);
@@ -88,6 +88,8 @@ public class WorldSlice implements IBlockAccess {
@Getter
private ChunkSectionPos origin;
StructureBoundingBox volume;
public static ChunkRenderContext prepare(World world, ChunkSectionPos origin, ClonedChunkSectionCache sectionCache) {
final Chunk chunk = world.getChunkFromChunkCoords(origin.x, origin.z);
final ExtendedBlockStorage section = chunk.getBlockStorageArray()[origin.y];
@@ -156,6 +158,7 @@ public class WorldSlice implements IBlockAccess {
public void copyData(ChunkRenderContext context) {
this.origin = context.getOrigin();
this.sections = context.getSections();
this.volume = context.getVolume();
this.baseX = (this.origin.x - NEIGHBOR_CHUNK_RADIUS) << 4;
this.baseY = (this.origin.y - NEIGHBOR_CHUNK_RADIUS) << 4;
@@ -167,7 +170,7 @@ public class WorldSlice implements IBlockAccess {
for (int z = 0; z < SECTION_LENGTH; z++) {
final int idx = getLocalSectionIndex(x, y, z);
ClonedChunkSection section = this.sections[idx];
final ClonedChunkSection section = this.sections[idx];
this.unpackBlockData(this.blockArrays[idx], this.metadataArrays[idx], section, context.getVolume());
this.biomeData[idx] = section.getBiomeData();
@@ -227,11 +230,15 @@ public class WorldSlice implements IBlockAccess {
@Override
public BiomeGenBase getBiomeGenForCoords(int x, int z) {
if (!blockBoxContains(this.volume, x, volume.minY, z)) {
return BiomeGenBase.plains;
}
final int relX = x - this.baseX;
final int relY = 0;
final int relZ = z - this.baseZ;
BiomeGenBase biome = this.biomeData[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)]
final BiomeGenBase biome = this.biomeData[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)]
[(x & 15) | (z & 15) << 4];
// can be null if biome wasn't generated yet
return biome == null ? BiomeGenBase.plains : biome;
@@ -274,7 +281,7 @@ public class WorldSlice implements IBlockAccess {
}
private void unpackBlockDataR(Block[] blocks, int metas[], ClonedChunkSection section, StructureBoundingBox box) {
ChunkSectionPos pos = section.getPosition();
final ChunkSectionPos pos = section.getPosition();
final int minBlockX = Math.max(box.minX, pos.getMinX());
final int maxBlockX = Math.min(box.maxX, pos.getMaxX());
@@ -306,6 +313,10 @@ public class WorldSlice implements IBlockAccess {
}
public Block getBlock(int x, int y, int z) {
if (!blockBoxContains(this.volume, x, y, z)) {
return Blocks.air;
}
final int relX = x - this.baseX;
final int relY = y - this.baseY;
final int relZ = z - this.baseZ;
@@ -322,6 +333,9 @@ public class WorldSlice implements IBlockAccess {
@Override
public int getBlockMetadata(int x, int y, int z) {
if (!blockBoxContains(this.volume, x, y, z)) {
return 0;
}
final int relX = x - this.baseX;
final int relY = y - this.baseY;
final int relZ = z - this.baseZ;
@@ -331,22 +345,27 @@ public class WorldSlice implements IBlockAccess {
@Override
public TileEntity getTileEntity(int x, int y, int z) {
int relX = x - this.baseX;
int relY = y - this.baseY;
int relZ = z - this.baseZ;
if (!blockBoxContains(this.volume, x, y, z)) {
return null;
}
final int relX = x - this.baseX;
final int relY = y - this.baseY;
final int relZ = z - this.baseZ;
return this.sections[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)].getBlockEntity(relX & 15, relY & 15, relZ & 15);
}
public int getLightLevel(EnumSkyBlock type, int x, int y, int z) {
if (!blockBoxContains(this.volume, x, y, z)) {
return 0;
}
y = MathHelper.clamp_int(y, 0, 255);
int relX = x - this.baseX;
int relY = y - this.baseY;
int relZ = z - this.baseZ;
NibbleArray lightArray = this.lightArrays[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)][type.ordinal()];
final int relX = x - this.baseX;
final int relY = y - this.baseY;
final int relZ = z - this.baseZ;
final NibbleArray lightArray = this.lightArrays[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)][type.ordinal()];
if (lightArray == null) {
// If the array is null, it means the dimension for the current world does not support that light type
return this.defaultLightValues[type.ordinal()];
@@ -385,4 +404,12 @@ public class WorldSlice implements IBlockAccess {
public World getWorld() {
return this.world;
}
private static boolean blockBoxContains(StructureBoundingBox box, int x, int y, int z) {
return x >= box.minX &&
x <= box.maxX &&
y >= box.minY &&
y <= box.maxY &&
z >= box.minZ &&
z <= box.maxZ;
}
}