]> git.lizzy.rs Git - LightOverlay.git/blob - common/src/main/java/me/shedaniel/lightoverlay/common/LightOverlayTicker.java
f9710156c3d90c553af23f8c33fafacb4a7981e3
[LightOverlay.git] / common / src / main / java / me / shedaniel / lightoverlay / common / LightOverlayTicker.java
1 package me.shedaniel.lightoverlay.common;
2
3 import com.google.common.base.Suppliers;
4 import com.google.common.collect.Maps;
5 import dev.architectury.injectables.annotations.ExpectPlatform;
6 import it.unimi.dsi.fastutil.longs.Long2ByteMap;
7 import it.unimi.dsi.fastutil.longs.Long2ByteOpenHashMap;
8 import net.minecraft.client.Minecraft;
9 import net.minecraft.client.multiplayer.ClientLevel;
10 import net.minecraft.client.player.LocalPlayer;
11 import net.minecraft.core.BlockPos;
12 import net.minecraft.core.Direction;
13 import net.minecraft.core.Holder;
14 import net.minecraft.tags.BlockTags;
15 import net.minecraft.util.Mth;
16 import net.minecraft.world.entity.Entity;
17 import net.minecraft.world.entity.EntityType;
18 import net.minecraft.world.level.BlockGetter;
19 import net.minecraft.world.level.Level;
20 import net.minecraft.world.level.LightLayer;
21 import net.minecraft.world.level.biome.Biome;
22 import net.minecraft.world.level.block.Block;
23 import net.minecraft.world.level.block.state.BlockState;
24 import net.minecraft.world.level.chunk.ChunkStatus;
25 import net.minecraft.world.level.chunk.LevelChunk;
26 import net.minecraft.world.level.lighting.LayerLightEventListener;
27 import net.minecraft.world.phys.shapes.CollisionContext;
28 import net.minecraft.world.phys.shapes.VoxelShape;
29 import org.apache.logging.log4j.LogManager;
30 import sun.misc.Unsafe;
31
32 import java.lang.reflect.Field;
33 import java.util.*;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.ThreadPoolExecutor;
36 import java.util.function.Supplier;
37
38 public class LightOverlayTicker {
39     private final Minecraft minecraft = Minecraft.getInstance();
40     private long ticks = 0;
41     private static int threadNumber = 0;
42     private static final ThreadPoolExecutor EXECUTOR = (ThreadPoolExecutor) Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), r -> {
43         Thread thread = new Thread(r, "light-overlay-" + threadNumber++);
44         thread.setDaemon(true);
45         return thread;
46     });
47     public final Set<CubicChunkPos> POS = Collections.synchronizedSet(new HashSet<>());
48     public final Set<CubicChunkPos> CALCULATING_POS = Collections.synchronizedSet(new HashSet<>());
49     public final Map<CubicChunkPos, Long2ByteMap> CHUNK_MAP = Maps.newConcurrentMap();
50     private static final Supplier<EntityType<Entity>> TESTING_ENTITY_TYPE = Suppliers.memoize(() -> {
51         // get unsafe
52         try {
53             Field f = Unsafe.class.getDeclaredField("theUnsafe");
54             f.setAccessible(true);
55             Unsafe unsafe = (Unsafe) f.get(null);
56             
57             // instantiate entity type
58             EntityType<Entity> type = (EntityType<Entity>) unsafe.allocateInstance(EntityType.class);
59             return type;
60         } catch (Exception e) {
61             throw new RuntimeException(e);
62         }
63     });
64     
65     @ExpectPlatform
66     public static void populateEntityType(EntityType<Entity> type) {
67         throw new AssertionError();
68     }
69     
70     public void queueChunk(CubicChunkPos pos) {
71         if (LightOverlay.enabled && LightOverlay.caching && !CALCULATING_POS.contains(pos)) {
72             POS.add(pos);
73         }
74     }
75     
76     public void tick(Minecraft minecraft) {
77         while (LightOverlay.enableOverlay.consumeClick())
78             LightOverlay.enabled = !LightOverlay.enabled;
79         
80         try {
81             ticks++;
82             if (minecraft.player == null || !LightOverlay.enabled) {
83                 POS.clear();
84                 CALCULATING_POS.clear();
85                 EXECUTOR.getQueue().clear();
86                 CHUNK_MAP.clear();
87             } else {
88                 LocalPlayer player = minecraft.player;
89                 ClientLevel world = minecraft.level;
90                 CollisionContext collisionContext = CollisionContext.of(player);
91                 
92                 if (!LightOverlay.caching) {
93                     CALCULATING_POS.clear();
94                     POS.clear();
95                     CHUNK_MAP.clear();
96                     BlockPos playerPos = player.blockPosition();
97                     LayerLightEventListener block = world.getLightEngine().getLayerListener(LightLayer.BLOCK);
98                     LayerLightEventListener sky = LightOverlay.showNumber ? null : world.getLightEngine().getLayerListener(LightLayer.SKY);
99                     BlockPos.MutableBlockPos downPos = new BlockPos.MutableBlockPos();
100                     Iterable<BlockPos> iterate = BlockPos.betweenClosed(playerPos.getX() - LightOverlay.reach, playerPos.getY() - LightOverlay.reach, playerPos.getZ() - LightOverlay.reach,
101                             playerPos.getX() + LightOverlay.reach, playerPos.getY() + LightOverlay.reach, playerPos.getZ() + LightOverlay.reach);
102                     Long2ByteMap chunkData = new Long2ByteOpenHashMap();
103                     CHUNK_MAP.put(new CubicChunkPos(0, 0, 0), chunkData);
104                     for (BlockPos blockPos : iterate) {
105                         downPos.set(blockPos.getX(), blockPos.getY() - 1, blockPos.getZ());
106                         if (LightOverlay.showNumber) {
107                             int level = getCrossLevel(blockPos, downPos, world, block, collisionContext);
108                             if (level >= 0) {
109                                 chunkData.put(blockPos.asLong(), (byte) level);
110                             }
111                         } else {
112                             Holder<Biome> biome = !LightOverlay.mushroom ? world.getBiome(blockPos) : null;
113                             byte type = getCrossType(blockPos, biome, downPos, world, block, sky, collisionContext);
114                             if (type != LightOverlay.CROSS_NONE) {
115                                 chunkData.put(blockPos.asLong(), type);
116                             }
117                         }
118                     }
119                 } else {
120                     var height = Mth.ceil(Minecraft.getInstance().level.getHeight() / 32.0);
121                     var start = Math.floorDiv(Minecraft.getInstance().level.getMinBuildHeight(), 32);
122                     int playerPosX = ((int) player.getX()) >> 4;
123                     int playerPosY = ((int) player.getY()) >> 5;
124                     int playerPosZ = ((int) player.getZ()) >> 4;
125                     var chunkRange = LightOverlay.getChunkRange();
126                     for (int chunkX = playerPosX - chunkRange; chunkX <= playerPosX + chunkRange; chunkX++) {
127                         for (int chunkY = Math.max(playerPosY - Math.max(1, chunkRange >> 1), start); chunkY <= playerPosY + Math.max(1, chunkRange >> 1) && chunkY <= start + height; chunkY++) {
128                             for (int chunkZ = playerPosZ - chunkRange; chunkZ <= playerPosZ + chunkRange; chunkZ++) {
129                                 if (Mth.abs(chunkX - playerPosX) > chunkRange || Mth.abs(chunkY - playerPosY) > chunkRange || Mth.abs(chunkZ - playerPosZ) > chunkRange)
130                                     continue;
131                                 CubicChunkPos chunkPos = new CubicChunkPos(chunkX, chunkY, chunkZ);
132                                 if (!CHUNK_MAP.containsKey(chunkPos))
133                                     queueChunk(chunkPos);
134                             }
135                         }
136                     }
137                     for (int p = 0; p < 3; p++) {
138                         if (EXECUTOR.getQueue().size() >= Runtime.getRuntime().availableProcessors()) break;
139                         double d1 = Double.MAX_VALUE, d2 = Double.MAX_VALUE, d3 = Double.MAX_VALUE;
140                         CubicChunkPos c1 = null, c2 = null, c3 = null;
141                         synchronized (POS) {
142                             Iterator<CubicChunkPos> iterator = POS.iterator();
143                             while (iterator.hasNext()) {
144                                 CubicChunkPos pos = iterator.next();
145                                 if (Mth.abs(pos.x - playerPosX) > chunkRange || Mth.abs(pos.y - playerPosY) > Math.max(1, chunkRange >> 1) || Mth.abs(pos.z - playerPosZ) > chunkRange || CALCULATING_POS.contains(pos)) {
146                                     iterator.remove();
147                                 } else {
148                                     if (LightOverlay.renderer.isFrustumVisible(pos.getMinBlockX(), pos.getMinBlockY(), pos.getMinBlockZ(), pos.getMaxBlockX(), pos.getMaxBlockY(), pos.getMaxBlockZ())) {
149                                         int dx = Math.abs(pos.x - playerPosX);
150                                         int dy = Math.abs(pos.y - playerPosY) << 1;
151                                         int dz = Math.abs(pos.z - playerPosZ);
152                                         double distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
153                                         if (distance < d1) {
154                                             d3 = d2;
155                                             d2 = d1;
156                                             d1 = distance;
157                                             c3 = c2;
158                                             c2 = c1;
159                                             c1 = pos;
160                                         } else if (distance < d2) {
161                                             d3 = d2;
162                                             d2 = distance;
163                                             c3 = c2;
164                                             c2 = pos;
165                                         } else if (distance < d3) {
166                                             d3 = distance;
167                                             c3 = pos;
168                                         }
169                                     }
170                                 }
171                             }
172                         }
173                         CubicChunkPos finalC1 = c1;
174                         CubicChunkPos finalC2 = c2;
175                         CubicChunkPos finalC3 = c3;
176                         if (finalC1 != null) {
177                             CALCULATING_POS.add(finalC1);
178                             POS.remove(finalC1);
179                             if (finalC2 != null) {
180                                 CALCULATING_POS.add(finalC2);
181                                 POS.remove(finalC2);
182                                 if (finalC3 != null) {
183                                     CALCULATING_POS.add(finalC3);
184                                     POS.remove(finalC3);
185                                 }
186                             }
187                             EXECUTOR.submit(() -> {
188                                 int playerPosX1 = ((int) minecraft.player.getX()) >> 4;
189                                 int playerPosY1 = ((int) minecraft.player.getY()) >> 5;
190                                 int playerPosZ1 = ((int) minecraft.player.getZ()) >> 4;
191                                 if (finalC1 != null) processChunk(finalC1, playerPosX1, playerPosY1, playerPosZ1, collisionContext);
192                                 if (finalC2 != null) processChunk(finalC2, playerPosX1, playerPosY1, playerPosZ1, collisionContext);
193                                 if (finalC3 != null) processChunk(finalC3, playerPosX1, playerPosY1, playerPosZ1, collisionContext);
194                             });
195                         }
196                     }
197                     if (ticks % 50 == 0) {
198                         CHUNK_MAP.entrySet().removeIf(entry -> Mth.abs(entry.getKey().x - playerPosX) > chunkRange * 2 || Mth.abs(entry.getKey().y - playerPosY) > chunkRange * 2 || Mth.abs(entry.getKey().z - playerPosZ) > chunkRange * 2);
199                     }
200                 }
201             }
202         } catch (Throwable throwable) {
203             LogManager.getLogger().throwing(throwable);
204         }
205     }
206     
207     private void processChunk(CubicChunkPos pos, int playerPosX, int playerPosY, int playerPosZ, CollisionContext context) {
208         CALCULATING_POS.remove(pos);
209         int chunkRange = LightOverlay.getChunkRange();
210         if (Mth.abs(pos.x - playerPosX) > chunkRange || Mth.abs(pos.y - playerPosY) > Math.max(1, chunkRange >> 1) || Mth.abs(pos.z - playerPosZ) > chunkRange || POS.contains(pos)) {
211             return;
212         }
213         try {
214             calculateChunk(minecraft.level.getChunkSource().getChunk(pos.x, pos.z, ChunkStatus.FULL, false), minecraft.level, pos, context);
215         } catch (Throwable throwable) {
216             LogManager.getLogger().throwing(throwable);
217         }
218     }
219     
220     private void calculateChunk(LevelChunk chunk, Level world, CubicChunkPos chunkPos, CollisionContext collisionContext) {
221         if (world != null && chunk != null) {
222             Long2ByteMap chunkData = new Long2ByteOpenHashMap();
223             LayerLightEventListener block = world.getLightEngine().getLayerListener(LightLayer.BLOCK);
224             LayerLightEventListener sky = LightOverlay.showNumber ? null : world.getLightEngine().getLayerListener(LightLayer.SKY);
225             for (BlockPos pos : BlockPos.betweenClosed(chunkPos.getMinBlockX(), chunkPos.getMinBlockY(), chunkPos.getMinBlockZ(), chunkPos.getMaxBlockX(), chunkPos.getMaxBlockY(), chunkPos.getMaxBlockZ())) {
226                 BlockPos down = pos.below();
227                 if (LightOverlay.showNumber) {
228                     int level = getCrossLevel(pos, down, chunk, block, collisionContext);
229                     if (level >= 0) {
230                         chunkData.put(pos.asLong(), (byte) level);
231                     }
232                 } else {
233                     Holder<Biome> biome = !LightOverlay.mushroom ? world.getBiome(pos) : null;
234                     byte type = getCrossType(pos, biome, down, chunk, block, sky, collisionContext);
235                     if (type != LightOverlay.CROSS_NONE) {
236                         chunkData.put(pos.asLong(), type);
237                     }
238                 }
239             }
240             CHUNK_MAP.put(chunkPos, chunkData);
241         } else {
242             CHUNK_MAP.remove(chunkPos);
243         }
244     }
245     
246     public byte getCrossType(BlockPos pos, Holder<Biome> biome, BlockPos down, BlockGetter world, LayerLightEventListener block, LayerLightEventListener sky, CollisionContext entityContext) {
247         BlockState blockBelowState = world.getBlockState(down);
248         BlockState blockUpperState = world.getBlockState(pos);
249         VoxelShape upperCollisionShape = blockUpperState.getCollisionShape(world, pos, entityContext);
250         if (!LightOverlay.underwater && !blockUpperState.getFluidState().isEmpty())
251             return LightOverlay.CROSS_NONE;
252         // Check if the outline is full
253         if (Block.isFaceFull(upperCollisionShape, Direction.UP))
254             return LightOverlay.CROSS_NONE;
255         // TODO: Not to hard code no redstone
256         if (blockUpperState.isSignalSource())
257             return LightOverlay.CROSS_NONE;
258         // Check if the collision has a bump
259         if (upperCollisionShape.max(Direction.Axis.Y) > 0)
260             return LightOverlay.CROSS_NONE;
261         if (blockUpperState.is(BlockTags.RAILS))
262             return LightOverlay.CROSS_NONE;
263         // Check block state allow spawning (excludes bedrock and barriers automatically)
264         if (!blockBelowState.isValidSpawn(world, down, TESTING_ENTITY_TYPE.get()))
265             return LightOverlay.CROSS_NONE;
266         if (!LightOverlay.mushroom && Biome.BiomeCategory.MUSHROOM == Biome.getBiomeCategory(biome))
267             return LightOverlay.CROSS_NONE;
268         int blockLightLevel = block.getLightValue(pos);
269         int skyLightLevel = sky.getLightValue(pos);
270         if (blockLightLevel > LightOverlay.higherCrossLevel)
271             return LightOverlay.CROSS_NONE;
272         if (skyLightLevel > LightOverlay.higherCrossLevel)
273             return LightOverlay.higherCross;
274         return LightOverlay.lowerCrossLevel >= 0 && blockLightLevel > LightOverlay.lowerCrossLevel ?
275                 LightOverlay.lowerCross : LightOverlay.CROSS_RED;
276     }
277     
278     public static int getCrossLevel(BlockPos pos, BlockPos down, BlockGetter world, LayerLightEventListener view, CollisionContext collisionContext) {
279         BlockState blockBelowState = world.getBlockState(down);
280         BlockState blockUpperState = world.getBlockState(pos);
281         VoxelShape collisionShape = blockBelowState.getCollisionShape(world, down, collisionContext);
282         VoxelShape upperCollisionShape = blockUpperState.getCollisionShape(world, pos, collisionContext);
283         if (!LightOverlay.underwater && !blockUpperState.getFluidState().isEmpty())
284             return -1;
285         if (!blockBelowState.getFluidState().isEmpty())
286             return -1;
287         if (blockBelowState.isAir())
288             return -1;
289         if (Block.isFaceFull(upperCollisionShape, Direction.DOWN))
290             return -1;
291         return view.getLightValue(pos);
292     }
293 }