package codechicken.lib.world;

import net.minecraft.world.chunk.ChunkPrimerWrapper;
import net.minecraft.world.chunk.IChunk;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.ChunkEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;

public class TileChunkLoadHook {

    private static boolean init;

    public static void init() {
        if (init) {
            return;
        }
        init = true;

        MinecraftForge.EVENT_BUS.register(new TileChunkLoadHook());
    }

    @SubscribeEvent
    public void onChunkLoad(ChunkEvent.Load event) {
        IChunk chunk = event.getChunk();
        if(chunk instanceof ChunkPrimerWrapper) {
            chunk = ((ChunkPrimerWrapper) chunk).func_217336_u();
        }
        chunk.getTileEntitiesPos().stream()//
                .map(chunk::getTileEntity)//
                .filter(e -> e instanceof IChunkLoadTile)//
                .map(e -> (IChunkLoadTile) e)//
                .forEach(IChunkLoadTile::onChunkLoad);
    }
}

@@ -25,16 +25,187 @@
 world;%0A%0A
+import net.minecraft.tileentity.TileEntity;%0Aimport net.minecraft.util.math.BlockPos;%0Aimport net.minecraft.world.chunk.Chunk;%0Aimport net.minecraft.world.chunk.ChunkPrimer;%0A
 import n
@@ -445,16 +445,39 @@
 Event;%0A%0A
+import java.util.Map;%0A%0A
 public c
@@ -825,24 +825,72 @@
 getChunk();%0A
+        Map%3CBlockPos, TileEntity%3E tiles = null;%0A
         if(c
@@ -887,16 +887,17 @@
       if
+ 
 (chunk i
@@ -1016,74 +1016,190 @@
     
+if (
 chunk
-.getTileEntitiesPos().stream()//%0A                .map(
+ instanceof Chunk) %7B%0A            tiles = ((Chunk) chunk).getTileEntityMap();%0A        %7D%0A        if (chunk instanceof ChunkPrimer) %7B%0A            tiles = ((ChunkPrimer) 
 chunk
-::
+).
 getT
@@ -1210,12 +1210,14 @@
 ntit
-y)//
+ies();
 %0A   
@@ -1221,24 +1221,26 @@
         
+%7D%0A
         
 .filter(
@@ -1235,79 +1235,118 @@
     
-.filter(e -%3E e instanceof IChunkLoadTile)//%0A                .map(e -%3E (
+if (tiles != null) %7B%0A            for (TileEntity tile : tiles.values()) %7B%0A                if (tile instanceof 
 IChu
@@ -1361,12 +1361,9 @@
 le) 
-e)//
+%7B
 %0A   
@@ -1379,16 +1379,13 @@
     
-.forEach
+    (
 (ICh
@@ -1399,10 +1399,16 @@
 Tile
-::
+) tile).
 onCh
@@ -1414,19 +1414,62 @@
 hunkLoad
+(
 );%0A
+                %7D%0A            %7D%0A        %7D%0A
     %7D%0A%7D%0A

Fix chunk load hook causing chunk loading deadlocks.