From 0a32b6eda9fb8dc879a94db1cdc9262ffdd8b4a3 Mon Sep 17 00:00:00 2001
From: MattiDragon <matias.koivikko@gmail.com>
Date: Sun, 24 Apr 2022 13:17:38 +0300
Subject: [PATCH] Add config

---
 build.gradle                                  |  4 ++
 gradle.properties                             |  5 +-
 .../extendeddrawers/ExtendedDrawers.java      |  4 ++
 .../renderer/DrawerBlockEntityRenderer.java   | 54 +++++++++++--------
 .../ShadowDrawerBlockEntityRenderer.java      | 23 +++++---
 .../extendeddrawers/config/ClientConfig.java  | 17 ++++++
 .../extendeddrawers/config/CommonConfig.java  | 17 ++++++
 .../util/DrawerInteractionStatusManager.java  | 11 ++--
 .../extendeddrawers/util/NetworkHelper.java   |  5 +-
 9 files changed, 103 insertions(+), 37 deletions(-)
 create mode 100644 src/main/java/io/github/mattidragon/extendeddrawers/config/ClientConfig.java
 create mode 100644 src/main/java/io/github/mattidragon/extendeddrawers/config/CommonConfig.java

diff --git a/build.gradle b/build.gradle
index c636975..bf41ec2 100644
--- a/build.gradle
+++ b/build.gradle
@@ -9,6 +9,9 @@ version project.mod_version + (run == null ? "" : "-dev.$run") + "+mc.$minecraft
 group project.maven_group
 
 repositories {
+    ext.maven = { String s -> maven {url(s)}}
+
+    maven "https://jitpack.io"
 }
 
 dependencies {
@@ -17,6 +20,7 @@ dependencies {
     modImplementation "net.fabricmc:fabric-loader:$loader_version"
 
     modImplementation "net.fabricmc.fabric-api:fabric-api:$fabric_version"
+    include modImplementation("com.github.mattidragon:mconfig:$mconfig_version")
 }
 
 loom {
diff --git a/gradle.properties b/gradle.properties
index b016e7c..68e991a 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -1,12 +1,13 @@
 org.gradle.jvmargs=-Xmx1G
 
 minecraft_version=1.18.2
-yarn_mappings=1.18.2+build.2
+yarn_mappings=1.18.2+build.3
 loader_version=0.13.3
 
 mod_version=1.0.0
 maven_group=io.github.mattidragon
 archives_base_name=ExtendedDrawers
 
-fabric_version=0.51.0+1.18.2
+fabric_version=0.51.1+1.18.2
+mconfig_version=1.1.0
 
diff --git a/src/main/java/io/github/mattidragon/extendeddrawers/ExtendedDrawers.java b/src/main/java/io/github/mattidragon/extendeddrawers/ExtendedDrawers.java
index 70e8f18..6d14d14 100644
--- a/src/main/java/io/github/mattidragon/extendeddrawers/ExtendedDrawers.java
+++ b/src/main/java/io/github/mattidragon/extendeddrawers/ExtendedDrawers.java
@@ -1,5 +1,7 @@
 package io.github.mattidragon.extendeddrawers;
 
+import io.github.mattidragon.extendeddrawers.config.ClientConfig;
+import io.github.mattidragon.extendeddrawers.config.CommonConfig;
 import io.github.mattidragon.extendeddrawers.registry.ModBlocks;
 import io.github.mattidragon.extendeddrawers.registry.ModItems;
 import net.fabricmc.api.ModInitializer;
@@ -20,5 +22,7 @@ public static Identifier id(String path) {
     public void onInitialize() {
         ModBlocks.register();
         ModItems.register();
+        ClientConfig.HANDLE.load();
+        CommonConfig.HANDLE.load();
     }
 }
diff --git a/src/main/java/io/github/mattidragon/extendeddrawers/client/renderer/DrawerBlockEntityRenderer.java b/src/main/java/io/github/mattidragon/extendeddrawers/client/renderer/DrawerBlockEntityRenderer.java
index bfda63e..51cd2f4 100644
--- a/src/main/java/io/github/mattidragon/extendeddrawers/client/renderer/DrawerBlockEntityRenderer.java
+++ b/src/main/java/io/github/mattidragon/extendeddrawers/client/renderer/DrawerBlockEntityRenderer.java
@@ -2,6 +2,7 @@
 
 import io.github.mattidragon.extendeddrawers.block.DrawerBlock;
 import io.github.mattidragon.extendeddrawers.block.entity.DrawerBlockEntity;
+import io.github.mattidragon.extendeddrawers.config.ClientConfig;
 import io.github.mattidragon.extendeddrawers.drawer.DrawerSlot;
 import net.fabricmc.fabric.api.renderer.v1.RendererAccess;
 import net.fabricmc.fabric.api.renderer.v1.mesh.MutableQuadView;
@@ -15,15 +16,11 @@
 import net.minecraft.client.render.model.json.ModelTransformation;
 import net.minecraft.client.texture.Sprite;
 import net.minecraft.client.util.math.MatrixStack;
-import net.minecraft.item.ItemStack;
 import net.minecraft.screen.PlayerScreenHandler;
-import net.minecraft.util.math.Direction;
-import net.minecraft.util.math.Matrix4f;
-import net.minecraft.util.math.Vec3f;
+import net.minecraft.util.math.*;
 
 import java.util.ArrayList;
 import java.util.Objects;
-import java.util.stream.StreamSupport;
 
 import static io.github.mattidragon.extendeddrawers.ExtendedDrawers.id;
 
@@ -31,6 +28,12 @@
 public class DrawerBlockEntityRenderer implements BlockEntityRenderer<DrawerBlockEntity> {
     public DrawerBlockEntityRenderer(BlockEntityRendererFactory.Context context) {}
     
+    @Override
+    public int getRenderDistance() {
+        var config = ClientConfig.HANDLE.get();
+        return Math.max(config.iconRenderDistance(), Math.max(config.textRenderDistance(), config.itemRenderDistance()));
+    }
+    
     @Override
     public void render(DrawerBlockEntity entity, float tickDelta, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, int overlay) {
         matrices.push();
@@ -44,26 +47,27 @@ public void render(DrawerBlockEntity entity, float tickDelta, MatrixStack matric
     
         light = WorldRenderer.getLightmapCoordinates(Objects.requireNonNull(entity.getWorld()), entity.getPos().offset(dir));
         var slots = ((DrawerBlock)entity.getCachedState().getBlock()).slots;
-    
+        var blockPos = entity.getPos();
+        
         switch (slots) {
-            case 1 -> renderSlot(entity.storages[0], light, matrices, vertexConsumers, (int) entity.getPos().asLong(), overlay);
+            case 1 -> renderSlot(entity.storages[0], light, matrices, vertexConsumers, (int) entity.getPos().asLong(), overlay, blockPos);
             case 2 -> {
                 matrices.scale(0.5f, 0.5f, 0.5f);
                 matrices.translate(-0.5, 0, 0);
-                renderSlot(entity.storages[0], light, matrices, vertexConsumers, (int) entity.getPos().asLong(), overlay);
+                renderSlot(entity.storages[0], light, matrices, vertexConsumers, (int) entity.getPos().asLong(), overlay, blockPos);
                 matrices.translate(1, 0, 0);
-                renderSlot(entity.storages[1], light, matrices, vertexConsumers, (int) entity.getPos().asLong(), overlay);
+                renderSlot(entity.storages[1], light, matrices, vertexConsumers, (int) entity.getPos().asLong(), overlay, blockPos);
             }
             case 4 -> {
                 matrices.scale(0.5f, 0.5f, 0.5f);
                 matrices.translate(-0.5, 0.5, 0);
-                renderSlot(entity.storages[0], light, matrices, vertexConsumers, (int) entity.getPos().asLong(), overlay);
+                renderSlot(entity.storages[0], light, matrices, vertexConsumers, (int) entity.getPos().asLong(), overlay, blockPos);
                 matrices.translate(1, 0, 0);
-                renderSlot(entity.storages[1], light, matrices, vertexConsumers, (int) entity.getPos().asLong(), overlay);
+                renderSlot(entity.storages[1], light, matrices, vertexConsumers, (int) entity.getPos().asLong(), overlay, blockPos);
                 matrices.translate(-1, -1, 0);
-                renderSlot(entity.storages[2], light, matrices, vertexConsumers, (int) entity.getPos().asLong(), overlay);
+                renderSlot(entity.storages[2], light, matrices, vertexConsumers, (int) entity.getPos().asLong(), overlay, blockPos);
                 matrices.translate(1, 0, 0);
-                renderSlot(entity.storages[3], light, matrices, vertexConsumers, (int) entity.getPos().asLong(), overlay);
+                renderSlot(entity.storages[3], light, matrices, vertexConsumers, (int) entity.getPos().asLong(), overlay, blockPos);
             }
             default -> throw new IllegalStateException("unexpected drawer slot count");
         }
@@ -71,24 +75,28 @@ public void render(DrawerBlockEntity entity, float tickDelta, MatrixStack matric
         matrices.pop();
     }
     
-    private void renderSlot(DrawerSlot storage, int light, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int seed, int overlay) {
-        renderText(storage, light, matrices, vertexConsumers);
-        renderIcons(storage, light, matrices, vertexConsumers, overlay);
-        renderItem(storage, light, matrices, vertexConsumers, seed);
+    private void renderSlot(DrawerSlot storage, int light, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int seed, int overlay, BlockPos pos) {
+        //noinspection ConstantConditions
+        var playerPos = MinecraftClient.getInstance().player.getPos();
+        var config = ClientConfig.HANDLE.get();
+        
+        if (pos.isWithinDistance(playerPos, config.textRenderDistance()))
+            renderText(storage, light, matrices, vertexConsumers);
+        if (pos.isWithinDistance(playerPos, config.iconRenderDistance()))
+            renderIcons(storage, light, matrices, vertexConsumers, overlay);
+        if (pos.isWithinDistance(playerPos, config.itemRenderDistance()))
+            renderItem(storage, light, matrices, vertexConsumers, seed);
     }
     
     private void renderIcons(DrawerSlot storage, int light, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int overlay) {
         var icons = new ArrayList<Sprite>();
         var mc = MinecraftClient.getInstance();
         var blockAtlas = mc.getSpriteAtlas(PlayerScreenHandler.BLOCK_ATLAS_TEXTURE);
-    
-        //noinspection ConstantConditions
-        var handItems = StreamSupport.stream(mc.player.getItemsHand().spliterator(), false).map(ItemStack::getItem).toList();
-        
-        if (storage.locked /*&& handItems.contains(ModItems.LOCK)*/)
+
+        if (storage.locked)
             icons.add(blockAtlas.apply(id("item/lock")));
         
-        if (storage.upgrade != null /* &&  CollectionUtils.anyMatch(handItems, item -> item instanceof UpgradeItem)*/)
+        if (storage.upgrade != null)
             icons.add(blockAtlas.apply(storage.upgrade.sprite));
 
         
diff --git a/src/main/java/io/github/mattidragon/extendeddrawers/client/renderer/ShadowDrawerBlockEntityRenderer.java b/src/main/java/io/github/mattidragon/extendeddrawers/client/renderer/ShadowDrawerBlockEntityRenderer.java
index fb2e64f..687f5cd 100644
--- a/src/main/java/io/github/mattidragon/extendeddrawers/client/renderer/ShadowDrawerBlockEntityRenderer.java
+++ b/src/main/java/io/github/mattidragon/extendeddrawers/client/renderer/ShadowDrawerBlockEntityRenderer.java
@@ -2,6 +2,7 @@
 
 import io.github.mattidragon.extendeddrawers.block.ShadowDrawerBlock;
 import io.github.mattidragon.extendeddrawers.block.entity.ShadowDrawerBlockEntity;
+import io.github.mattidragon.extendeddrawers.config.ClientConfig;
 import net.minecraft.client.MinecraftClient;
 import net.minecraft.client.render.OverlayTexture;
 import net.minecraft.client.render.VertexConsumerProvider;
@@ -18,12 +19,20 @@
 public class ShadowDrawerBlockEntityRenderer implements BlockEntityRenderer<ShadowDrawerBlockEntity> {
     public ShadowDrawerBlockEntityRenderer(BlockEntityRendererFactory.Context context) {}
     
+    @Override
+    public int getRenderDistance() {
+        var config = ClientConfig.HANDLE.get();
+        return Math.max(config.textRenderDistance(), config.itemRenderDistance());
+    }
+    
     @SuppressWarnings("UnstableApiUsage")
     @Override
     public void render(ShadowDrawerBlockEntity entity, float tickDelta, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, int overlay) {
         matrices.push();
         var dir = entity.getCachedState().get(ShadowDrawerBlock.FACING);
         var pos = dir.getUnitVector();
+        var config = ClientConfig.HANDLE.get();
+        var playerPos = MinecraftClient.getInstance().player.getPos();
     
         matrices.translate(pos.getX() / 2 + 0.5, pos.getY() / 2 + 0.5, pos.getZ() / 2 + 0.5);
         matrices.multiply(dir.getRotationQuaternion());
@@ -32,13 +41,15 @@ public void render(ShadowDrawerBlockEntity entity, float tickDelta, MatrixStack
     
         light = WorldRenderer.getLightmapCoordinates(Objects.requireNonNull(entity.getWorld()), entity.getPos().offset(dir));
         
-        matrices.push();
-        matrices.scale(0.75f, 0.75f, 1);
-        matrices.multiplyPositionMatrix(Matrix4f.scale(1, 1, 0.01f));
-        MinecraftClient.getInstance().getItemRenderer().renderItem(entity.item.toStack(), ModelTransformation.Mode.GUI, light, OverlayTexture.DEFAULT_UV, matrices, vertexConsumers, (int)entity.getPos().asLong());
-        matrices.pop();
+        if (entity.getPos().isWithinDistance(playerPos, config.itemRenderDistance())) {
+            matrices.push();
+            matrices.scale(0.75f, 0.75f, 1);
+            matrices.multiplyPositionMatrix(Matrix4f.scale(1, 1, 0.01f));
+            MinecraftClient.getInstance().getItemRenderer().renderItem(entity.item.toStack(), ModelTransformation.Mode.GUI, light, OverlayTexture.DEFAULT_UV, matrices, vertexConsumers, (int) entity.getPos().asLong());
+            matrices.pop();
+        }
     
-        if (!entity.item.isBlank()) {
+        if (!entity.item.isBlank() && entity.getPos().isWithinDistance(playerPos, config.textRenderDistance())) {
             var amount = entity.createStorage().simulateExtract(entity.item, Long.MAX_VALUE, null);
             
             matrices.push();
diff --git a/src/main/java/io/github/mattidragon/extendeddrawers/config/ClientConfig.java b/src/main/java/io/github/mattidragon/extendeddrawers/config/ClientConfig.java
new file mode 100644
index 0000000..cd31aa5
--- /dev/null
+++ b/src/main/java/io/github/mattidragon/extendeddrawers/config/ClientConfig.java
@@ -0,0 +1,17 @@
+package io.github.mattidragon.extendeddrawers.config;
+
+import io.github.mattidragon.mconfig.config.Comment;
+import io.github.mattidragon.mconfig.config.Config;
+import io.github.mattidragon.mconfig.config.ConfigManager;
+import io.github.mattidragon.mconfig.config.ConfigType;
+
+public record ClientConfig(
+        @Comment("The render distance of the item icon on drawers")
+        int itemRenderDistance,
+        @Comment("The render distance of the lock and upgrade icons on drawers")
+        int iconRenderDistance,
+        @Comment("The render distance of the number of items on the drawers")
+        int textRenderDistance
+) {
+    public static final Config<ClientConfig> HANDLE = ConfigManager.register(ConfigType.CLIENT, "extended_drawers", new ClientConfig(64, 16, 32));
+}
diff --git a/src/main/java/io/github/mattidragon/extendeddrawers/config/CommonConfig.java b/src/main/java/io/github/mattidragon/extendeddrawers/config/CommonConfig.java
new file mode 100644
index 0000000..6efddca
--- /dev/null
+++ b/src/main/java/io/github/mattidragon/extendeddrawers/config/CommonConfig.java
@@ -0,0 +1,17 @@
+package io.github.mattidragon.extendeddrawers.config;
+
+import io.github.mattidragon.mconfig.config.Comment;
+import io.github.mattidragon.mconfig.config.Config;
+import io.github.mattidragon.mconfig.config.ConfigManager;
+import io.github.mattidragon.mconfig.config.ConfigType;
+
+public record CommonConfig(
+        @Comment("The max distance that blocks will search for other blocks on a network")
+        int networkSearchDistance,
+        @Comment("The max time between the clicks of a double insert")
+        int insertAllTime,
+        @Comment("Whether to add a small cooldown to extractions to avoid double ones caused by a vanilla bug")
+        boolean deduplicateExtraction
+) {
+    public static final Config<CommonConfig> HANDLE = ConfigManager.register(ConfigType.COMMON, "extended_drawers", new CommonConfig(64, 10, true));
+}
diff --git a/src/main/java/io/github/mattidragon/extendeddrawers/util/DrawerInteractionStatusManager.java b/src/main/java/io/github/mattidragon/extendeddrawers/util/DrawerInteractionStatusManager.java
index 94f6a4c..d026af7 100644
--- a/src/main/java/io/github/mattidragon/extendeddrawers/util/DrawerInteractionStatusManager.java
+++ b/src/main/java/io/github/mattidragon/extendeddrawers/util/DrawerInteractionStatusManager.java
@@ -1,5 +1,6 @@
 package io.github.mattidragon.extendeddrawers.util;
 
+import io.github.mattidragon.extendeddrawers.config.CommonConfig;
 import net.fabricmc.fabric.api.transfer.v1.item.ItemVariant;
 import net.minecraft.entity.player.PlayerEntity;
 import net.minecraft.util.math.BlockPos;
@@ -7,6 +8,7 @@
 import java.util.Optional;
 import java.util.WeakHashMap;
 
+@SuppressWarnings("ALL")
 public final class DrawerInteractionStatusManager {
     private DrawerInteractionStatusManager(){}
     
@@ -22,12 +24,11 @@ private DrawerInteractionStatusManager(){}
      * @param item The type of item inserted
      * @return The item that should be used for the insertion or an empty optional if there shouldn't be a multi-stack insertion.
      */
-    @SuppressWarnings("UnstableApiUsage")
     public static Optional<ItemVariant> getAndResetInsertStatus(PlayerEntity player, BlockPos pos, int slot, ItemVariant item) {
         var timestamp = player.getWorld().getTime();
         var interaction = INSERTIONS.get().remove(player);
         if (interaction != null)
-            if (interaction.pos.equals(pos) && timestamp - interaction.timestamp < 10 && interaction.slot == slot) //TODO: config
+            if (interaction.pos.equals(pos) && timestamp - interaction.timestamp < CommonConfig.HANDLE.get().insertAllTime() && interaction.slot == slot)
                 return Optional.of(interaction.item);
             else
                 return Optional.empty();
@@ -37,11 +38,13 @@ public static Optional<ItemVariant> getAndResetInsertStatus(PlayerEntity player,
     }
     
     /**
-     * Makes sure that players can only extract evey four ticks to avoid double extractions caused by changing the held item.
+     * Makes sure that players can only extract every four ticks to avoid double extractions caused by changing the held item.
      * @param player The player attempting extraction
      * @return Whether the player should be allowed to extract.
      */
-    public static boolean getAndResetExtractionTimer(PlayerEntity player) { // TODO: possible config to disable this
+    public static boolean getAndResetExtractionTimer(PlayerEntity player) {
+        if (!CommonConfig.HANDLE.get().deduplicateExtraction()) return true;
+        
         var time = player.getWorld().getTime();
         var timestamp = EXTRACTIONS.get().remove(player);
         if (timestamp != null && time - timestamp <= 3) return false;
diff --git a/src/main/java/io/github/mattidragon/extendeddrawers/util/NetworkHelper.java b/src/main/java/io/github/mattidragon/extendeddrawers/util/NetworkHelper.java
index 10ca347..9d54a02 100644
--- a/src/main/java/io/github/mattidragon/extendeddrawers/util/NetworkHelper.java
+++ b/src/main/java/io/github/mattidragon/extendeddrawers/util/NetworkHelper.java
@@ -3,6 +3,7 @@
 import com.google.common.collect.Queues;
 import io.github.mattidragon.extendeddrawers.block.DrawerBlock;
 import io.github.mattidragon.extendeddrawers.block.entity.DrawerBlockEntity;
+import io.github.mattidragon.extendeddrawers.config.CommonConfig;
 import io.github.mattidragon.extendeddrawers.drawer.DrawerSlot;
 import io.github.mattidragon.extendeddrawers.registry.ModTags;
 import net.minecraft.util.math.BlockPos;
@@ -29,7 +30,7 @@ public static Optional<BlockPos> findFirstConnectedComponent(World world, BlockP
         
             for (var dir : Direction.values()) {
                 var offsetPos = searching.offset(dir);
-                if (!searched.contains(offsetPos) && offsetPos.isWithinDistance(pos, 64))  // TODO: config
+                if (!searched.contains(offsetPos) && offsetPos.isWithinDistance(pos, CommonConfig.HANDLE.get().networkSearchDistance()))
                     toSearch.add(offsetPos);
             }
         }
@@ -54,7 +55,7 @@ public static List<BlockPos> findConnectedComponents(World world, BlockPos pos,
         
             for (var dir : Direction.values()) {
                 var offsetPos = searching.offset(dir);
-                if (!searched.contains(offsetPos) && offsetPos.isWithinDistance(pos, 64))  // TODO: config
+                if (!searched.contains(offsetPos) && offsetPos.isWithinDistance(pos, CommonConfig.HANDLE.get().networkSearchDistance()))
                     toSearch.add(offsetPos);
             }
         }