Files
src
build.gradle
gradle.properties
settings.gradle
Code
9 411
src/main/java/com/kodari/xpmultiplier/XpMultiplier.java
package com.kodari.xpmultiplier;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.brigadier.arguments.DoubleArgumentType;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.permissions.Permissions;
import net.minecraft.world.entity.LivingEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
public final class XpMultiplier implements ModInitializer {
public static final String MOD_ID = "xpmultiplier";
private static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private static final Path CONFIG_PATH = Path.of("config", "xpmultiplier.json");
private static final ThreadLocal<ArrayDeque<MobContext>> MOB_CONTEXT = ThreadLocal.withInitial(ArrayDeque::new);
private static final Map<String, Double> PER_MOB = new HashMap<>();
private static final Set<String> BLACKLIST = new HashSet<>();
private static boolean enabled = true;
private static double multiplier = 2.0;
private static double otherMultiplier = 2.0;
private static boolean requirePlayerKill = true;
@Override
public void onInitialize() {
loadConfig();
registerCommands();
}
public static void beginMobReward(LivingEntity entity, boolean playerCredited) {
MOB_CONTEXT.get().push(new MobContext(entity, playerCredited));
}
public static void endMobReward() {
ArrayDeque<MobContext> contexts = MOB_CONTEXT.get();
if (!contexts.isEmpty()) {
contexts.pop();
}
if (contexts.isEmpty()) {
MOB_CONTEXT.remove();
}
}
public static int scaleOrbValue(int value) {
if (!enabled || value <= 0) {
return value;
}
double rate = otherMultiplier;
ArrayDeque<MobContext> contexts = MOB_CONTEXT.get();
if (!contexts.isEmpty()) {
MobContext context = contexts.peek();
String entityId = BuiltInRegistries.ENTITY_TYPE.getKey(context.entity().getType()).toString();
if (BLACKLIST.contains(entityId) || (requirePlayerKill && !context.playerCredited())) {
return value;
}
rate = PER_MOB.getOrDefault(entityId, multiplier);
}
double scaled = value * rate;
long whole = (long) Math.floor(scaled);
if (ThreadLocalRandom.current().nextDouble() < scaled - whole) {
whole++;
}
return (int) Math.min(Integer.MAX_VALUE, whole);
}
private static void registerCommands() {
CommandRegistrationCallback.EVENT.register((dispatcher, buildContext, selection) -> dispatcher.register(
Commands.literal("xpmult")
.requires(source -> source.permissions().hasPermission(Permissions.COMMANDS_MODERATOR))
.executes(context -> showStatus(context.getSource()))
.then(Commands.literal("status").executes(context -> showStatus(context.getSource())))
.then(Commands.literal("set")
.then(Commands.argument("value", DoubleArgumentType.doubleArg(0.0, 64.0))
.executes(context -> setMultiplier(context.getSource(), DoubleArgumentType.getDouble(context, "value")))))
.then(Commands.literal("other")
.then(Commands.argument("value", DoubleArgumentType.doubleArg(0.0, 64.0))
.executes(context -> setOtherMultiplier(context.getSource(), DoubleArgumentType.getDouble(context, "value")))))
.then(Commands.literal("enabled")
.then(Commands.argument("value", BoolArgumentType.bool())
.executes(context -> setEnabled(context.getSource(), BoolArgumentType.getBool(context, "value")))))
.then(Commands.literal("reload").executes(context -> reloadConfig(context.getSource())))
));
}
private static int showStatus(CommandSourceStack source) {
source.sendSuccess(() -> Component.literal(
"XP multiplier: " + (enabled ? "enabled" : "disabled")
+ ", mobs=" + multiplier
+ ", other=" + otherMultiplier
+ ", config=" + CONFIG_PATH.toAbsolutePath()
), false);
return 1;
}
private static int setMultiplier(CommandSourceStack source, double value) {
multiplier = value;
return saveAndReply(source, "Mob XP multiplier set to " + value + ".");
}
private static int setOtherMultiplier(CommandSourceStack source, double value) {
otherMultiplier = value;
return saveAndReply(source, "Other XP multiplier set to " + value + ".");
}
private static int setEnabled(CommandSourceStack source, boolean value) {
enabled = value;
return saveAndReply(source, "XP multiplier " + (value ? "enabled" : "disabled") + ".");
}
private static int saveAndReply(CommandSourceStack source, String message) {
if (saveConfig()) {
source.sendSuccess(() -> Component.literal(message), true);
} else {
source.sendSuccess(() -> Component.literal(message + " Could not save the config file."), false);
}
return 1;
}
private static int reloadConfig(CommandSourceStack source) {
boolean loaded = loadConfig();
source.sendSuccess(() -> Component.literal(loaded
? "XP multiplier config reloaded."
: "Could not read the XP multiplier config; defaults are active."), false);
return loaded ? 1 : 0;
}
private static boolean loadConfig() {
resetDefaults();
if (!Files.exists(CONFIG_PATH)) {
return saveConfig();
}
try {
JsonElement root = JsonParser.parseString(Files.readString(CONFIG_PATH));
if (!root.isJsonObject()) {
throw new IllegalArgumentException("The config root must be a JSON object.");
}
JsonObject json = root.getAsJsonObject();
enabled = readBoolean(json, "enabled", enabled);
multiplier = readMultiplier(json, "multiplier", multiplier);
otherMultiplier = readMultiplier(json, "other_multiplier", otherMultiplier);
requirePlayerKill = readBoolean(json, "require_player_kill", requirePlayerKill);
JsonElement perMob = json.get("per_mob");
if (perMob != null && perMob.isJsonObject()) {
for (Map.Entry<String, JsonElement> entry : perMob.getAsJsonObject().entrySet()) {
JsonElement value = entry.getValue();
if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isNumber()) {
PER_MOB.put(entry.getKey(), clampMultiplier(value.getAsDouble()));
}
}
}
JsonElement blacklist = json.get("blacklist");
if (blacklist != null && blacklist.isJsonArray()) {
BLACKLIST.clear();
for (JsonElement value : blacklist.getAsJsonArray()) {
if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isString()) {
BLACKLIST.add(value.getAsString());
}
}
}
return true;
} catch (IOException | RuntimeException exception) {
resetDefaults();
LOGGER.warn("Could not load XP multiplier config at {}", CONFIG_PATH, exception);
return false;
}
}
private static boolean saveConfig() {
JsonObject json = new JsonObject();
json.addProperty("enabled", enabled);
json.addProperty("multiplier", multiplier);
json.addProperty("other_multiplier", otherMultiplier);