Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import net.tfminecraft.advancedcrafting.objects.crafting.CraftingStation;
import net.tfminecraft.advancedcrafting.utils.RevisionTracker;
import net.tfminecraft.advancedcrafting.lifecycle.CraftLifecycle;
import net.tfminecraft.advancedcrafting.lifecycle.KnownAlloyRecipes;
import net.tfminecraft.advancedcrafting.lifecycle.PlayerAlloyForgeTracker;

public class AdvancedCrafting extends JavaPlugin{
Expand Down Expand Up @@ -68,6 +69,7 @@ public void onEnable() {
revisionTracker.load(getDataFolder());
loadConfigs();
CraftLifecycle.init(new PlayerAlloyForgeTracker(new File(getDataFolder(), "data")));
KnownAlloyRecipes.init(new KnownAlloyRecipes(new File(getDataFolder(), "data")));
registerListeners();
craftRefreshListener.start(this);
getCommand(commandManager.cmd1).setExecutor(commandManager);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
package net.tfminecraft.advancedcrafting.lifecycle;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;

import net.tfminecraft.advancedcrafting.AdvancedCrafting;
import net.tfminecraft.advancedcrafting.managers.AlloyManager;
import net.tfminecraft.advancedcrafting.objects.alloys.Alloy;
import net.tfminecraft.advancedcrafting.objects.data.AlloyRecipe;

/**
* The alloy recipes each account has forged, as combo keys ({@code base|catalyst,catalyst}).
* A combo never changes when its alloy is named or renamed and is never reused, unlike alloy ids.
* Files live in {@code data/known-alloy-recipes/<uuid>.json}. A player without a file yet starts
* from the alloys {@link PlayerAlloyForgeTracker} has on record for them.
*/
public final class KnownAlloyRecipes {
private static KnownAlloyRecipes instance;

private final File folder;
private final Map<UUID, Set<String>> cache = new HashMap<>();
/** Accounts whose file could not be read; it is never overwritten this session. */
private final Set<UUID> unreadable = new HashSet<>();

public KnownAlloyRecipes(File dataFolder) {
this.folder = new File(dataFolder, "known-alloy-recipes");
if (!folder.exists()) {
folder.mkdirs();
}
}

public static void init(KnownAlloyRecipes known) {
instance = known;
}

public static KnownAlloyRecipes get() {
return instance;
}

/** Called for every successful forge (not scrap). No-op before the plugin has set an instance. */
public static void learn(UUID playerUuid, AlloyRecipe recipe) {
if (instance != null && playerUuid != null && recipe != null) {
instance.add(playerUuid, recipe.comboKey());
}
}

public boolean knows(UUID playerUuid, Alloy alloy) {
if (playerUuid == null || alloy == null || alloy.getData() == null) {
return false;
}
AlloyRecipe recipe = alloy.getData().getRecipe();
return recipe != null && load(playerUuid).contains(recipe.comboKey());
}

private void add(UUID playerUuid, String comboKey) {
Set<String> known = load(playerUuid);
if (known.add(comboKey) && !save(playerUuid, known)) {
// Not on disk, so the next forge of this combo tries again.
known.remove(comboKey);
}
}

private Set<String> load(UUID playerUuid) {
Set<String> known = cache.get(playerUuid);
if (known != null) {
return known;
}
known = new HashSet<>();
File file = file(playerUuid);
if (file.exists()) {
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)) {
Object parsed = new JSONParser().parse(reader);
if (parsed instanceof JSONArray array) {
for (Object entry : array) {
if (entry != null && !entry.toString().isBlank()) {
known.add(entry.toString().trim().toLowerCase(Locale.ROOT));
}
}
}
} catch (Exception ex) {
// Leave the file for staff to repair; this session works from memory only.
AdvancedCrafting.plugin.getLogger().warning("AC: could not read " + file.getPath() + ", leaving it unchanged: "
+ ex.getMessage());
unreadable.add(playerUuid);
cache.put(playerUuid, known);
return known;
}
} else if (seedFromForgeHistory(playerUuid, known)) {
save(playerUuid, known);
}
cache.put(playerUuid, known);
return known;
}

/** Recipes of the alloys this player forged before recipes were recorded. */
private boolean seedFromForgeHistory(UUID playerUuid, Set<String> known) {
PlayerAlloyForgeTracker tracker = CraftLifecycle.getTracker();
if (tracker == null) {
return false;
}
for (String alloyId : tracker.getForgedIds(playerUuid)) {
Alloy alloy = AlloyManager.getAlloyById(alloyId);
if (alloy != null && alloy.getData() != null && alloy.getData().getRecipe() != null) {
known.add(alloy.getData().getRecipe().comboKey());
}
}
return !known.isEmpty();
}

/** Writes a temp file and moves it over the old one, so a crash can't leave half a file. */
@SuppressWarnings("unchecked")
private boolean save(UUID playerUuid, Set<String> known) {
if (unreadable.contains(playerUuid)) {
return true;
}
List<String> sorted = new ArrayList<>(known);
sorted.sort(null);
JSONArray array = new JSONArray();
array.addAll(sorted);
Path target = file(playerUuid).toPath();
Path temp = target.resolveSibling(target.getFileName() + ".tmp");
try {
Files.createDirectories(folder.toPath());
Files.writeString(temp, array.toJSONString(), StandardCharsets.UTF_8);
try {
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException ex) {
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return true;
} catch (IOException ex) {
AdvancedCrafting.plugin.getLogger().warning("AC: could not save known alloy recipes for " + playerUuid
+ ": " + ex.getMessage());
return false;
}
}

private File file(UUID playerUuid) {
return new File(folder, playerUuid + ".json");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ public boolean recordForge(UUID playerUuid, String alloyId) {
return true;
}

/** The alloy ids this account has forged; a read-only copy. */
public Set<String> getForgedIds(UUID playerUuid) {
if (playerUuid == null) {
return Set.of();
}
return Set.copyOf(loadForgedIds(playerUuid));
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

private Set<String> loadForgedIds(UUID playerUuid) {
Set<String> cached = CACHE.get(playerUuid);
if (cached != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
package net.tfminecraft.advancedcrafting.managers;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.TreeSet;

import org.apache.commons.lang.WordUtils;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.tfminecraft.advancedcrafting.AdvancedCrafting;
import net.tfminecraft.advancedcrafting.lifecycle.KnownAlloyRecipes;
import net.tfminecraft.advancedcrafting.loaders.IngredientLoader;
import net.tfminecraft.advancedcrafting.objects.alloys.Alloy;
import net.tfminecraft.advancedcrafting.objects.data.AlloyRecipe;
import net.tfminecraft.advancedcrafting.objects.ingredients.Ingredient;
import net.tfminecraft.advancedcrafting.utils.AcItemTags;

/**
* {@code /alloy recipes} and {@code /alloy recipe [name]}: the base and catalysts of the alloys a
* player has forged. Only the ingredients are shown, never hits, stats or forge odds. An alloy the
* player has not forged gets the same reply whether or not it exists, so names can't be probed.
*/
final class AlloyRecipeCommand {
private static final LegacyComponentSerializer LEGACY = LegacyComponentSerializer.legacySection();

/** {@code /alloy recipes}: every alloy this account has forged, each name clickable. */
void list(Player p) {
List<Alloy> known = knownAlloys(p);
if (known.isEmpty()) {
p.sendMessage("§7You haven't forged any alloys yet. Forge one to keep its recipe here.");
return;
}
p.sendMessage("§6Alloys you have forged §7(" + known.size() + ")§6, click one for its recipe:");
Component line = Component.empty();
for (int i = 0; i < known.size(); i++) {
Alloy alloy = known.get(i);
if (i > 0) {
line = line.append(Component.text(", ", NamedTextColor.GRAY));
}
line = line.append(LEGACY.deserialize(alloy.getName())
.clickEvent(ClickEvent.runCommand("/alloy recipe " + alloy.getId()))
.hoverEvent(HoverEvent.showText(Component.text("Show the recipe", NamedTextColor.GRAY))));
}
p.sendMessage(line);
}

/** {@code /alloy recipe [name]}: the named alloy, or the alloy in the main hand. */
void show(Player p, String[] args) {
if (args.length < 2) {
showHeld(p);
return;
}
String typed = String.join(" ", java.util.Arrays.copyOfRange(args, 1, args.length));
String id = typed.replace(' ', '_').toLowerCase(Locale.ROOT);
Alloy alloy = AlloyManager.getAlloyById(id);
if (alloy == null || !knows(p, alloy)) {
p.sendMessage("§cYou don't know the recipe for §f" + typed + "§c.");
return;
}
sendRecipe(p, alloy);
}

private void showHeld(Player p) {
ItemStack held = p.getInventory().getItemInMainHand();
if (AcItemTags.getKind(held) != AcItemTags.Kind.ALLOY) {
p.sendMessage("§cHold an alloy, or use §f/alloy recipe <name>§c. §f/alloy recipes §clists the ones you know.");
return;
}
Alloy alloy = AlloyManager.getAlloyById(AcItemTags.getId(held));
if (alloy == null || !knows(p, alloy)) {
String name = held.getItemMeta().hasDisplayName() ? held.getItemMeta().getDisplayName() : "this alloy";
p.sendMessage("§cYou don't know the recipe for §f" + name + "§c. Forge it yourself to learn it.");
return;
}
sendRecipe(p, alloy);
}

private void sendRecipe(Player p, Alloy alloy) {
// knows() already required a recipe.
AlloyRecipe recipe = alloy.getData().getRecipe();
// The forge reads this index, so a combo that now makes something else must not be shown.
String result = AdvancedCrafting.getAlloyRecipeStore().getResultByCombo(recipe.comboKey());
if (!alloy.getId().equalsIgnoreCase(result)) {
p.sendMessage("§cThat recipe no longer makes §f" + alloy.getName() + "§c.");
return;
}
p.sendMessage("§6Recipe for §r" + alloy.getName());
p.sendMessage("§7Base: §r" + ingredientName(recipe.getBaseId()));
List<String> catalysts = new ArrayList<>();
for (String id : recipe.getCatalystIds()) {
catalysts.add(ingredientName(id));
}
p.sendMessage("§7Catalysts: §r" + (catalysts.isEmpty() ? "§fnone" : String.join("§7, §r", catalysts)));
p.sendMessage("§8Add the base to an alloy forge first, then the catalysts in any order.");
}

/** Tab completion for {@code /alloy recipe}: only alloys this player has forged. */
List<String> completions(Player p) {
List<String> ids = new ArrayList<>();
for (Alloy alloy : knownAlloys(p)) {
ids.add(alloy.getId());
}
return ids;
}

private List<Alloy> knownAlloys(Player p) {
List<Alloy> known = new ArrayList<>();
for (String id : new TreeSet<>(AlloyManager.getAlloyIds())) {
Alloy alloy = AlloyManager.getAlloyById(id);
if (knows(p, alloy)) {
known.add(alloy);
}
}
return known;
}

private boolean knows(Player p, Alloy alloy) {
KnownAlloyRecipes known = KnownAlloyRecipes.get();
return known != null && known.knows(p.getUniqueId(), alloy);
}

/** The ingredient's item name with its colour, or its id in title case if the item can't be built. */
static String ingredientName(String id) {
Ingredient ingredient = IngredientLoader.getByString(id);
if (ingredient != null) {
try {
// Ingredient.buildTo always gives the item a display name.
return ingredient.build().getItemMeta().getDisplayName();
} catch (RuntimeException ex) {
// The item source (MMOItems, ItemsAdder) may be missing; fall back to the id.
}
}
return "§f" + WordUtils.capitalize(id.replace('_', ' '));
}
}
Loading
Loading