44 lines
2.1 KiB
Java
44 lines
2.1 KiB
Java
package whirlfrenzy.itemdespawntimer.config;
|
|
|
|
import com.google.gson.Gson;
|
|
import com.google.gson.GsonBuilder;
|
|
import net.fabricmc.api.EnvType;
|
|
import net.fabricmc.loader.api.FabricLoader;
|
|
import net.minecraft.core.registries.BuiltInRegistries;
|
|
import net.minecraft.world.entity.item.ItemEntity;
|
|
import whirlfrenzy.itemdespawntimer.ItemDespawnTimer;
|
|
import java.io.*; import java.nio.file.*; import java.util.*;
|
|
|
|
public final class ServerConfig {
|
|
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
|
private static Data data = new Data();
|
|
public static final class Data {
|
|
public int defaultDespawnSeconds = 300;
|
|
public boolean allowInfiniteLifetime = true;
|
|
public Map<String,Integer> itemDespawnSeconds = new LinkedHashMap<>();
|
|
}
|
|
private ServerConfig() {}
|
|
public static void load() {
|
|
// The common/main initializer also runs in a physical Minecraft client.
|
|
// Never create or read the server config there: a client installation owns
|
|
// presentation settings only. Integrated singleplayer uses server defaults
|
|
// in memory; a dedicated server owns the persistent server config file.
|
|
if (FabricLoader.getInstance().getEnvironmentType() != EnvType.SERVER) {
|
|
data = new Data();
|
|
return;
|
|
}
|
|
|
|
Path p = FabricLoader.getInstance().getConfigDir().resolve("item-despawn-timer-server.json");
|
|
try {
|
|
if (Files.exists(p)) { try (Reader r=Files.newBufferedReader(p)) { Data d=GSON.fromJson(r,Data.class); if(d!=null)data=d; } }
|
|
else { Files.createDirectories(p.getParent()); try(Writer w=Files.newBufferedWriter(p)){GSON.toJson(data,w);} }
|
|
} catch(Exception e){ ItemDespawnTimer.LOGGER.error("Cannot load server config",e); }
|
|
}
|
|
public static int lifespanTicks(ItemEntity entity) {
|
|
String id = BuiltInRegistries.ITEM.getKey(entity.getItem().getItem()).toString();
|
|
int seconds = data.itemDespawnSeconds.getOrDefault(id, data.defaultDespawnSeconds);
|
|
if (seconds < 0 && data.allowInfiniteLifetime) return Integer.MAX_VALUE;
|
|
return Math.max(1, seconds) * 20;
|
|
}
|
|
}
|