1 package me.shedaniel.lightoverlay.fabric;
3 import com.google.common.collect.Lists;
4 import com.google.common.collect.Maps;
5 import com.mojang.blaze3d.platform.GlStateManager;
6 import com.mojang.blaze3d.systems.RenderSystem;
7 import it.unimi.dsi.fastutil.longs.Long2ReferenceMap;
8 import it.unimi.dsi.fastutil.longs.Long2ReferenceOpenHashMap;
9 import me.shedaniel.cloth.api.client.events.v0.ClothClientHooks;
10 import net.fabricmc.api.ClientModInitializer;
11 import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
12 import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
13 import net.fabricmc.loader.api.FabricLoader;
14 import net.minecraft.block.Block;
15 import net.minecraft.block.BlockState;
16 import net.minecraft.client.MinecraftClient;
17 import net.minecraft.client.font.TextRenderer;
18 import net.minecraft.client.network.ClientPlayerEntity;
19 import net.minecraft.client.options.KeyBinding;
20 import net.minecraft.client.render.Camera;
21 import net.minecraft.client.render.Frustum;
22 import net.minecraft.client.render.Tessellator;
23 import net.minecraft.client.render.VertexConsumerProvider;
24 import net.minecraft.client.util.InputUtil;
25 import net.minecraft.client.util.math.Rotation3;
26 import net.minecraft.client.world.ClientWorld;
27 import net.minecraft.entity.Entity;
28 import net.minecraft.entity.EntityCategory;
29 import net.minecraft.entity.EntityContext;
30 import net.minecraft.entity.EntityType;
31 import net.minecraft.entity.player.PlayerEntity;
32 import net.minecraft.tag.BlockTags;
33 import net.minecraft.util.Identifier;
34 import net.minecraft.util.math.*;
35 import net.minecraft.util.shape.VoxelShape;
36 import net.minecraft.world.BlockView;
37 import net.minecraft.world.LightType;
38 import net.minecraft.world.World;
39 import net.minecraft.world.chunk.ChunkStatus;
40 import net.minecraft.world.chunk.WorldChunk;
41 import net.minecraft.world.chunk.light.ChunkLightingView;
42 import org.apache.logging.log4j.LogManager;
43 import org.lwjgl.opengl.GL11;
46 import java.io.FileInputStream;
47 import java.io.FileOutputStream;
48 import java.io.IOException;
49 import java.text.DecimalFormat;
50 import java.util.Comparator;
51 import java.util.List;
53 import java.util.Properties;
54 import java.util.concurrent.Executors;
55 import java.util.concurrent.ThreadPoolExecutor;
57 public class LightOverlay implements ClientModInitializer {
59 static final DecimalFormat FORMAT = new DecimalFormat("#.#");
60 private static final String KEYBIND_CATEGORY = "key.lightoverlay.category";
61 private static final Identifier ENABLE_OVERLAY_KEYBIND = new Identifier("lightoverlay", "enable_overlay");
62 static int reach = 12;
63 static int crossLevel = 7;
64 static int secondaryLevel = -1;
65 static int lowerCrossLevel = -1;
66 static int higherCrossLevel = -1;
67 static boolean caching = false;
68 static boolean showNumber = false;
69 static boolean smoothLines = true;
70 static boolean underwater = false;
71 static float lineWidth = 1.0F;
72 static int yellowColor = 0xFFFF00, redColor = 0xFF0000, secondaryColor = 0x0000FF;
73 static File configFile = new File(FabricLoader.getInstance().getConfigDir().toFile(), "lightoverlay.properties");
74 private static final KeyBinding ENABLE_OVERLAY = createKeyBinding(ENABLE_OVERLAY_KEYBIND, InputUtil.Type.KEYSYM, 296, KEYBIND_CATEGORY);
75 private static boolean enabled = false;
76 private static EntityType<Entity> testingEntityType;
77 private static int threadNumber = 0;
78 public static Frustum frustum;
79 private static final ThreadPoolExecutor EXECUTOR = (ThreadPoolExecutor) Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), r -> {
80 Thread thread = new Thread(r, "light-overlay-" + threadNumber++);
81 thread.setDaemon(true);
84 private static final List<ChunkPos> POS = Lists.newCopyOnWriteArrayList();
85 private static final Map<ChunkPos, Long2ReferenceMap<Object>> CHUNK_MAP = Maps.newConcurrentMap();
86 private static final MinecraftClient CLIENT = MinecraftClient.getInstance();
87 private static long ticks = 0;
90 ClientTickEvents.END_CLIENT_TICK.register(client -> {
93 if (CLIENT.player == null || !enabled) {
100 ClientPlayerEntity player = CLIENT.player;
101 ClientWorld world = CLIENT.world;
102 BlockPos playerPos = player.getSenseCenterPos();
103 EntityContext entityContext = EntityContext.of(player);
104 ChunkLightingView block = world.getLightingProvider().get(LightType.BLOCK);
105 ChunkLightingView sky = showNumber ? null : world.getLightingProvider().get(LightType.SKY);
106 BlockPos.Mutable downPos = new BlockPos.Mutable();
107 Iterable<BlockPos> iterate = BlockPos.iterate(playerPos.getX() - reach, playerPos.getY() - reach, playerPos.getZ() - reach,
108 playerPos.getX() + reach, playerPos.getY() + reach, playerPos.getZ() + reach);
109 Long2ReferenceMap<Object> map = new Long2ReferenceOpenHashMap<>();
110 CHUNK_MAP.put(new ChunkPos(0, 0), map);
111 for (BlockPos blockPos : iterate) {
112 downPos.set(blockPos.getX(), blockPos.getY() - 1, blockPos.getZ());
114 int level = getCrossLevel(blockPos, downPos, world, block, entityContext);
116 map.put(blockPos.asLong(), Integer.valueOf(level));
119 CrossType type = getCrossType(blockPos, downPos, world, block, sky, entityContext);
120 if (type != CrossType.NONE) {
121 map.put(blockPos.asLong(), type);
126 ClientPlayerEntity player = CLIENT.player;
127 ClientWorld world = CLIENT.world;
128 EntityContext entityContext = EntityContext.of(player);
129 Vec3d[] playerPos = {null};
130 int playerPosX = ((int) player.getX()) >> 4;
131 int playerPosZ = ((int) player.getZ()) >> 4;
132 if (ticks % 20 == 0) {
133 for (int chunkX = playerPosX - getChunkRange(); chunkX <= playerPosX + getChunkRange(); chunkX++) {
134 for (int chunkZ = playerPosZ - getChunkRange(); chunkZ <= playerPosZ + getChunkRange(); chunkZ++) {
135 ChunkPos chunkPos = new ChunkPos(chunkX, chunkZ);
136 if (!CHUNK_MAP.containsKey(chunkPos))
137 queueChunk(chunkPos);
141 POS.removeIf(pos -> MathHelper.abs(pos.x - playerPosX) > getChunkRange() || MathHelper.abs(pos.z - playerPosZ) > getChunkRange());
142 for (int k = 0; k < 2; k++) {
143 if (!POS.isEmpty()) {
144 if (playerPos[0] == null) {
145 playerPos[0] = player.getPos();
147 ChunkPos pos = POS.stream().min(Comparator.comparingDouble(value -> {
148 int i = Math.abs(value.x - playerPosX);
149 int j = Math.abs(value.z - playerPosZ);
150 return i * i + j * j;
153 EXECUTOR.submit(() -> {
155 calculateChunk(world.getChunkManager().getChunk(pos.x, pos.z, ChunkStatus.FULL, false), world, pos, entityContext);
156 } catch (Throwable throwable) {
157 LogManager.getLogger().throwing(throwable);
162 if (ticks % 50 == 0) {
163 CHUNK_MAP.entrySet().removeIf(pos -> MathHelper.abs(pos.getKey().x - playerPosX) > getChunkRange() * 2 || MathHelper.abs(pos.getKey().z - playerPosZ) > getChunkRange() * 2);
167 } catch (Throwable throwable) {
168 LogManager.getLogger().throwing(throwable);
173 public static void queueChunkAndNear(ChunkPos pos) {
174 for (int xOffset = -1; xOffset <= 1; xOffset++) {
175 for (int zOffset = -1; zOffset <= 1; zOffset++) {
176 queueChunk(new ChunkPos(pos.x + xOffset, pos.z + zOffset));
181 public static void queueChunk(ChunkPos pos) {
183 if (!POS.contains(pos))
187 public static int getChunkRange() {
188 return Math.max(MathHelper.ceil(reach / 16f), 1);
191 private static void calculateChunk(WorldChunk chunk, World world, ChunkPos chunkPos, EntityContext entityContext) {
192 if (world != null && chunk != null) {
193 Long2ReferenceMap<Object> map = new Long2ReferenceOpenHashMap<>();
194 ChunkLightingView block = world.getLightingProvider().get(LightType.BLOCK);
195 ChunkLightingView sky = showNumber ? null : world.getLightingProvider().get(LightType.SKY);
196 for (BlockPos pos : BlockPos.iterate(chunkPos.getStartX(), 0, chunkPos.getStartZ(), chunkPos.getEndX(), 256, chunkPos.getEndZ())) {
197 BlockPos down = pos.down();
199 int level = LightOverlay.getCrossLevel(pos, down, chunk, block, entityContext);
201 map.put(pos.asLong(), Integer.valueOf(level));
204 CrossType type = LightOverlay.getCrossType(pos, down, chunk, block, sky, entityContext);
205 if (type != CrossType.NONE) {
206 map.put(pos.asLong(), type);
210 CHUNK_MAP.put(chunkPos, map);
212 CHUNK_MAP.remove(chunkPos);
216 public static CrossType getCrossType(BlockPos pos, BlockPos down, BlockView world, ChunkLightingView block, ChunkLightingView sky, EntityContext entityContext) {
217 BlockState blockBelowState = world.getBlockState(down);
218 BlockState blockUpperState = world.getBlockState(pos);
219 VoxelShape upperCollisionShape = blockUpperState.getCollisionShape(world, pos, entityContext);
220 if (!underwater && !blockUpperState.getFluidState().isEmpty())
221 return CrossType.NONE;
222 // Check if the outline is full
223 if (Block.isFaceFullSquare(upperCollisionShape, Direction.UP))
224 return CrossType.NONE;
225 // TODO: Not to hard code no redstone
226 if (blockUpperState.emitsRedstonePower())
227 return CrossType.NONE;
228 // Check if the collision has a bump
229 if (upperCollisionShape.getMaximum(Direction.Axis.Y) > 0)
230 return CrossType.NONE;
231 if (blockUpperState.getBlock().isIn(BlockTags.RAILS))
232 return CrossType.NONE;
233 // Check block state allow spawning (excludes bedrock and barriers automatically)
234 if (!blockBelowState.allowsSpawning(world, down, testingEntityType))
235 return CrossType.NONE;
236 int blockLightLevel = block.getLightLevel(pos);
237 int skyLightLevel = sky.getLightLevel(pos);
238 if (blockLightLevel > higherCrossLevel)
239 return CrossType.NONE;
240 if (skyLightLevel > higherCrossLevel)
241 return CrossType.YELLOW;
242 return lowerCrossLevel >= 0 && blockLightLevel > lowerCrossLevel ? CrossType.SECONDARY : CrossType.RED;
245 public static int getCrossLevel(BlockPos pos, BlockPos down, BlockView world, ChunkLightingView view, EntityContext entityContext) {
246 BlockState blockBelowState = world.getBlockState(down);
247 BlockState blockUpperState = world.getBlockState(pos);
248 VoxelShape collisionShape = blockBelowState.getCollisionShape(world, down, entityContext);
249 VoxelShape upperCollisionShape = blockUpperState.getCollisionShape(world, pos, entityContext);
250 if (!underwater && !blockUpperState.getFluidState().isEmpty())
252 if (!blockBelowState.getFluidState().isEmpty())
254 if (blockBelowState.isAir())
256 if (Block.isFaceFullSquare(upperCollisionShape, Direction.DOWN))
258 return view.getLightLevel(pos);
261 public static void renderCross(Camera camera, World world, BlockPos pos, int color, EntityContext entityContext) {
262 double d0 = camera.getPos().x;
263 double d1 = camera.getPos().y - .005D;
264 VoxelShape upperOutlineShape = world.getBlockState(pos).getOutlineShape(world, pos, entityContext);
265 if (!upperOutlineShape.isEmpty())
266 d1 -= upperOutlineShape.getMaximum(Direction.Axis.Y);
267 double d2 = camera.getPos().z;
269 int red = (color >> 16) & 255;
270 int green = (color >> 8) & 255;
271 int blue = color & 255;
275 RenderSystem.color4f(red / 255f, green / 255f, blue / 255f, 1f);
276 GL11.glVertex3d(x + .01 - d0, y - d1, z + .01 - d2);
277 GL11.glVertex3d(x - .01 + 1 - d0, y - d1, z - .01 + 1 - d2);
278 GL11.glVertex3d(x - .01 + 1 - d0, y - d1, z + .01 - d2);
279 GL11.glVertex3d(x + .01 - d0, y - d1, z - .01 + 1 - d2);
282 @SuppressWarnings("deprecation")
283 public static void renderLevel(MinecraftClient client, Camera camera, World world, BlockPos pos, BlockPos down, int level, EntityContext entityContext) {
284 String text = String.valueOf(level);
285 TextRenderer textRenderer_1 = client.textRenderer;
286 double double_4 = camera.getPos().x;
287 double double_5 = camera.getPos().y;
288 VoxelShape upperOutlineShape = world.getBlockState(down).getOutlineShape(world, down, entityContext);
289 if (!upperOutlineShape.isEmpty())
290 double_5 += 1 - upperOutlineShape.getMaximum(Direction.Axis.Y);
291 double double_6 = camera.getPos().z;
292 RenderSystem.pushMatrix();
293 RenderSystem.translatef((float) (pos.getX() + 0.5f - double_4), (float) (pos.getY() - double_5) + 0.005f, (float) (pos.getZ() + 0.5f - double_6));
294 RenderSystem.rotatef(90, 1, 0, 0);
295 RenderSystem.normal3f(0.0F, 1.0F, 0.0F);
297 RenderSystem.scalef(-size, -size, size);
298 float float_3 = (float) (-textRenderer_1.getStringWidth(text)) / 2.0F + 0.4f;
299 RenderSystem.enableAlphaTest();
300 VertexConsumerProvider.Immediate immediate = VertexConsumerProvider.immediate(Tessellator.getInstance().getBuffer());
301 textRenderer_1.draw(text, float_3, -3.5f, level > higherCrossLevel ? 0xff042404 : (lowerCrossLevel >= 0 && level > lowerCrossLevel ? 0xff0066ff : 0xff731111), false, Rotation3.identity().getMatrix(), immediate, false, 0, 15728880);
303 RenderSystem.popMatrix();
306 static void loadConfig(File file) {
309 yellowColor = 0xFFFF00;
310 secondaryColor = 0x0000FF;
311 if (!file.exists() || !file.canRead())
313 FileInputStream fis = new FileInputStream(file);
314 Properties properties = new Properties();
315 properties.load(fis);
317 reach = Integer.parseInt((String) properties.computeIfAbsent("reach", a -> "12"));
318 crossLevel = Integer.parseInt((String) properties.computeIfAbsent("crossLevel", a -> "7"));
319 secondaryLevel = Integer.parseInt((String) properties.computeIfAbsent("secondaryLevel", a -> "-1"));
320 caching = ((String) properties.computeIfAbsent("caching", a -> "false")).equalsIgnoreCase("true");
321 showNumber = ((String) properties.computeIfAbsent("showNumber", a -> "false")).equalsIgnoreCase("true");
322 smoothLines = ((String) properties.computeIfAbsent("smoothLines", a -> "true")).equalsIgnoreCase("true");
323 underwater = ((String) properties.computeIfAbsent("underwater", a -> "false")).equalsIgnoreCase("true");
324 lineWidth = Float.parseFloat((String) properties.computeIfAbsent("lineWidth", a -> "1"));
327 r = Integer.parseInt((String) properties.computeIfAbsent("yellowColorRed", a -> "255"));
328 g = Integer.parseInt((String) properties.computeIfAbsent("yellowColorGreen", a -> "255"));
329 b = Integer.parseInt((String) properties.computeIfAbsent("yellowColorBlue", a -> "0"));
330 yellowColor = (r << 16) + (g << 8) + b;
334 r = Integer.parseInt((String) properties.computeIfAbsent("redColorRed", a -> "255"));
335 g = Integer.parseInt((String) properties.computeIfAbsent("redColorGreen", a -> "0"));
336 b = Integer.parseInt((String) properties.computeIfAbsent("redColorBlue", a -> "0"));
337 redColor = (r << 16) + (g << 8) + b;
341 r = Integer.parseInt((String) properties.computeIfAbsent("secondaryColorRed", a -> "0"));
342 g = Integer.parseInt((String) properties.computeIfAbsent("secondaryColorGreen", a -> "0"));
343 b = Integer.parseInt((String) properties.computeIfAbsent("secondaryColorBlue", a -> "255"));
344 secondaryColor = (r << 16) + (g << 8) + b;
347 } catch (Exception e) {
354 yellowColor = 0xFFFF00;
355 secondaryColor = 0x0000FF;
362 } catch (IOException ex) {
363 ex.printStackTrace();
366 if (secondaryLevel >= crossLevel) System.err.println("[Light Overlay] Secondary Level is higher than Cross Level");
367 lowerCrossLevel = Math.min(crossLevel, secondaryLevel);
368 higherCrossLevel = Math.max(crossLevel, secondaryLevel);
373 static void saveConfig(File file) throws IOException {
374 FileOutputStream fos = new FileOutputStream(file, false);
375 fos.write("# Light Overlay Config".getBytes());
376 fos.write("\n".getBytes());
377 fos.write(("reach=" + reach).getBytes());
378 fos.write("\n".getBytes());
379 fos.write(("crossLevel=" + crossLevel).getBytes());
380 fos.write("\n".getBytes());
381 fos.write(("secondaryLevel=" + secondaryLevel).getBytes());
382 fos.write("\n".getBytes());
383 fos.write(("caching=" + caching).getBytes());
384 fos.write("\n".getBytes());
385 fos.write(("showNumber=" + showNumber).getBytes());
386 fos.write("\n".getBytes());
387 fos.write(("smoothLines=" + smoothLines).getBytes());
388 fos.write("\n".getBytes());
389 fos.write(("underwater=" + underwater).getBytes());
390 fos.write("\n".getBytes());
391 fos.write(("lineWidth=" + FORMAT.format(lineWidth)).getBytes());
392 fos.write("\n".getBytes());
393 fos.write(("yellowColorRed=" + ((yellowColor >> 16) & 255)).getBytes());
394 fos.write("\n".getBytes());
395 fos.write(("yellowColorGreen=" + ((yellowColor >> 8) & 255)).getBytes());
396 fos.write("\n".getBytes());
397 fos.write(("yellowColorBlue=" + (yellowColor & 255)).getBytes());
398 fos.write("\n".getBytes());
399 fos.write(("redColorRed=" + ((redColor >> 16) & 255)).getBytes());
400 fos.write("\n".getBytes());
401 fos.write(("redColorGreen=" + ((redColor >> 8) & 255)).getBytes());
402 fos.write("\n".getBytes());
403 fos.write(("redColorBlue=" + (redColor & 255)).getBytes());
404 fos.write("\n".getBytes());
405 fos.write(("secondaryColorRed=" + ((secondaryColor >> 16) & 255)).getBytes());
406 fos.write("\n".getBytes());
407 fos.write(("secondaryColorGreen=" + ((secondaryColor >> 8) & 255)).getBytes());
408 fos.write("\n".getBytes());
409 fos.write(("secondaryColorBlue=" + (secondaryColor & 255)).getBytes());
413 private static KeyBinding createKeyBinding(Identifier id, InputUtil.Type type, int code, String category) {
414 return KeyBindingHelper.registerKeyBinding(new KeyBinding("key." + id.getNamespace() + "." + id.getPath(), type, code, category));
418 public void onInitializeClient() {
420 loadConfig(configFile);
423 testingEntityType = EntityType.Builder.create(EntityCategory.MONSTER).setDimensions(0f, 0f).disableSaving().build(null);
424 ClientTickEvents.END_CLIENT_TICK.register(minecraftClient -> {
425 while (ENABLE_OVERLAY.wasPressed())
428 ClothClientHooks.DEBUG_RENDER_PRE.register(() -> {
429 if (LightOverlay.enabled) {
430 PlayerEntity playerEntity = CLIENT.player;
431 int playerPosX = ((int) playerEntity.getX()) >> 4;
432 int playerPosZ = ((int) playerEntity.getZ()) >> 4;
433 EntityContext entityContext = EntityContext.of(playerEntity);
434 World world = CLIENT.world;
435 BlockPos playerPos = new BlockPos(playerEntity.getX(), playerEntity.getY(), playerEntity.getZ());
436 Camera camera = CLIENT.gameRenderer.getCamera();
438 RenderSystem.enableTexture();
439 RenderSystem.depthMask(true);
440 BlockPos.Mutable mutable = new BlockPos.Mutable();
441 BlockPos.Mutable downMutable = new BlockPos.Mutable();
442 for (Map.Entry<ChunkPos, Long2ReferenceMap<Object>> entry : CHUNK_MAP.entrySet()) {
443 if (caching && (MathHelper.abs(entry.getKey().x - playerPosX) > getChunkRange() || MathHelper.abs(entry.getKey().z - playerPosZ) > getChunkRange())) {
446 for (Long2ReferenceMap.Entry<Object> objectEntry : entry.getValue().long2ReferenceEntrySet()) {
447 if (objectEntry.getValue() instanceof Integer) {
448 mutable.set(BlockPos.unpackLongX(objectEntry.getLongKey()), BlockPos.unpackLongY(objectEntry.getLongKey()), BlockPos.unpackLongZ(objectEntry.getLongKey()));
449 if (mutable.isWithinDistance(playerPos, reach)) {
450 if (frustum == null || FrustumHelper.isVisible(frustum, mutable.getX(), mutable.getY(), mutable.getZ(), mutable.getX() + 1, mutable.getX() + 1, mutable.getX() + 1)) {
451 downMutable.set(mutable.getX(), mutable.getY() - 1, mutable.getZ());
452 LightOverlay.renderLevel(CLIENT, camera, world, mutable, downMutable, (Integer) objectEntry.getValue(), entityContext);
458 RenderSystem.enableDepthTest();
460 RenderSystem.enableDepthTest();
461 RenderSystem.disableTexture();
462 RenderSystem.enableBlend();
463 RenderSystem.blendFunc(GlStateManager.SrcFactor.SRC_ALPHA, GlStateManager.DstFactor.ONE_MINUS_SRC_ALPHA);
464 if (smoothLines) GL11.glEnable(GL11.GL_LINE_SMOOTH);
465 GL11.glLineWidth(lineWidth);
466 GL11.glBegin(GL11.GL_LINES);
467 BlockPos.Mutable mutable = new BlockPos.Mutable();
468 for (Map.Entry<ChunkPos, Long2ReferenceMap<Object>> entry : CHUNK_MAP.entrySet()) {
469 if (caching && (MathHelper.abs(entry.getKey().x - playerPosX) > getChunkRange() || MathHelper.abs(entry.getKey().z - playerPosZ) > getChunkRange())) {
472 for (Long2ReferenceMap.Entry<Object> objectEntry : entry.getValue().long2ReferenceEntrySet()) {
473 if (objectEntry.getValue() instanceof CrossType) {
474 mutable.set(BlockPos.unpackLongX(objectEntry.getLongKey()), BlockPos.unpackLongY(objectEntry.getLongKey()), BlockPos.unpackLongZ(objectEntry.getLongKey()));
475 if (mutable.isWithinDistance(playerPos, reach)) {
476 if (frustum == null || FrustumHelper.isVisible(frustum, mutable.getX(), mutable.getY(), mutable.getZ(), mutable.getX() + 1, mutable.getX() + 1, mutable.getX() + 1)) {
477 int color = objectEntry.getValue() == CrossType.RED ? redColor : objectEntry.getValue() == CrossType.YELLOW ? yellowColor : secondaryColor;
478 LightOverlay.renderCross(camera, world, mutable, color, entityContext);
485 RenderSystem.disableBlend();
486 RenderSystem.enableTexture();
487 if (smoothLines) GL11.glDisable(GL11.GL_LINE_SMOOTH);
493 private enum CrossType {