Simplify ingredient matching and clean up source and config comments
This commit is contained in:
@@ -1,5 +1,8 @@
|
|||||||
package online.astradev.soups;
|
package online.astradev.soups;
|
||||||
|
|
||||||
|
import net.kyori.adventure.text.Component;
|
||||||
|
import net.kyori.adventure.text.format.NamedTextColor;
|
||||||
|
|
||||||
import org.bukkit.*;
|
import org.bukkit.*;
|
||||||
import org.bukkit.block.Block;
|
import org.bukkit.block.Block;
|
||||||
import org.bukkit.block.data.Levelled;
|
import org.bukkit.block.data.Levelled;
|
||||||
@@ -20,8 +23,6 @@ import org.bukkit.plugin.java.JavaPlugin;
|
|||||||
import org.bukkit.util.Transformation;
|
import org.bukkit.util.Transformation;
|
||||||
import org.joml.Quaternionf;
|
import org.joml.Quaternionf;
|
||||||
import org.joml.Vector3f;
|
import org.joml.Vector3f;
|
||||||
import net.kyori.adventure.text.Component;
|
|
||||||
import net.kyori.adventure.text.format.NamedTextColor;
|
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.nio.file.*;
|
import java.nio.file.*;
|
||||||
@@ -38,25 +39,46 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
private int ticks;
|
private int ticks;
|
||||||
|
|
||||||
record Position(UUID world, int x, int y, int z) {
|
record Position(UUID world, int x, int y, int z) {
|
||||||
static Position at(Block b) { return new Position(b.getWorld().getUID(), b.getX(), b.getY(), b.getZ()); }
|
static Position at(Block b) {
|
||||||
|
return new Position(b.getWorld().getUID(), b.getX(), b.getY(), b.getZ());
|
||||||
|
}
|
||||||
|
|
||||||
Block loadedBlock() {
|
Block loadedBlock() {
|
||||||
World w = Bukkit.getWorld(world);
|
World w = Bukkit.getWorld(world);
|
||||||
return w == null || !w.isChunkLoaded(x >> 4, z >> 4) ? null : w.getBlockAt(x, y, z);
|
return w == null || !w.isChunkLoaded(x >> 4, z >> 4) ? null : w.getBlockAt(x, y, z);
|
||||||
}
|
}
|
||||||
String id() { return world + "," + x + "," + y + "," + z; }
|
|
||||||
|
String id() {
|
||||||
|
return world + "," + x + "," + y + "," + z;
|
||||||
|
}
|
||||||
|
|
||||||
static Position parse(String s) {
|
static Position parse(String s) {
|
||||||
String[] p = s.split(",");
|
String[] p = s.split(",");
|
||||||
if (p.length != 4) throw new IllegalArgumentException("Invalid cauldron position " + s);
|
if (p.length != 4) throw new IllegalArgumentException("Invalid cauldron position " + s);
|
||||||
return new Position(UUID.fromString(p[0]), Integer.parseInt(p[1]), Integer.parseInt(p[2]), Integer.parseInt(p[3]));
|
return new Position(
|
||||||
|
UUID.fromString(p[0]),
|
||||||
|
Integer.parseInt(p[1]),
|
||||||
|
Integer.parseInt(p[2]),
|
||||||
|
Integer.parseInt(p[3]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
record Pot(List<ItemStack> items, ItemStack soup, int brewTicks, int servings, int capacity) {
|
|
||||||
Pot { items = List.copyOf(items); }
|
|
||||||
Pot(List<ItemStack> items, ItemStack soup) { this(items, soup, 0, soup == null ? 0 : 1, soup == null ? 0 : 1); }
|
|
||||||
boolean brewing() { return brewTicks > 0; }
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override public void onEnable() {
|
record Pot(List<ItemStack> items, ItemStack soup, int brewTicks, int servings, int capacity) {
|
||||||
|
Pot {
|
||||||
|
items = List.copyOf(items);
|
||||||
|
}
|
||||||
|
|
||||||
|
Pot(List<ItemStack> items, ItemStack soup) {
|
||||||
|
this(items, soup, 0, soup == null ? 0 : 1, soup == null ? 0 : 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean brewing() {
|
||||||
|
return brewTicks > 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onEnable() {
|
||||||
pots.clear();
|
pots.clear();
|
||||||
brewElapsed.clear();
|
brewElapsed.clear();
|
||||||
ticks = 0;
|
ticks = 0;
|
||||||
@@ -66,17 +88,23 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
saveDefaultConfig();
|
saveDefaultConfig();
|
||||||
dataFile = new File(getDataFolder(), "cauldrons.yml");
|
dataFile = new File(getDataFolder(), "cauldrons.yml");
|
||||||
try {
|
try {
|
||||||
// Unlike loadConfiguration(), load() reports malformed YAML instead of silently using defaults.
|
// Unlike loadConfiguration(), load() reports malformed YAML instead of silently using
|
||||||
|
// defaults.
|
||||||
new YamlConfiguration().load(new File(getDataFolder(), "config.yml"));
|
new YamlConfiguration().load(new File(getDataFolder(), "config.yml"));
|
||||||
ingredients = new Ingredients(this);
|
ingredients = new Ingredients(this);
|
||||||
loadPots();
|
loadPots();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
getLogger().log(Level.SEVERE, "Не удалось прочитать конфигурацию/котлы; данные оставлены без изменений", e);
|
getLogger()
|
||||||
|
.log(
|
||||||
|
Level.SEVERE,
|
||||||
|
"Не удалось прочитать конфигурацию/котлы; данные оставлены без изменений",
|
||||||
|
e);
|
||||||
Bukkit.getPluginManager().disablePlugin(this);
|
Bukkit.getPluginManager().disablePlugin(this);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Bukkit.getPluginManager().registerEvents(this, this);
|
Bukkit.getPluginManager().registerEvents(this, this);
|
||||||
for (World world : Bukkit.getWorlds()) for (Entity entity : world.getEntities()) {
|
for (World world : Bukkit.getWorlds())
|
||||||
|
for (Entity entity : world.getEntities()) {
|
||||||
if (isVisual(entity)) entity.remove();
|
if (isVisual(entity)) entity.remove();
|
||||||
else if (entity instanceof Item item) normalizeEntity(item);
|
else if (entity instanceof Item item) normalizeEntity(item);
|
||||||
}
|
}
|
||||||
@@ -85,35 +113,51 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
getLogger().info("AstraSoups: загружено котлов: " + pots.size());
|
getLogger().info("AstraSoups: загружено котлов: " + pots.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override public void onDisable() {
|
@Override
|
||||||
|
public void onDisable() {
|
||||||
for (Position pos : new ArrayList<>(visuals.keySet())) removeVisuals(pos);
|
for (Position pos : new ArrayList<>(visuals.keySet())) removeVisuals(pos);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Ingredients ingredients() { return ingredients; }
|
public Ingredients ingredients() {
|
||||||
|
return ingredients;
|
||||||
|
}
|
||||||
|
|
||||||
private void loadPots() throws Exception {
|
private void loadPots() throws Exception {
|
||||||
if (!dataFile.exists()) return;
|
if (!dataFile.exists()) return;
|
||||||
YamlConfiguration data = new YamlConfiguration();
|
YamlConfiguration data = new YamlConfiguration();
|
||||||
data.load(dataFile);
|
data.load(dataFile);
|
||||||
ConfigurationSection section = data.getConfigurationSection("cauldrons");
|
ConfigurationSection section = data.getConfigurationSection("cauldrons");
|
||||||
if (section == null && !data.getKeys(false).isEmpty()) throw new IllegalArgumentException("Invalid cauldrons.yml");
|
if (section == null && !data.getKeys(false).isEmpty())
|
||||||
|
throw new IllegalArgumentException("Invalid cauldrons.yml");
|
||||||
if (section == null) return;
|
if (section == null) return;
|
||||||
for (String id : section.getKeys(false)) {
|
for (String id : section.getKeys(false)) {
|
||||||
ConfigurationSection c = Objects.requireNonNull(section.getConfigurationSection(id));
|
ConfigurationSection c = Objects.requireNonNull(section.getConfigurationSection(id));
|
||||||
List<ItemStack> items = new ArrayList<>();
|
List<ItemStack> items = new ArrayList<>();
|
||||||
for (Object value : c.getList("items", List.of())) {
|
for (Object value : c.getList("items", List.of())) {
|
||||||
if (!(value instanceof ItemStack item) || item.getAmount() != 1 || item.getType().isAir()) throw new IllegalArgumentException("Invalid ingredient at " + id);
|
if (!(value instanceof ItemStack item)
|
||||||
|
|| item.getAmount() != 1
|
||||||
|
|| item.getType().isAir())
|
||||||
|
throw new IllegalArgumentException("Invalid ingredient at " + id);
|
||||||
items.add(item);
|
items.add(item);
|
||||||
}
|
}
|
||||||
ItemStack soup = c.getItemStack("soup");
|
ItemStack soup = c.getItemStack("soup");
|
||||||
int brewTicks = c.getInt("brew-ticks", 0);
|
int brewTicks = c.getInt("brew-ticks", 0);
|
||||||
int servings = c.getInt("servings", soup == null ? 0 : 1);
|
int servings = c.getInt("servings", soup == null ? 0 : 1);
|
||||||
int capacity = c.getInt("capacity", soup == null ? 0 : Math.max(servings, getConfig().getInt("servings-per-brew", 4)));
|
int capacity =
|
||||||
if (items.size() > 4 || brewTicks < 0 || brewTicks > 1200
|
c.getInt(
|
||||||
|
"capacity",
|
||||||
|
soup == null
|
||||||
|
? 0
|
||||||
|
: Math.max(
|
||||||
|
servings, getConfig().getInt("servings-per-brew", 4)));
|
||||||
|
if (items.size() > 4
|
||||||
|
|| brewTicks < 0
|
||||||
|
|| brewTicks > 1200
|
||||||
|| (soup == null ? capacity != 0 : capacity < servings || capacity > 16)
|
|| (soup == null ? capacity != 0 : capacity < servings || capacity > 16)
|
||||||
|| (soup == null ? servings != 0 : servings < 1 || servings > 16)
|
|| (soup == null ? servings != 0 : servings < 1 || servings > 16)
|
||||||
|| (soup != null && (soup.getAmount() != 1 || !ingredients.isCombined(soup)))
|
|| (soup != null && (soup.getAmount() != 1 || !ingredients.isCombined(soup)))
|
||||||
|| (brewTicks > 0 ? items.size() != 4 || soup == null
|
|| (brewTicks > 0
|
||||||
|
? items.size() != 4 || soup == null
|
||||||
: (soup != null ? !items.isEmpty() : items.isEmpty()))) {
|
: (soup != null ? !items.isEmpty() : items.isEmpty()))) {
|
||||||
throw new IllegalArgumentException("Invalid cauldron at " + id);
|
throw new IllegalArgumentException("Invalid cauldron at " + id);
|
||||||
}
|
}
|
||||||
@@ -124,7 +168,8 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
/** Save before transferring real items. A failed save rolls back the in-memory change. */
|
/** Save before transferring real items. A failed save rolls back the in-memory change. */
|
||||||
private boolean change(Position pos, Pot next) {
|
private boolean change(Position pos, Pot next) {
|
||||||
Pot old = pots.get(pos);
|
Pot old = pots.get(pos);
|
||||||
if (next == null) pots.remove(pos); else pots.put(pos, next);
|
if (next == null) pots.remove(pos);
|
||||||
|
else pots.put(pos, next);
|
||||||
try {
|
try {
|
||||||
YamlConfiguration data = new YamlConfiguration();
|
YamlConfiguration data = new YamlConfiguration();
|
||||||
data.createSection("cauldrons");
|
data.createSection("cauldrons");
|
||||||
@@ -132,20 +177,31 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
String prefix = "cauldrons." + entry.getKey().id();
|
String prefix = "cauldrons." + entry.getKey().id();
|
||||||
data.set(prefix + ".items", entry.getValue().items);
|
data.set(prefix + ".items", entry.getValue().items);
|
||||||
data.set(prefix + ".soup", entry.getValue().soup);
|
data.set(prefix + ".soup", entry.getValue().soup);
|
||||||
if (entry.getValue().brewing()) data.set(prefix + ".brew-ticks", entry.getValue().brewTicks);
|
if (entry.getValue().brewing())
|
||||||
if (entry.getValue().soup != null) data.set(prefix + ".servings", entry.getValue().servings);
|
data.set(prefix + ".brew-ticks", entry.getValue().brewTicks);
|
||||||
if (entry.getValue().soup != null) data.set(prefix + ".capacity", entry.getValue().capacity);
|
if (entry.getValue().soup != null)
|
||||||
|
data.set(prefix + ".servings", entry.getValue().servings);
|
||||||
|
if (entry.getValue().soup != null)
|
||||||
|
data.set(prefix + ".capacity", entry.getValue().capacity);
|
||||||
}
|
}
|
||||||
Path temp = dataFile.toPath().resolveSibling("cauldrons.yml.tmp");
|
Path temp = dataFile.toPath().resolveSibling("cauldrons.yml.tmp");
|
||||||
Files.writeString(temp, data.saveToString());
|
Files.writeString(temp, data.saveToString());
|
||||||
try { Files.move(temp, dataFile.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
|
try {
|
||||||
catch (AtomicMoveNotSupportedException e) { Files.move(temp, dataFile.toPath(), StandardCopyOption.REPLACE_EXISTING); }
|
Files.move(
|
||||||
|
temp,
|
||||||
|
dataFile.toPath(),
|
||||||
|
StandardCopyOption.ATOMIC_MOVE,
|
||||||
|
StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
} catch (AtomicMoveNotSupportedException e) {
|
||||||
|
Files.move(temp, dataFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
}
|
||||||
// Keep the same visuals when starting a brew or taking a portion: no respawn flash.
|
// Keep the same visuals when starting a brew or taking a portion: no respawn flash.
|
||||||
if (old == null || next == null || !old.items.equals(next.items)) removeVisuals(pos);
|
if (old == null || next == null || !old.items.equals(next.items)) removeVisuals(pos);
|
||||||
brewElapsed.remove(pos);
|
brewElapsed.remove(pos);
|
||||||
return true;
|
return true;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
if (old == null) pots.remove(pos); else pots.put(pos, old);
|
if (old == null) pots.remove(pos);
|
||||||
|
else pots.put(pos, old);
|
||||||
getLogger().log(Level.SEVERE, "Ошибка сохранения котла; действие отменено", e);
|
getLogger().log(Level.SEVERE, "Ошибка сохранения котла; действие отменено", e);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -153,7 +209,8 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST)
|
@EventHandler(priority = EventPriority.HIGHEST)
|
||||||
public void interact(PlayerInteractEvent event) {
|
public void interact(PlayerInteractEvent event) {
|
||||||
if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getClickedBlock() == null) return;
|
if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getClickedBlock() == null)
|
||||||
|
return;
|
||||||
Block block = event.getClickedBlock();
|
Block block = event.getClickedBlock();
|
||||||
Position pos = Position.at(block);
|
Position pos = Position.at(block);
|
||||||
Pot pot = pots.get(pos);
|
Pot pot = pots.get(pos);
|
||||||
@@ -161,10 +218,12 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
if (pot != null) event.setCancelled(true);
|
if (pot != null) event.setCancelled(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (event.useInteractedBlock() == Event.Result.DENY || event.useItemInHand() == Event.Result.DENY) return;
|
if (event.useInteractedBlock() == Event.Result.DENY
|
||||||
|
|| event.useItemInHand() == Event.Result.DENY) return;
|
||||||
if (!validBlock(block, pot)) return;
|
if (!validBlock(block, pot)) return;
|
||||||
Player player = event.getPlayer();
|
Player player = event.getPlayer();
|
||||||
if (!player.hasPermission("astrasoups.use") || player.getGameMode() == GameMode.SPECTATOR) return;
|
if (!player.hasPermission("astrasoups.use") || player.getGameMode() == GameMode.SPECTATOR)
|
||||||
|
return;
|
||||||
ItemStack held = player.getInventory().getItemInMainHand();
|
ItemStack held = player.getInventory().getItemInMainHand();
|
||||||
boolean empty = held.getType().isAir();
|
boolean empty = held.getType().isAir();
|
||||||
boolean bowl = held.getType() == Material.BOWL;
|
boolean bowl = held.getType() == Material.BOWL;
|
||||||
@@ -172,37 +231,63 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
event.setCancelled(true);
|
event.setCancelled(true);
|
||||||
if (pot == null) {
|
if (pot == null) {
|
||||||
if (getConfig().getBoolean("require-full-water", true)
|
if (getConfig().getBoolean("require-full-water", true)
|
||||||
&& block.getBlockData() instanceof Levelled level && level.getLevel() != level.getMaximumLevel()) {
|
&& block.getBlockData() instanceof Levelled level
|
||||||
say(player, "Сначала наполните котёл водой доверху."); return;
|
&& level.getLevel() != level.getMaximumLevel()) {
|
||||||
|
say(player, "Сначала наполните котёл водой доверху.");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
pot = new Pot(List.of(), null);
|
pot = new Pot(List.of(), null);
|
||||||
}
|
}
|
||||||
if (pot.brewing()) {
|
if (pot.brewing()) {
|
||||||
int remaining = Math.max(1, (pot.brewTicks - brewElapsed.getOrDefault(pos, 0) + 19) / 20);
|
int remaining =
|
||||||
|
Math.max(1, (pot.brewTicks - brewElapsed.getOrDefault(pos, 0) + 19) / 20);
|
||||||
say(player, "Суп варится… Осталось: " + remaining + " с.");
|
say(player, "Суп варится… Осталось: " + remaining + " с.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (pot.soup != null) {
|
if (pot.soup != null) {
|
||||||
if (!bowl) { say(player, "Суп готов. Порций: " + pot.servings + ". Возьмите его миской — ПКМ."); return; }
|
if (!bowl) {
|
||||||
|
say(player, "Суп готов. Порций: " + pot.servings + ". Возьмите его миской — ПКМ.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
ItemStack result = pot.soup.clone();
|
ItemStack result = pot.soup.clone();
|
||||||
int remaining = pot.servings - 1;
|
int remaining = pot.servings - 1;
|
||||||
if (!change(pos, remaining == 0 ? null : new Pot(List.of(), pot.soup, 0, remaining, pot.capacity))) { saveError(player); return; }
|
if (!change(
|
||||||
|
pos,
|
||||||
|
remaining == 0
|
||||||
|
? null
|
||||||
|
: new Pot(List.of(), pot.soup, 0, remaining, pot.capacity))) {
|
||||||
|
saveError(player);
|
||||||
|
return;
|
||||||
|
}
|
||||||
takeOne(player);
|
takeOne(player);
|
||||||
give(player, result);
|
give(player, result);
|
||||||
if (remaining == 0) block.setType(Material.CAULDRON);
|
if (remaining == 0) block.setType(Material.CAULDRON);
|
||||||
else { syncWater(block, pots.get(pos)); show(pos, pots.get(pos), block); }
|
else {
|
||||||
|
syncWater(block, pots.get(pos));
|
||||||
|
show(pos, pots.get(pos), block);
|
||||||
|
}
|
||||||
block.getWorld().playSound(block.getLocation(), Sound.ITEM_BOTTLE_FILL, 0.8f, 0.7f);
|
block.getWorld().playSound(block.getLocation(), Sound.ITEM_BOTTLE_FILL, 0.8f, 0.7f);
|
||||||
say(player, remaining == 0 ? "Последняя порция собрана. Котёл пуст." : "Осталось порций: " + remaining + ".");
|
say(
|
||||||
|
player,
|
||||||
|
remaining == 0
|
||||||
|
? "Последняя порция собрана. Котёл пуст."
|
||||||
|
: "Осталось порций: " + remaining + ".");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
boolean cook = pot.items.size() == 4 && (player.isSneaking() || !empty);
|
boolean cook = pot.items.size() == 4 && (player.isSneaking() || !empty);
|
||||||
if (cook) {
|
if (cook) {
|
||||||
String error = ingredients.rejection(pot.items);
|
String error = ingredients.rejection(pot.items);
|
||||||
if (error != null) { say(player, error + " ПКМ пустой рукой возвращает последний ингредиент."); return; }
|
if (error != null) {
|
||||||
|
say(player, error + " ПКМ пустой рукой возвращает последний ингредиент.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
ItemStack soup = ingredients.brew(pot.items);
|
ItemStack soup = ingredients.brew(pot.items);
|
||||||
int duration = (int) Math.round(getConfig().getDouble("brew-seconds", 4.0) * 20);
|
int duration = (int) Math.round(getConfig().getDouble("brew-seconds", 4.0) * 20);
|
||||||
int capacity = getConfig().getInt("servings-per-brew", 4);
|
int capacity = getConfig().getInt("servings-per-brew", 4);
|
||||||
if (!change(pos, new Pot(pot.items, soup, duration, capacity, capacity))) { saveError(player); return; }
|
if (!change(pos, new Pot(pot.items, soup, duration, capacity, capacity))) {
|
||||||
|
saveError(player);
|
||||||
|
return;
|
||||||
|
}
|
||||||
show(pos, pots.get(pos), block);
|
show(pos, pots.get(pos), block);
|
||||||
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_BREWING_STAND_BREW, 1, 1);
|
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_BREWING_STAND_BREW, 1, 1);
|
||||||
say(player, "Варка началась! Дождитесь окончания водоворота.");
|
say(player, "Варка началась! Дождитесь окончания водоворота.");
|
||||||
@@ -212,20 +297,39 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
if (pot.items.isEmpty()) return;
|
if (pot.items.isEmpty()) return;
|
||||||
List<ItemStack> remaining = new ArrayList<>(pot.items);
|
List<ItemStack> remaining = new ArrayList<>(pot.items);
|
||||||
ItemStack last = remaining.removeLast();
|
ItemStack last = remaining.removeLast();
|
||||||
if (!change(pos, remaining.isEmpty() ? null : new Pot(remaining, null))) { saveError(player); return; }
|
if (!change(pos, remaining.isEmpty() ? null : new Pot(remaining, null))) {
|
||||||
|
saveError(player);
|
||||||
|
return;
|
||||||
|
}
|
||||||
give(player, last.clone());
|
give(player, last.clone());
|
||||||
say(player, "Возвращён последний ингредиент. В котле: " + remaining.size() + "/4.");
|
say(player, "Возвращён последний ингредиент. В котле: " + remaining.size() + "/4.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (pot.items.size() == 4) { say(player, "Для варки: Shift+ПКМ или ПКМ с предметом в руке."); return; }
|
if (pot.items.size() == 4) {
|
||||||
if (ingredients.read(held) == null) { say(player, "Добавьте еду или зелье. В котле: " + pot.items.size() + "/4."); return; }
|
say(player, "Для варки: Shift+ПКМ или ПКМ с предметом в руке.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (ingredients.read(held) == null) {
|
||||||
|
say(player, "Добавьте еду или зелье. В котле: " + pot.items.size() + "/4.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
List<ItemStack> items = new ArrayList<>(pot.items);
|
List<ItemStack> items = new ArrayList<>(pot.items);
|
||||||
items.add(held.asOne());
|
items.add(held.asOne());
|
||||||
if (!change(pos, new Pot(items, null))) { saveError(player); return; }
|
if (!change(pos, new Pot(items, null))) {
|
||||||
|
saveError(player);
|
||||||
|
return;
|
||||||
|
}
|
||||||
takeOne(player);
|
takeOne(player);
|
||||||
show(pos, pots.get(pos), block);
|
show(pos, pots.get(pos), block);
|
||||||
block.getWorld().playSound(block.getLocation(), Sound.ENTITY_GENERIC_SPLASH, .3f, 1.6f);
|
block.getWorld().playSound(block.getLocation(), Sound.ENTITY_GENERIC_SPLASH, .3f, 1.6f);
|
||||||
say(player, "Ингредиенты: " + items.size() + "/4." + (items.size() == 4 ? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний." : ""));
|
say(
|
||||||
|
player,
|
||||||
|
"Ингредиенты: "
|
||||||
|
+ items.size()
|
||||||
|
+ "/4."
|
||||||
|
+ (items.size() == 4
|
||||||
|
? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний."
|
||||||
|
: ""));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void takeOne(Player p) {
|
private void takeOne(Player p) {
|
||||||
@@ -233,57 +337,105 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
ItemStack held = p.getInventory().getItemInMainHand();
|
ItemStack held = p.getInventory().getItemInMainHand();
|
||||||
p.getInventory().setItemInMainHand(held.getAmount() == 1 ? null : held.subtract(1));
|
p.getInventory().setItemInMainHand(held.getAmount() == 1 ? null : held.subtract(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void give(Player p, ItemStack item) {
|
private void give(Player p, ItemStack item) {
|
||||||
Ingredients.normalize(item);
|
Ingredients.normalize(item);
|
||||||
p.getInventory().addItem(item).values().forEach(left -> p.getWorld().dropItemNaturally(p.getLocation(), left));
|
p.getInventory()
|
||||||
|
.addItem(item)
|
||||||
|
.values()
|
||||||
|
.forEach(left -> p.getWorld().dropItemNaturally(p.getLocation(), left));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void say(Player p, String text) {
|
||||||
|
p.sendActionBar(Component.text(text, NamedTextColor.GOLD));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void saveError(Player p) {
|
||||||
|
say(p, "Не удалось сохранить котёл. Обратитесь к администратору.");
|
||||||
}
|
}
|
||||||
private void say(Player p, String text) { p.sendActionBar(Component.text(text, NamedTextColor.GOLD)); }
|
|
||||||
private void saveError(Player p) { say(p, "Не удалось сохранить котёл. Обратитесь к администратору."); }
|
|
||||||
|
|
||||||
private void refresh() {
|
private void refresh() {
|
||||||
ticks++;
|
ticks++;
|
||||||
for (Map.Entry<Position, Pot> entry : new ArrayList<>(pots.entrySet())) {
|
for (Map.Entry<Position, Pot> entry : new ArrayList<>(pots.entrySet())) {
|
||||||
Position pos = entry.getKey();
|
Position pos = entry.getKey();
|
||||||
Block block = pos.loadedBlock();
|
Block block = pos.loadedBlock();
|
||||||
if (block == null) { removeVisuals(pos); continue; }
|
if (block == null) {
|
||||||
|
removeVisuals(pos);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (!validBlock(block, entry.getValue())) {
|
if (!validBlock(block, entry.getValue())) {
|
||||||
// External block editing: return raw ingredients only once, never resurrect a missing block.
|
// External block editing: return raw ingredients only once, never resurrect a
|
||||||
if (change(pos, null)) for (ItemStack item : entry.getValue().items) block.getWorld().dropItemNaturally(block.getLocation().add(.5, .5, .5), item.clone());
|
// missing block.
|
||||||
|
if (change(pos, null))
|
||||||
|
for (ItemStack item : entry.getValue().items)
|
||||||
|
block.getWorld()
|
||||||
|
.dropItemNaturally(
|
||||||
|
block.getLocation().add(.5, .5, .5), item.clone());
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
Pot pot = entry.getValue();
|
Pot pot = entry.getValue();
|
||||||
if (pot.brewing()) {
|
if (pot.brewing()) {
|
||||||
int elapsed = brewElapsed.merge(pos, 1, Integer::sum);
|
int elapsed = brewElapsed.merge(pos, 1, Integer::sum);
|
||||||
// On a save failure keep ingredients locked and retry once per second.
|
// On a save failure keep ingredients locked and retry once per second.
|
||||||
if (elapsed >= pot.brewTicks && (elapsed - pot.brewTicks) % 20 == 0
|
if (elapsed >= pot.brewTicks
|
||||||
&& change(pos, new Pot(List.of(), pot.soup, 0, pot.servings, pot.capacity))) {
|
&& (elapsed - pot.brewTicks) % 20 == 0
|
||||||
|
&& change(
|
||||||
|
pos, new Pot(List.of(), pot.soup, 0, pot.servings, pot.capacity))) {
|
||||||
syncWater(block, pots.get(pos));
|
syncWater(block, pots.get(pos));
|
||||||
show(pos, pots.get(pos), block);
|
show(pos, pots.get(pos), block);
|
||||||
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_BUBBLE_COLUMN_BUBBLE_POP, .8f, 1.2f);
|
block.getWorld()
|
||||||
block.getWorld().spawnParticle(Particle.CLOUD, block.getLocation().add(.5, 1.05, .5), 12, .2, .12, .2, .01);
|
.playSound(
|
||||||
|
block.getLocation(),
|
||||||
|
Sound.BLOCK_BUBBLE_COLUMN_BUBBLE_POP,
|
||||||
|
.8f,
|
||||||
|
1.2f);
|
||||||
|
block.getWorld()
|
||||||
|
.spawnParticle(
|
||||||
|
Particle.CLOUD,
|
||||||
|
block.getLocation().add(.5, 1.05, .5),
|
||||||
|
12,
|
||||||
|
.2,
|
||||||
|
.12,
|
||||||
|
.2,
|
||||||
|
.01);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (pot.soup != null && !pot.brewing()) syncWater(block, pot);
|
if (pot.soup != null && !pot.brewing()) syncWater(block, pot);
|
||||||
List<Entity> entities = visuals.get(pos);
|
List<Entity> entities = visuals.get(pos);
|
||||||
if (entities == null || entities.stream().anyMatch(e -> !e.isValid())) {
|
if (entities == null || entities.stream().anyMatch(e -> !e.isValid())) {
|
||||||
removeVisuals(pos); show(pos, entry.getValue(), block);
|
removeVisuals(pos);
|
||||||
|
show(pos, entry.getValue(), block);
|
||||||
} else {
|
} else {
|
||||||
for (int i = 0; i < entities.size(); i++) if (entities.get(i) instanceof ItemDisplay item && ticks % 2 == 0) {
|
for (int i = 0; i < entities.size(); i++)
|
||||||
// Client interpolates the local transform; the entity itself never teleports.
|
if (entities.get(i) instanceof ItemDisplay item && ticks % 2 == 0) {
|
||||||
|
// Client interpolates the local transform; the entity itself never
|
||||||
|
// teleports.
|
||||||
item.setInterpolationDelay(0);
|
item.setInterpolationDelay(0);
|
||||||
item.setTransformation(itemTransform(block, i, pot, 2));
|
item.setTransformation(itemTransform(block, i, pot, 2));
|
||||||
if (pot.brewing() && ticks % 5 == 0) {
|
if (pot.brewing() && ticks % 5 == 0) {
|
||||||
Vector3f offset = item.getTransformation().getTranslation();
|
Vector3f offset = item.getTransformation().getTranslation();
|
||||||
double height = .375 + .1875 * ((Levelled) block.getBlockData()).getLevel();
|
double height =
|
||||||
block.getWorld().spawnParticle(Particle.SPLASH,
|
.375 + .1875 * ((Levelled) block.getBlockData()).getLevel();
|
||||||
block.getLocation().add(.5 + offset.x, height + .01, .5 + offset.z),
|
block.getWorld()
|
||||||
1, .015, 0, .015, 0);
|
.spawnParticle(
|
||||||
|
Particle.SPLASH,
|
||||||
|
block.getLocation()
|
||||||
|
.add(
|
||||||
|
.5 + offset.x,
|
||||||
|
height + .01,
|
||||||
|
.5 + offset.z),
|
||||||
|
1,
|
||||||
|
.015,
|
||||||
|
0,
|
||||||
|
.015,
|
||||||
|
0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (ticks % 20 == 0) for (Player player : Bukkit.getOnlinePlayers()) {
|
if (ticks % 20 == 0)
|
||||||
|
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||||
normalizeInventory(player.getInventory());
|
normalizeInventory(player.getInventory());
|
||||||
normalizeInventory(player.getOpenInventory().getTopInventory());
|
normalizeInventory(player.getOpenInventory().getTopInventory());
|
||||||
ItemStack cursor = player.getItemOnCursor();
|
ItemStack cursor = player.getItemOnCursor();
|
||||||
@@ -293,35 +445,61 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
|
|
||||||
private boolean validBlock(Block block, Pot pot) {
|
private boolean validBlock(Block block, Pot pot) {
|
||||||
return block.getType() == Material.WATER_CAULDRON
|
return block.getType() == Material.WATER_CAULDRON
|
||||||
|| (block.getType() == Material.CAULDRON && pot != null && pot.soup != null && !pot.brewing());
|
|| (block.getType() == Material.CAULDRON
|
||||||
|
&& pot != null
|
||||||
|
&& pot.soup != null
|
||||||
|
&& !pot.brewing());
|
||||||
}
|
}
|
||||||
|
|
||||||
private void syncWater(Block block, Pot pot) {
|
private void syncWater(Block block, Pot pot) {
|
||||||
int level = CauldronAnimation.waterLevel(pot.servings, pot.capacity);
|
int level = CauldronAnimation.waterLevel(pot.servings, pot.capacity);
|
||||||
if (level == 0) { if (block.getType() != Material.CAULDRON) block.setType(Material.CAULDRON); }
|
if (level == 0) {
|
||||||
else {
|
if (block.getType() != Material.CAULDRON) block.setType(Material.CAULDRON);
|
||||||
|
} else {
|
||||||
if (block.getType() != Material.WATER_CAULDRON) block.setType(Material.WATER_CAULDRON);
|
if (block.getType() != Material.WATER_CAULDRON) block.setType(Material.WATER_CAULDRON);
|
||||||
Levelled water = (Levelled) block.getBlockData();
|
Levelled water = (Levelled) block.getBlockData();
|
||||||
if (water.getLevel() != level) { water.setLevel(level); block.setBlockData(water); }
|
if (water.getLevel() != level) {
|
||||||
|
water.setLevel(level);
|
||||||
|
block.setBlockData(water);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private Transformation itemTransform(Block block, int i, Pot pot, int ahead) {
|
private Transformation itemTransform(Block block, int i, Pot pot, int ahead) {
|
||||||
int waterLevel = block.getBlockData() instanceof Levelled l ? l.getLevel() : 3;
|
int waterLevel = block.getBlockData() instanceof Levelled l ? l.getLevel() : 3;
|
||||||
CauldronAnimation.Offset frame = CauldronAnimation.frame(i, waterLevel, ticks + ahead,
|
CauldronAnimation.Offset frame =
|
||||||
brewElapsed.getOrDefault(Position.at(block), 0) + ahead, pot.brewTicks);
|
CauldronAnimation.frame(
|
||||||
return new Transformation(new Vector3f((float) frame.x() - .5f, (float) frame.y() - .5f, (float) frame.z() - .5f),
|
i,
|
||||||
new Quaternionf(), new Vector3f(.3f), new Quaternionf().rotationY((ticks + ahead) * .035f + i));
|
waterLevel,
|
||||||
|
ticks + ahead,
|
||||||
|
brewElapsed.getOrDefault(Position.at(block), 0) + ahead,
|
||||||
|
pot.brewTicks);
|
||||||
|
return new Transformation(
|
||||||
|
new Vector3f(
|
||||||
|
(float) frame.x() - .5f, (float) frame.y() - .5f, (float) frame.z() - .5f),
|
||||||
|
new Quaternionf(),
|
||||||
|
new Vector3f(.3f),
|
||||||
|
new Quaternionf().rotationY((ticks + ahead) * .035f + i));
|
||||||
}
|
}
|
||||||
|
|
||||||
private Transformation liquidTransform(Pot pot) {
|
private Transformation liquidTransform(Pot pot) {
|
||||||
return new Transformation(new Vector3f(-.075f, (float) CauldronAnimation.liquidHeight(pot.servings, pot.capacity) + .005f - .5f, .375f),
|
return new Transformation(
|
||||||
new Quaternionf().rotationX((float) (-Math.PI / 2)), new Vector3f(6, 3, 1), new Quaternionf());
|
new Vector3f(
|
||||||
|
-.075f,
|
||||||
|
(float) CauldronAnimation.liquidHeight(pot.servings, pot.capacity)
|
||||||
|
+ .005f
|
||||||
|
- .5f,
|
||||||
|
.375f),
|
||||||
|
new Quaternionf().rotationX((float) (-Math.PI / 2)),
|
||||||
|
new Vector3f(6, 3, 1),
|
||||||
|
new Quaternionf());
|
||||||
}
|
}
|
||||||
|
|
||||||
private void show(Position pos, Pot pot, Block block) {
|
private void show(Position pos, Pot pot, Block block) {
|
||||||
if (visuals.containsKey(pos)) {
|
if (visuals.containsKey(pos)) {
|
||||||
if (pot.soup != null && !pot.brewing()) for (Entity entity : visuals.get(pos)) if (entity instanceof TextDisplay display) {
|
if (pot.soup != null && !pot.brewing())
|
||||||
|
for (Entity entity : visuals.get(pos))
|
||||||
|
if (entity instanceof TextDisplay display) {
|
||||||
display.setInterpolationDelay(0);
|
display.setInterpolationDelay(0);
|
||||||
display.setTransformation(liquidTransform(pot));
|
display.setTransformation(liquidTransform(pot));
|
||||||
}
|
}
|
||||||
@@ -330,12 +508,27 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
List<Entity> entities = new ArrayList<>();
|
List<Entity> entities = new ArrayList<>();
|
||||||
visuals.put(pos, entities);
|
visuals.put(pos, entities);
|
||||||
if (pot.soup != null && !pot.brewing()) {
|
if (pot.soup != null && !pot.brewing()) {
|
||||||
int rgb = pot.soup.getItemMeta().getPersistentDataContainer().getOrDefault(colorKey, PersistentDataType.INTEGER, 0xB77A36);
|
int rgb =
|
||||||
TextDisplay display = block.getWorld().spawn(block.getLocation().add(.5, .5, .5), TextDisplay.class, d -> {
|
pot.soup
|
||||||
|
.getItemMeta()
|
||||||
|
.getPersistentDataContainer()
|
||||||
|
.getOrDefault(colorKey, PersistentDataType.INTEGER, 0xB77A36);
|
||||||
|
TextDisplay display =
|
||||||
|
block.getWorld()
|
||||||
|
.spawn(
|
||||||
|
block.getLocation().add(.5, .5, .5),
|
||||||
|
TextDisplay.class,
|
||||||
|
d -> {
|
||||||
markVisual(d);
|
markVisual(d);
|
||||||
// One default-font space: native background spans 5x10 pixels at 0.025 blocks/pixel.
|
// One default-font space: native background spans 5x10
|
||||||
// Center the rectangle, scale to 0.75x0.75 and face upwards inside the cauldron.
|
// pixels at 0.025 blocks/pixel.
|
||||||
d.text(Component.text(" ").font(net.kyori.adventure.key.Key.key("minecraft:default")));
|
// Center the rectangle, scale to 0.75x0.75 and face upwards
|
||||||
|
// inside the cauldron.
|
||||||
|
d.text(
|
||||||
|
Component.text(" ")
|
||||||
|
.font(
|
||||||
|
net.kyori.adventure.key.Key.key(
|
||||||
|
"minecraft:default")));
|
||||||
d.setDefaultBackground(false);
|
d.setDefaultBackground(false);
|
||||||
d.setBackgroundColor(Color.fromARGB(0xFF000000 | rgb));
|
d.setBackgroundColor(Color.fromARGB(0xFF000000 | rgb));
|
||||||
d.setShadowed(false);
|
d.setShadowed(false);
|
||||||
@@ -346,13 +539,20 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
d.setViewRange(.5f);
|
d.setViewRange(.5f);
|
||||||
});
|
});
|
||||||
entities.add(display);
|
entities.add(display);
|
||||||
} else for (int i = 0; i < pot.items.size(); i++) {
|
} else
|
||||||
|
for (int i = 0; i < pot.items.size(); i++) {
|
||||||
ItemStack stack = pot.items.get(i).clone();
|
ItemStack stack = pot.items.get(i).clone();
|
||||||
int slot = i;
|
int slot = i;
|
||||||
ItemDisplay item = block.getWorld().spawn(block.getLocation().add(.5, .5, .5), ItemDisplay.class, e -> {
|
ItemDisplay item =
|
||||||
|
block.getWorld()
|
||||||
|
.spawn(
|
||||||
|
block.getLocation().add(.5, .5, .5),
|
||||||
|
ItemDisplay.class,
|
||||||
|
e -> {
|
||||||
markVisual(e);
|
markVisual(e);
|
||||||
e.setItemStack(stack);
|
e.setItemStack(stack);
|
||||||
e.setItemDisplayTransform(ItemDisplay.ItemDisplayTransform.FIXED);
|
e.setItemDisplayTransform(
|
||||||
|
ItemDisplay.ItemDisplayTransform.FIXED);
|
||||||
e.setTransformation(itemTransform(block, slot, pot, 0));
|
e.setTransformation(itemTransform(block, slot, pot, 0));
|
||||||
e.setInterpolationDuration(2);
|
e.setInterpolationDuration(2);
|
||||||
e.setViewRange(.5f);
|
e.setViewRange(.5f);
|
||||||
@@ -368,7 +568,11 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
entity.setInvulnerable(true);
|
entity.setInvulnerable(true);
|
||||||
entity.setSilent(true);
|
entity.setSilent(true);
|
||||||
}
|
}
|
||||||
private boolean isVisual(Entity entity) { return entity.getPersistentDataContainer().has(visualKey, PersistentDataType.BYTE); }
|
|
||||||
|
private boolean isVisual(Entity entity) {
|
||||||
|
return entity.getPersistentDataContainer().has(visualKey, PersistentDataType.BYTE);
|
||||||
|
}
|
||||||
|
|
||||||
private void removeVisuals(Position pos) {
|
private void removeVisuals(Position pos) {
|
||||||
List<Entity> entities = visuals.remove(pos);
|
List<Entity> entities = visuals.remove(pos);
|
||||||
if (entities != null) entities.forEach(Entity::remove);
|
if (entities != null) entities.forEach(Entity::remove);
|
||||||
@@ -376,79 +580,168 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
public void breakBlock(BlockBreakEvent e) {
|
public void breakBlock(BlockBreakEvent e) {
|
||||||
Position pos = Position.at(e.getBlock()); Pot pot = pots.get(pos);
|
Position pos = Position.at(e.getBlock());
|
||||||
|
Pot pot = pots.get(pos);
|
||||||
if (pot == null) return;
|
if (pot == null) return;
|
||||||
if (!change(pos, null)) { e.setCancelled(true); saveError(e.getPlayer()); return; }
|
if (!change(pos, null)) {
|
||||||
for (ItemStack item : pot.items) e.getBlock().getWorld().dropItemNaturally(e.getBlock().getLocation().add(.5, .5, .5), item.clone());
|
e.setCancelled(true);
|
||||||
if (pot.soup != null && !pot.brewing()) say(e.getPlayer(), "Суп вылился из разбитого котла.");
|
saveError(e.getPlayer());
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
for (ItemStack item : pot.items)
|
||||||
public void cauldronChange(CauldronLevelChangeEvent e) { if (pots.containsKey(Position.at(e.getBlock()))) e.setCancelled(true); }
|
e.getBlock()
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
.getWorld()
|
||||||
public void explode(EntityExplodeEvent e) { e.blockList().removeIf(b -> pots.containsKey(Position.at(b))); }
|
.dropItemNaturally(e.getBlock().getLocation().add(.5, .5, .5), item.clone());
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
if (pot.soup != null && !pot.brewing())
|
||||||
public void blockExplode(BlockExplodeEvent e) { e.blockList().removeIf(b -> pots.containsKey(Position.at(b))); }
|
say(e.getPlayer(), "Суп вылился из разбитого котла.");
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
|
||||||
public void piston(BlockPistonExtendEvent e) { if (e.getBlocks().stream().anyMatch(b -> pots.containsKey(Position.at(b)))) e.setCancelled(true); }
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
|
||||||
public void pistonRetract(BlockPistonRetractEvent e) { if (e.getBlocks().stream().anyMatch(b -> pots.containsKey(Position.at(b)))) e.setCancelled(true); }
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
|
||||||
public void entityBlock(EntityChangeBlockEvent e) { if (pots.containsKey(Position.at(e.getBlock()))) e.setCancelled(true); }
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
|
||||||
public void pickup(EntityPickupItemEvent e) { if (isVisual(e.getItem())) e.setCancelled(true); else normalizeEntity(e.getItem()); }
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
|
||||||
public void hopperPickup(InventoryPickupItemEvent e) { if (isVisual(e.getItem())) e.setCancelled(true); else normalizeEntity(e.getItem()); }
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
|
||||||
public void merge(ItemMergeEvent e) { if (isVisual(e.getEntity()) || isVisual(e.getTarget())) e.setCancelled(true); }
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
|
||||||
public void damage(EntityDamageEvent e) { if (isVisual(e.getEntity())) e.setCancelled(true); }
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
|
||||||
public void portal(EntityPortalEvent e) { if (isVisual(e.getEntity())) e.setCancelled(true); }
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
|
||||||
public void despawn(ItemDespawnEvent e) { if (isVisual(e.getEntity())) e.setCancelled(true); }
|
|
||||||
@EventHandler public void unload(ChunkUnloadEvent e) {
|
|
||||||
for (Position p : new ArrayList<>(visuals.keySet())) if (p.world.equals(e.getWorld().getUID()) && (p.x >> 4) == e.getChunk().getX() && (p.z >> 4) == e.getChunk().getZ()) removeVisuals(p);
|
|
||||||
}
|
}
|
||||||
@EventHandler public void entitiesLoad(EntitiesLoadEvent e) {
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void cauldronChange(CauldronLevelChangeEvent e) {
|
||||||
|
if (pots.containsKey(Position.at(e.getBlock()))) e.setCancelled(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void explode(EntityExplodeEvent e) {
|
||||||
|
e.blockList().removeIf(b -> pots.containsKey(Position.at(b)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void blockExplode(BlockExplodeEvent e) {
|
||||||
|
e.blockList().removeIf(b -> pots.containsKey(Position.at(b)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void piston(BlockPistonExtendEvent e) {
|
||||||
|
if (e.getBlocks().stream().anyMatch(b -> pots.containsKey(Position.at(b))))
|
||||||
|
e.setCancelled(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void pistonRetract(BlockPistonRetractEvent e) {
|
||||||
|
if (e.getBlocks().stream().anyMatch(b -> pots.containsKey(Position.at(b))))
|
||||||
|
e.setCancelled(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void entityBlock(EntityChangeBlockEvent e) {
|
||||||
|
if (pots.containsKey(Position.at(e.getBlock()))) e.setCancelled(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void pickup(EntityPickupItemEvent e) {
|
||||||
|
if (isVisual(e.getItem())) e.setCancelled(true);
|
||||||
|
else normalizeEntity(e.getItem());
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void hopperPickup(InventoryPickupItemEvent e) {
|
||||||
|
if (isVisual(e.getItem())) e.setCancelled(true);
|
||||||
|
else normalizeEntity(e.getItem());
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void merge(ItemMergeEvent e) {
|
||||||
|
if (isVisual(e.getEntity()) || isVisual(e.getTarget())) e.setCancelled(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void damage(EntityDamageEvent e) {
|
||||||
|
if (isVisual(e.getEntity())) e.setCancelled(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void portal(EntityPortalEvent e) {
|
||||||
|
if (isVisual(e.getEntity())) e.setCancelled(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void despawn(ItemDespawnEvent e) {
|
||||||
|
if (isVisual(e.getEntity())) e.setCancelled(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler
|
||||||
|
public void unload(ChunkUnloadEvent e) {
|
||||||
|
for (Position p : new ArrayList<>(visuals.keySet()))
|
||||||
|
if (p.world.equals(e.getWorld().getUID())
|
||||||
|
&& (p.x >> 4) == e.getChunk().getX()
|
||||||
|
&& (p.z >> 4) == e.getChunk().getZ()) removeVisuals(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler
|
||||||
|
public void entitiesLoad(EntitiesLoadEvent e) {
|
||||||
for (Entity entity : e.getEntities()) {
|
for (Entity entity : e.getEntities()) {
|
||||||
if (isVisual(entity) && visuals.values().stream().noneMatch(list -> list.contains(entity))) entity.remove();
|
if (isVisual(entity)
|
||||||
|
&& visuals.values().stream().noneMatch(list -> list.contains(entity)))
|
||||||
|
entity.remove();
|
||||||
else if (entity instanceof Item item && !isVisual(entity)) normalizeEntity(item);
|
else if (entity instanceof Item item && !isVisual(entity)) normalizeEntity(item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void normalizeEntity(Item item) { ItemStack stack = item.getItemStack(); if (Ingredients.normalize(stack)) item.setItemStack(stack); }
|
private void normalizeEntity(Item item) {
|
||||||
|
ItemStack stack = item.getItemStack();
|
||||||
|
if (Ingredients.normalize(stack)) item.setItemStack(stack);
|
||||||
|
}
|
||||||
|
|
||||||
private void normalizeInventory(Inventory inv) {
|
private void normalizeInventory(Inventory inv) {
|
||||||
for (int i = 0; i < inv.getSize(); i++) {
|
for (int i = 0; i < inv.getSize(); i++) {
|
||||||
ItemStack item = inv.getItem(i);
|
ItemStack item = inv.getItem(i);
|
||||||
if (Ingredients.normalize(item)) inv.setItem(i, item);
|
if (Ingredients.normalize(item)) inv.setItem(i, item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@EventHandler public void join(PlayerJoinEvent e) { normalizeInventory(e.getPlayer().getInventory()); }
|
|
||||||
|
@EventHandler
|
||||||
|
public void join(PlayerJoinEvent e) {
|
||||||
|
normalizeInventory(e.getPlayer().getInventory());
|
||||||
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
public void open(InventoryOpenEvent e) { normalizeInventory(e.getInventory()); normalizeInventory(e.getPlayer().getInventory()); }
|
public void open(InventoryOpenEvent e) {
|
||||||
|
normalizeInventory(e.getInventory());
|
||||||
|
normalizeInventory(e.getPlayer().getInventory());
|
||||||
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
public void spawn(ItemSpawnEvent e) { normalizeEntity(e.getEntity()); }
|
public void spawn(ItemSpawnEvent e) {
|
||||||
|
normalizeEntity(e.getEntity());
|
||||||
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST)
|
@EventHandler(priority = EventPriority.HIGHEST)
|
||||||
public void craft(PrepareItemCraftEvent e) {
|
public void craft(PrepareItemCraftEvent e) {
|
||||||
ItemStack result = e.getInventory().getResult();
|
ItemStack result = e.getInventory().getResult();
|
||||||
if (Ingredients.normalize(result)) e.getInventory().setResult(result);
|
if (Ingredients.normalize(result)) e.getInventory().setResult(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
public void crafted(CraftItemEvent e) {
|
public void crafted(CraftItemEvent e) {
|
||||||
ItemStack result = e.getCurrentItem();
|
ItemStack result = e.getCurrentItem();
|
||||||
if (Ingredients.normalize(result)) e.setCurrentItem(result);
|
if (Ingredients.normalize(result)) e.setCurrentItem(result);
|
||||||
}
|
}
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
|
||||||
public void loot(LootGenerateEvent e) { e.getLoot().forEach(Ingredients::normalize); }
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
|
||||||
public void transfer(InventoryMoveItemEvent e) { ItemStack item = e.getItem(); if (Ingredients.normalize(item)) e.setItem(item); }
|
|
||||||
|
|
||||||
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void loot(LootGenerateEvent e) {
|
||||||
|
e.getLoot().forEach(Ingredients::normalize);
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void transfer(InventoryMoveItemEvent e) {
|
||||||
|
ItemStack item = e.getItem();
|
||||||
|
if (Ingredients.normalize(item)) e.setItem(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||||
if (args.length == 0) {
|
if (args.length == 0) {
|
||||||
sender.sendMessage(Component.text("ПКМ с едой/зельем: добавить (4 предмета). ПКМ пустой рукой: забрать последний. Shift+ПКМ или ПКМ с предметом после заполнения: сварить. ПКМ миской по готовому супу: собрать.", NamedTextColor.GOLD));
|
sender.sendMessage(
|
||||||
|
Component.text(
|
||||||
|
"ПКМ с едой/зельем: добавить (4 предмета). ПКМ пустой рукой: забрать последний. Shift+ПКМ или ПКМ с предметом после заполнения: сварить. ПКМ миской по готовому супу: собрать.",
|
||||||
|
NamedTextColor.GOLD));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!sender.hasPermission("astrasoups.admin")) {
|
||||||
|
sender.sendMessage("Недостаточно прав.");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (!sender.hasPermission("astrasoups.admin")) { sender.sendMessage("Недостаточно прав."); return true; }
|
|
||||||
if (args[0].equalsIgnoreCase("reload") && args.length == 1) {
|
if (args[0].equalsIgnoreCase("reload") && args.length == 1) {
|
||||||
String previous = getConfig().saveToString();
|
String previous = getConfig().saveToString();
|
||||||
try {
|
try {
|
||||||
@@ -459,21 +752,38 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
ingredients = next;
|
ingredients = next;
|
||||||
sender.sendMessage("AstraSoups: конфигурация перезагружена.");
|
sender.sendMessage("AstraSoups: конфигурация перезагружена.");
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
// Restore prior settings in memory; leave the invalid file for the administrator to fix.
|
// Restore prior settings in memory; leave the invalid file for the administrator to
|
||||||
|
// fix.
|
||||||
restoreConfig(previous);
|
restoreConfig(previous);
|
||||||
sender.sendMessage("Ошибка конфигурации: " + ex.getMessage() + ". Продолжают действовать прежние настройки.");
|
sender.sendMessage(
|
||||||
|
"Ошибка конфигурации: "
|
||||||
|
+ ex.getMessage()
|
||||||
|
+ ". Продолжают действовать прежние настройки.");
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (args[0].equalsIgnoreCase("register") && args.length == 4 && sender instanceof Player player) {
|
if (args[0].equalsIgnoreCase("register")
|
||||||
if (!args[1].matches("[a-z0-9_-]+")) { sender.sendMessage("ID: только a-z, 0-9, _ и -."); return true; }
|
&& args.length == 4
|
||||||
|
&& sender instanceof Player player) {
|
||||||
|
if (!args[1].matches("[a-z0-9_-]+")) {
|
||||||
|
sender.sendMessage("ID: только a-z, 0-9, _ и -.");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
ItemStack item = player.getInventory().getItemInMainHand().asOne();
|
ItemStack item = player.getInventory().getItemInMainHand().asOne();
|
||||||
if (item.getType().isAir()) { sender.sendMessage("Возьмите уникальную еду в основную руку."); return true; }
|
if (item.getType().isAir()) {
|
||||||
|
sender.sendMessage("Возьмите уникальную еду в основную руку.");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
String previous = getConfig().saveToString();
|
String previous = getConfig().saveToString();
|
||||||
try {
|
try {
|
||||||
int nutrition = Integer.parseInt(args[2]); float saturation = Float.parseFloat(args[3]);
|
int nutrition = Integer.parseInt(args[2]);
|
||||||
if (nutrition < 0 || nutrition > getConfig().getInt("max-nutrition", 1000) || saturation < 0 || !Float.isFinite(saturation)
|
float saturation = Float.parseFloat(args[3]);
|
||||||
|| saturation > getConfig().getDouble("max-saturation", 1000)) throw new IllegalArgumentException();
|
if (nutrition < 0
|
||||||
|
|| nutrition > getConfig().getInt("max-nutrition", 1000)
|
||||||
|
|| saturation < 0
|
||||||
|
|| !Float.isFinite(saturation)
|
||||||
|
|| saturation > getConfig().getDouble("max-saturation", 1000))
|
||||||
|
throw new IllegalArgumentException();
|
||||||
String path = "custom-ingredients." + args[1];
|
String path = "custom-ingredients." + args[1];
|
||||||
getConfig().set(path + ".item", item);
|
getConfig().set(path + ".item", item);
|
||||||
getConfig().set(path + ".nutrition", nutrition);
|
getConfig().set(path + ".nutrition", nutrition);
|
||||||
@@ -484,18 +794,31 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
|||||||
sender.sendMessage("Зарегистрирован ингредиент: " + args[1]);
|
sender.sendMessage("Зарегистрирован ингредиент: " + args[1]);
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
restoreConfig(previous);
|
restoreConfig(previous);
|
||||||
sender.sendMessage("Не удалось зарегистрировать: проверьте числа и конфигурацию. " + ex.getMessage());
|
sender.sendMessage(
|
||||||
|
"Не удалось зарегистрировать: проверьте числа и конфигурацию. "
|
||||||
|
+ ex.getMessage());
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void restoreConfig(String yaml) {
|
private void restoreConfig(String yaml) {
|
||||||
try { getConfig().loadFromString(yaml); }
|
try {
|
||||||
catch (org.bukkit.configuration.InvalidConfigurationException ex) { throw new IllegalStateException("Cannot restore validated config", ex); }
|
getConfig().loadFromString(yaml);
|
||||||
|
} catch (org.bukkit.configuration.InvalidConfigurationException ex) {
|
||||||
|
throw new IllegalStateException("Cannot restore validated config", ex);
|
||||||
}
|
}
|
||||||
@Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> onTabComplete(
|
||||||
|
CommandSender sender, Command command, String alias, String[] args) {
|
||||||
if (!sender.hasPermission("astrasoups.admin")) return List.of();
|
if (!sender.hasPermission("astrasoups.admin")) return List.of();
|
||||||
return args.length == 1 ? List.of("reload", "register").stream().filter(s -> s.startsWith(args[0].toLowerCase(Locale.ROOT))).toList() : List.of();
|
return args.length == 1
|
||||||
|
? List.of("reload", "register").stream()
|
||||||
|
.filter(s -> s.startsWith(args[0].toLowerCase(Locale.ROOT)))
|
||||||
|
.toList()
|
||||||
|
: List.of();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package online.astradev.soups;
|
|||||||
/** ItemDisplay centers relative to the cauldron, without native dropped-item physics or bobbing. */
|
/** ItemDisplay centers relative to the cauldron, without native dropped-item physics or bobbing. */
|
||||||
public final class CauldronAnimation {
|
public final class CauldronAnimation {
|
||||||
private CauldronAnimation() {}
|
private CauldronAnimation() {}
|
||||||
|
|
||||||
public record Offset(double x, double y, double z) {}
|
public record Offset(double x, double y, double z) {}
|
||||||
|
|
||||||
public static Offset frame(int slot, int waterLevel, int tick, int elapsed, int duration) {
|
public static Offset frame(int slot, int waterLevel, int tick, int elapsed, int duration) {
|
||||||
@@ -11,8 +12,8 @@ public final class CauldronAnimation {
|
|||||||
double radius = .23;
|
double radius = .23;
|
||||||
double surface = .375 + .1875 * waterLevel;
|
double surface = .375 + .1875 * waterLevel;
|
||||||
double bob = Math.sin(tick * .04 + slot) * .004;
|
double bob = Math.sin(tick * .04 + slot) * .004;
|
||||||
return new Offset(.5 + Math.cos(angle) * radius,
|
return new Offset(
|
||||||
surface - .055 + bob, .5 + Math.sin(angle) * radius);
|
.5 + Math.cos(angle) * radius, surface - .055 + bob, .5 + Math.sin(angle) * radius);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static double liquidHeight(int servings, int capacity) {
|
public static double liquidHeight(int servings, int capacity) {
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package online.astradev.soups;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
/** Pure matching logic: incompatible selectors must occur in distinct slots. */
|
|
||||||
public final class CombinationRules {
|
public final class CombinationRules {
|
||||||
private CombinationRules() {}
|
private CombinationRules() {}
|
||||||
|
|
||||||
@@ -11,7 +10,8 @@ public final class CombinationRules {
|
|||||||
return selector.equals("*") || tags.contains(selector.toLowerCase(java.util.Locale.ROOT));
|
return selector.equals("*") || tags.contains(selector.toLowerCase(java.util.Locale.ROOT));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String rejection(List<Set<String>> ingredients, List<String> blocked, List<List<String>> pairs) {
|
public static String rejection(
|
||||||
|
List<Set<String>> ingredients, List<String> blocked, List<List<String>> pairs) {
|
||||||
if (ingredients.size() != 4) return "Нужно ровно 4 ингредиента.";
|
if (ingredients.size() != 4) return "Нужно ровно 4 ингредиента.";
|
||||||
for (Set<String> tags : ingredients) {
|
for (Set<String> tags : ingredients) {
|
||||||
for (String selector : blocked) {
|
for (String selector : blocked) {
|
||||||
@@ -20,8 +20,9 @@ public final class CombinationRules {
|
|||||||
}
|
}
|
||||||
for (List<String> pair : pairs) {
|
for (List<String> pair : pairs) {
|
||||||
for (int i = 0; i < ingredients.size(); i++) {
|
for (int i = 0; i < ingredients.size(); i++) {
|
||||||
|
if (!matches(ingredients.get(i), pair.get(0))) continue;
|
||||||
for (int j = 0; j < ingredients.size(); j++) {
|
for (int j = 0; j < ingredients.size(); j++) {
|
||||||
if (i != j && matches(ingredients.get(i), pair.get(0)) && matches(ingredients.get(j), pair.get(1))) {
|
if (i != j && matches(ingredients.get(j), pair.get(1))) {
|
||||||
return "Несовместимые ингредиенты: " + String.join(" + ", pair);
|
return "Несовместимые ингредиенты: " + String.join(" + ", pair);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,11 +3,12 @@ package online.astradev.soups;
|
|||||||
import org.bukkit.Color;
|
import org.bukkit.Color;
|
||||||
import org.bukkit.Material;
|
import org.bukkit.Material;
|
||||||
|
|
||||||
/** Representative food colors; potion contents and custom food overrides are read separately. */
|
|
||||||
final class IngredientColors {
|
final class IngredientColors {
|
||||||
private IngredientColors() {}
|
private IngredientColors() {}
|
||||||
|
|
||||||
static Color food(Material material, Color fallback) {
|
static Color food(Material material, Color fallback) {
|
||||||
int rgb = switch (material) {
|
int rgb =
|
||||||
|
switch (material) {
|
||||||
case SPIDER_EYE, FERMENTED_SPIDER_EYE -> 0xB52B38;
|
case SPIDER_EYE, FERMENTED_SPIDER_EYE -> 0xB52B38;
|
||||||
case GOLDEN_APPLE, ENCHANTED_GOLDEN_APPLE, GOLDEN_CARROT -> 0xF2C94C;
|
case GOLDEN_APPLE, ENCHANTED_GOLDEN_APPLE, GOLDEN_CARROT -> 0xF2C94C;
|
||||||
case APPLE, SWEET_BERRIES -> 0xC73735;
|
case APPLE, SWEET_BERRIES -> 0xC73735;
|
||||||
|
|||||||
@@ -5,9 +5,11 @@ import io.papermc.paper.datacomponent.item.Consumable;
|
|||||||
import io.papermc.paper.datacomponent.item.FoodProperties;
|
import io.papermc.paper.datacomponent.item.FoodProperties;
|
||||||
import io.papermc.paper.datacomponent.item.UseRemainder;
|
import io.papermc.paper.datacomponent.item.UseRemainder;
|
||||||
import io.papermc.paper.datacomponent.item.consumable.ConsumeEffect;
|
import io.papermc.paper.datacomponent.item.consumable.ConsumeEffect;
|
||||||
|
|
||||||
import net.kyori.adventure.text.Component;
|
import net.kyori.adventure.text.Component;
|
||||||
import net.kyori.adventure.text.format.NamedTextColor;
|
import net.kyori.adventure.text.format.NamedTextColor;
|
||||||
import net.kyori.adventure.text.format.TextDecoration;
|
import net.kyori.adventure.text.format.TextDecoration;
|
||||||
|
|
||||||
import org.bukkit.Color;
|
import org.bukkit.Color;
|
||||||
import org.bukkit.Material;
|
import org.bukkit.Material;
|
||||||
import org.bukkit.NamespacedKey;
|
import org.bukkit.NamespacedKey;
|
||||||
@@ -25,8 +27,21 @@ import java.lang.reflect.Method;
|
|||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
public final class Ingredients {
|
public final class Ingredients {
|
||||||
public record Ingredient(int nutrition, float saturation, List<ConsumeEffect> effects, Set<String> tags, Color color) {}
|
public record Ingredient(
|
||||||
private record Custom(String id, ItemStack sample, int nutrition, float saturation, List<PotionEffect> effects, Color color) {}
|
int nutrition,
|
||||||
|
float saturation,
|
||||||
|
List<ConsumeEffect> effects,
|
||||||
|
Set<String> tags,
|
||||||
|
Color color) {}
|
||||||
|
|
||||||
|
private record Custom(
|
||||||
|
String id,
|
||||||
|
ItemStack sample,
|
||||||
|
int nutrition,
|
||||||
|
float saturation,
|
||||||
|
List<PotionEffect> effects,
|
||||||
|
Color color) {}
|
||||||
|
|
||||||
private final AstraSoupsPlugin plugin;
|
private final AstraSoupsPlugin plugin;
|
||||||
private final List<Custom> custom = new ArrayList<>();
|
private final List<Custom> custom = new ArrayList<>();
|
||||||
private List<String> blocked;
|
private List<String> blocked;
|
||||||
@@ -41,12 +56,22 @@ public final class Ingredients {
|
|||||||
throw new IllegalArgumentException("brew-seconds должно быть от 0.5 до 60");
|
throw new IllegalArgumentException("brew-seconds должно быть от 0.5 до 60");
|
||||||
}
|
}
|
||||||
int servings = plugin.getConfig().getInt("servings-per-brew", 4);
|
int servings = plugin.getConfig().getInt("servings-per-brew", 4);
|
||||||
if (servings < 1 || servings > 16) throw new IllegalArgumentException("servings-per-brew должно быть от 1 до 16");
|
if (servings < 1 || servings > 16)
|
||||||
defaultColor = Color.fromRGB(Integer.parseInt(plugin.getConfig().getString("default-color", "#B77A36").replace("#", ""), 16));
|
throw new IllegalArgumentException("servings-per-brew должно быть от 1 до 16");
|
||||||
|
defaultColor =
|
||||||
|
Color.fromRGB(
|
||||||
|
Integer.parseInt(
|
||||||
|
plugin.getConfig()
|
||||||
|
.getString("default-color", "#B77A36")
|
||||||
|
.replace("#", ""),
|
||||||
|
16));
|
||||||
blocked = plugin.getConfig().getStringList("blocked-ingredients");
|
blocked = plugin.getConfig().getStringList("blocked-ingredients");
|
||||||
for (Object value : plugin.getConfig().getList("incompatible", List.of())) {
|
for (Object value : plugin.getConfig().getList("incompatible", List.of())) {
|
||||||
if (!(value instanceof List<?> list) || list.size() != 2 || list.stream().anyMatch(x -> !(x instanceof String))) {
|
if (!(value instanceof List<?> list)
|
||||||
throw new IllegalArgumentException("Каждое правило incompatible должно содержать два селектора");
|
|| list.size() != 2
|
||||||
|
|| list.stream().anyMatch(x -> !(x instanceof String))) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Каждое правило incompatible должно содержать два селектора");
|
||||||
}
|
}
|
||||||
pairs.add(List.of((String) list.get(0), (String) list.get(1)));
|
pairs.add(List.of((String) list.get(0), (String) list.get(1)));
|
||||||
}
|
}
|
||||||
@@ -55,27 +80,51 @@ public final class Ingredients {
|
|||||||
|| plugin.getConfig().getDouble("max-saturation", 1000) < 0) {
|
|| plugin.getConfig().getDouble("max-saturation", 1000) < 0) {
|
||||||
throw new IllegalArgumentException("Некорректные ограничения питания");
|
throw new IllegalArgumentException("Некорректные ограничения питания");
|
||||||
}
|
}
|
||||||
ConfigurationSection section = plugin.getConfig().getConfigurationSection("custom-ingredients");
|
ConfigurationSection section =
|
||||||
if (section != null) for (String id : section.getKeys(false)) {
|
plugin.getConfig().getConfigurationSection("custom-ingredients");
|
||||||
ConfigurationSection c = Objects.requireNonNull(section.getConfigurationSection(id));
|
if (section != null)
|
||||||
|
for (String id : section.getKeys(false)) {
|
||||||
|
ConfigurationSection c =
|
||||||
|
Objects.requireNonNull(section.getConfigurationSection(id));
|
||||||
ItemStack sample = c.getItemStack("item");
|
ItemStack sample = c.getItemStack("item");
|
||||||
int nutrition = c.getInt("nutrition");
|
int nutrition = c.getInt("nutrition");
|
||||||
float saturation = (float) c.getDouble("saturation");
|
float saturation = (float) c.getDouble("saturation");
|
||||||
if (sample == null || sample.getType().isAir() || nutrition < 0 || saturation < 0 || !Float.isFinite(saturation)) {
|
if (sample == null
|
||||||
|
|| sample.getType().isAir()
|
||||||
|
|| nutrition < 0
|
||||||
|
|| saturation < 0
|
||||||
|
|| !Float.isFinite(saturation)) {
|
||||||
throw new IllegalArgumentException("Некорректный custom-ingredients." + id);
|
throw new IllegalArgumentException("Некорректный custom-ingredients." + id);
|
||||||
}
|
}
|
||||||
List<PotionEffect> effects = new ArrayList<>();
|
List<PotionEffect> effects = new ArrayList<>();
|
||||||
for (Map<?, ?> map : c.getMapList("effects")) {
|
for (Map<?, ?> map : c.getMapList("effects")) {
|
||||||
PotionEffectType type = Registry.EFFECT.get(Objects.requireNonNull(NamespacedKey.fromString(String.valueOf(map.get("type")))));
|
PotionEffectType type =
|
||||||
if (type == null) throw new IllegalArgumentException("Неизвестный эффект в " + id);
|
Registry.EFFECT.get(
|
||||||
|
Objects.requireNonNull(
|
||||||
|
NamespacedKey.fromString(
|
||||||
|
String.valueOf(map.get("type")))));
|
||||||
|
if (type == null)
|
||||||
|
throw new IllegalArgumentException("Неизвестный эффект в " + id);
|
||||||
int duration = Integer.parseInt(String.valueOf(map.get("duration")));
|
int duration = Integer.parseInt(String.valueOf(map.get("duration")));
|
||||||
int amplifier = Integer.parseInt(String.valueOf(map.get("amplifier")));
|
int amplifier = Integer.parseInt(String.valueOf(map.get("amplifier")));
|
||||||
if (duration < -1 || duration == 0 || amplifier < 0 || amplifier > 255) throw new IllegalArgumentException("Некорректный эффект в " + id);
|
if (duration < -1 || duration == 0 || amplifier < 0 || amplifier > 255)
|
||||||
|
throw new IllegalArgumentException("Некорректный эффект в " + id);
|
||||||
effects.add(new PotionEffect(type, duration, amplifier));
|
effects.add(new PotionEffect(type, duration, amplifier));
|
||||||
}
|
}
|
||||||
normalize(sample);
|
normalize(sample);
|
||||||
Color customColor = c.isString("color") ? Color.fromRGB(Integer.parseInt(c.getString("color").replace("#", ""), 16)) : null;
|
Color customColor =
|
||||||
custom.add(new Custom(id, sample.asOne(), nutrition, saturation, List.copyOf(effects), customColor));
|
c.isString("color")
|
||||||
|
? Color.fromRGB(
|
||||||
|
Integer.parseInt(c.getString("color").replace("#", ""), 16))
|
||||||
|
: null;
|
||||||
|
custom.add(
|
||||||
|
new Custom(
|
||||||
|
id,
|
||||||
|
sample.asOne(),
|
||||||
|
nutrition,
|
||||||
|
saturation,
|
||||||
|
List.copyOf(effects),
|
||||||
|
customColor));
|
||||||
}
|
}
|
||||||
if (plugin.getServer().getPluginManager().isPluginEnabled("ItemsAdder")) {
|
if (plugin.getServer().getPluginManager().isPluginEnabled("ItemsAdder")) {
|
||||||
try {
|
try {
|
||||||
@@ -92,8 +141,13 @@ public final class Ingredients {
|
|||||||
if (item == null || item.getType().isAir()) return null;
|
if (item == null || item.getType().isAir()) return null;
|
||||||
FoodProperties food = item.getData(DataComponentTypes.FOOD);
|
FoodProperties food = item.getData(DataComponentTypes.FOOD);
|
||||||
ItemMeta meta = item.getItemMeta();
|
ItemMeta meta = item.getItemMeta();
|
||||||
Custom match = custom.stream().filter(c -> c.sample.isSimilar(item)).findFirst().orElse(null);
|
Custom match =
|
||||||
boolean potion = switch (item.getType()) { case POTION, SPLASH_POTION, LINGERING_POTION -> true; default -> false; };
|
custom.stream().filter(c -> c.sample.isSimilar(item)).findFirst().orElse(null);
|
||||||
|
boolean potion =
|
||||||
|
switch (item.getType()) {
|
||||||
|
case POTION, SPLASH_POTION, LINGERING_POTION -> true;
|
||||||
|
default -> false;
|
||||||
|
};
|
||||||
// Cake is edible as a placed block and has no FOOD component.
|
// Cake is edible as a placed block and has no FOOD component.
|
||||||
boolean cake = item.getType() == Material.CAKE;
|
boolean cake = item.getType() == Material.CAKE;
|
||||||
if (food == null && !potion && match == null && !cake) return null;
|
if (food == null && !potion && match == null && !cake) return null;
|
||||||
@@ -103,9 +157,17 @@ public final class Ingredients {
|
|||||||
Consumable consumable = item.getData(DataComponentTypes.CONSUMABLE);
|
Consumable consumable = item.getData(DataComponentTypes.CONSUMABLE);
|
||||||
if (consumable != null) effects.addAll(consumable.consumeEffects());
|
if (consumable != null) effects.addAll(consumable.consumeEffects());
|
||||||
Color color = IngredientColors.food(item.getType(), defaultColor);
|
Color color = IngredientColors.food(item.getType(), defaultColor);
|
||||||
if (isCombined(item)) color = Color.fromRGB(meta.getPersistentDataContainer().getOrDefault(plugin.colorKey, PersistentDataType.INTEGER, defaultColor.asRGB()));
|
if (isCombined(item))
|
||||||
|
color =
|
||||||
|
Color.fromRGB(
|
||||||
|
meta.getPersistentDataContainer()
|
||||||
|
.getOrDefault(
|
||||||
|
plugin.colorKey,
|
||||||
|
PersistentDataType.INTEGER,
|
||||||
|
defaultColor.asRGB()));
|
||||||
if (potion && meta instanceof PotionMeta pm) {
|
if (potion && meta instanceof PotionMeta pm) {
|
||||||
if (!pm.getAllEffects().isEmpty()) effects.add(ConsumeEffect.applyStatusEffects(pm.getAllEffects(), 1));
|
if (!pm.getAllEffects().isEmpty())
|
||||||
|
effects.add(ConsumeEffect.applyStatusEffects(pm.getAllEffects(), 1));
|
||||||
color = pm.computeEffectiveColor();
|
color = pm.computeEffectiveColor();
|
||||||
}
|
}
|
||||||
if (meta instanceof SuspiciousStewMeta stew && stew.hasCustomEffects()) {
|
if (meta instanceof SuspiciousStewMeta stew && stew.hasCustomEffects()) {
|
||||||
@@ -118,16 +180,20 @@ public final class Ingredients {
|
|||||||
nutrition = match.nutrition;
|
nutrition = match.nutrition;
|
||||||
saturation = match.saturation;
|
saturation = match.saturation;
|
||||||
tags.add("custom:" + match.id.toLowerCase(Locale.ROOT));
|
tags.add("custom:" + match.id.toLowerCase(Locale.ROOT));
|
||||||
if (!match.effects.isEmpty()) effects.add(ConsumeEffect.applyStatusEffects(match.effects, 1));
|
if (!match.effects.isEmpty())
|
||||||
|
effects.add(ConsumeEffect.applyStatusEffects(match.effects, 1));
|
||||||
if (match.color != null) color = match.color;
|
if (match.color != null) color = match.color;
|
||||||
}
|
}
|
||||||
if (iaLookup != null) try {
|
if (iaLookup != null)
|
||||||
|
try {
|
||||||
Object ia = iaLookup.invoke(null, item);
|
Object ia = iaLookup.invoke(null, item);
|
||||||
if (ia != null) tags.add("itemsadder:" + iaId.invoke(ia).toString().toLowerCase(Locale.ROOT));
|
if (ia != null)
|
||||||
|
tags.add("itemsadder:" + iaId.invoke(ia).toString().toLowerCase(Locale.ROOT));
|
||||||
} catch (ReflectiveOperationException e) {
|
} catch (ReflectiveOperationException e) {
|
||||||
throw new IllegalStateException("Ошибка чтения уникальной еды ItemsAdder", e);
|
throw new IllegalStateException("Ошибка чтения уникальной еды ItemsAdder", e);
|
||||||
}
|
}
|
||||||
for (ConsumeEffect effect : effects) if (effect instanceof ConsumeEffect.ApplyStatusEffects apply) {
|
for (ConsumeEffect effect : effects)
|
||||||
|
if (effect instanceof ConsumeEffect.ApplyStatusEffects apply) {
|
||||||
for (PotionEffect pe : apply.effects()) tags.add("effect:" + pe.getType().getKey());
|
for (PotionEffect pe : apply.effects()) tags.add("effect:" + pe.getType().getKey());
|
||||||
}
|
}
|
||||||
return new Ingredient(nutrition, saturation, List.copyOf(effects), Set.copyOf(tags), color);
|
return new Ingredient(nutrition, saturation, List.copyOf(effects), Set.copyOf(tags), color);
|
||||||
@@ -136,13 +202,17 @@ public final class Ingredients {
|
|||||||
public String rejection(List<ItemStack> items) {
|
public String rejection(List<ItemStack> items) {
|
||||||
List<Ingredient> data = items.stream().map(this::read).toList();
|
List<Ingredient> data = items.stream().map(this::read).toList();
|
||||||
if (data.contains(null)) return "Предмет больше не зарегистрирован как ингредиент.";
|
if (data.contains(null)) return "Предмет больше не зарегистрирован как ингредиент.";
|
||||||
String rule = CombinationRules.rejection(data.stream().map(Ingredient::tags).toList(), blocked, pairs);
|
String rule =
|
||||||
|
CombinationRules.rejection(
|
||||||
|
data.stream().map(Ingredient::tags).toList(), blocked, pairs);
|
||||||
if (rule != null) return rule;
|
if (rule != null) return rule;
|
||||||
long nutrition = data.stream().mapToLong(Ingredient::nutrition).sum();
|
long nutrition = data.stream().mapToLong(Ingredient::nutrition).sum();
|
||||||
double saturation = data.stream().mapToDouble(Ingredient::saturation).sum();
|
double saturation = data.stream().mapToDouble(Ingredient::saturation).sum();
|
||||||
if (nutrition > plugin.getConfig().getInt("max-nutrition", 1000)
|
if (nutrition > plugin.getConfig().getInt("max-nutrition", 1000)
|
||||||
|| saturation > plugin.getConfig().getDouble("max-saturation", 1000)) return "Превышен лимит питания супа.";
|
|| saturation > plugin.getConfig().getDouble("max-saturation", 1000))
|
||||||
if (data.stream().mapToInt(i -> i.effects.size()).sum() > 256) return "В супе слишком много эффектов.";
|
return "Превышен лимит питания супа.";
|
||||||
|
if (data.stream().mapToInt(i -> i.effects.size()).sum() > 256)
|
||||||
|
return "В супе слишком много эффектов.";
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,60 +220,131 @@ public final class Ingredients {
|
|||||||
String error = rejection(items);
|
String error = rejection(items);
|
||||||
if (error != null) throw new IllegalArgumentException(error);
|
if (error != null) throw new IllegalArgumentException(error);
|
||||||
// Stable order makes the same recipe stack regardless of insertion order.
|
// Stable order makes the same recipe stack regardless of insertion order.
|
||||||
List<Ingredient> ingredients = items.stream().map(ItemStack::asOne)
|
List<Ingredient> ingredients =
|
||||||
|
items.stream()
|
||||||
|
.map(ItemStack::asOne)
|
||||||
.peek(Ingredients::normalize)
|
.peek(Ingredients::normalize)
|
||||||
.sorted(Comparator.comparing(stack -> Base64.getEncoder().encodeToString(stack.serializeAsBytes())))
|
.sorted(
|
||||||
.map(this::read).toList();
|
Comparator.comparing(
|
||||||
|
stack ->
|
||||||
|
Base64.getEncoder()
|
||||||
|
.encodeToString(stack.serializeAsBytes())))
|
||||||
|
.map(this::read)
|
||||||
|
.toList();
|
||||||
int nutrition = ingredients.stream().mapToInt(Ingredient::nutrition).sum();
|
int nutrition = ingredients.stream().mapToInt(Ingredient::nutrition).sum();
|
||||||
float saturation = (float) ingredients.stream().mapToDouble(Ingredient::saturation).sum();
|
float saturation = (float) ingredients.stream().mapToDouble(Ingredient::saturation).sum();
|
||||||
List<ConsumeEffect> effects = ingredients.stream().flatMap(i -> i.effects.stream()).toList();
|
List<ConsumeEffect> effects =
|
||||||
|
ingredients.stream().flatMap(i -> i.effects.stream()).toList();
|
||||||
ItemStack soup = new ItemStack(Material.MUSHROOM_STEW);
|
ItemStack soup = new ItemStack(Material.MUSHROOM_STEW);
|
||||||
ItemMeta meta = soup.getItemMeta();
|
ItemMeta meta = soup.getItemMeta();
|
||||||
meta.displayName(Component.text(plugin.getConfig().getString("soup-name", "Комбинированный суп"),
|
meta.displayName(
|
||||||
net.kyori.adventure.text.format.TextColor.color(color(ingredients).asRGB())).decoration(TextDecoration.ITALIC, false));
|
Component.text(
|
||||||
|
plugin.getConfig().getString("soup-name", "Комбинированный суп"),
|
||||||
|
net.kyori.adventure.text.format.TextColor.color(
|
||||||
|
color(ingredients).asRGB()))
|
||||||
|
.decoration(TextDecoration.ITALIC, false));
|
||||||
meta.lore(soupLore(nutrition, saturation, effects));
|
meta.lore(soupLore(nutrition, saturation, effects));
|
||||||
meta.getPersistentDataContainer().set(plugin.soupKey, PersistentDataType.BYTE, (byte) 1);
|
meta.getPersistentDataContainer().set(plugin.soupKey, PersistentDataType.BYTE, (byte) 1);
|
||||||
meta.getPersistentDataContainer().set(plugin.colorKey, PersistentDataType.INTEGER, color(ingredients).asRGB());
|
meta.getPersistentDataContainer()
|
||||||
|
.set(plugin.colorKey, PersistentDataType.INTEGER, color(ingredients).asRGB());
|
||||||
soup.setItemMeta(meta);
|
soup.setItemMeta(meta);
|
||||||
soup.setData(DataComponentTypes.FOOD, FoodProperties.food().nutrition(nutrition).saturation(saturation).canAlwaysEat(true).build());
|
soup.setData(
|
||||||
soup.setData(DataComponentTypes.CONSUMABLE, Consumable.consumable().effects(effects).build());
|
DataComponentTypes.FOOD,
|
||||||
soup.setData(DataComponentTypes.USE_REMAINDER, UseRemainder.useRemainder(new ItemStack(Material.BOWL)));
|
FoodProperties.food()
|
||||||
|
.nutrition(nutrition)
|
||||||
|
.saturation(saturation)
|
||||||
|
.canAlwaysEat(true)
|
||||||
|
.build());
|
||||||
|
soup.setData(
|
||||||
|
DataComponentTypes.CONSUMABLE, Consumable.consumable().effects(effects).build());
|
||||||
|
soup.setData(
|
||||||
|
DataComponentTypes.USE_REMAINDER,
|
||||||
|
UseRemainder.useRemainder(new ItemStack(Material.BOWL)));
|
||||||
normalize(soup);
|
normalize(soup);
|
||||||
return soup;
|
return soup;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static List<Component> soupLore(int nutrition, float saturation, List<ConsumeEffect> effects) {
|
private static List<Component> soupLore(
|
||||||
|
int nutrition, float saturation, List<ConsumeEffect> effects) {
|
||||||
List<Component> lore = new ArrayList<>();
|
List<Component> lore = new ArrayList<>();
|
||||||
lore.add(line("Голод: +" + nutrition, NamedTextColor.YELLOW));
|
lore.add(line("Голод: +" + nutrition, NamedTextColor.YELLOW));
|
||||||
lore.add(line(String.format(Locale.ROOT, "Насыщение: +%.1f", saturation), NamedTextColor.GOLD));
|
lore.add(
|
||||||
|
line(
|
||||||
|
String.format(Locale.ROOT, "Насыщение: +%.1f", saturation),
|
||||||
|
NamedTextColor.GOLD));
|
||||||
for (ConsumeEffect effect : effects) {
|
for (ConsumeEffect effect : effects) {
|
||||||
if (effect instanceof ConsumeEffect.ApplyStatusEffects apply) {
|
if (effect instanceof ConsumeEffect.ApplyStatusEffects apply) {
|
||||||
for (PotionEffect pe : apply.effects()) {
|
for (PotionEffect pe : apply.effects()) {
|
||||||
String duration = pe.isInfinite() ? "∞" : (pe.getDuration() / 1200) + ":" + String.format(Locale.ROOT, "%02d", (pe.getDuration() / 20) % 60);
|
String duration =
|
||||||
lore.add(Component.translatable(pe.getType().translationKey()).color(NamedTextColor.AQUA)
|
pe.isInfinite()
|
||||||
.append(Component.text(" " + SoupText.roman(pe.getAmplifier() + 1) + " (" + duration + ")"
|
? "∞"
|
||||||
+ (apply.probability() < 1 ? " " + Math.round(apply.probability() * 100) + "%" : "")))
|
: (pe.getDuration() / 1200)
|
||||||
|
+ ":"
|
||||||
|
+ String.format(
|
||||||
|
Locale.ROOT,
|
||||||
|
"%02d",
|
||||||
|
(pe.getDuration() / 20) % 60);
|
||||||
|
lore.add(
|
||||||
|
Component.translatable(pe.getType().translationKey())
|
||||||
|
.color(NamedTextColor.AQUA)
|
||||||
|
.append(
|
||||||
|
Component.text(
|
||||||
|
" "
|
||||||
|
+ SoupText.roman(pe.getAmplifier() + 1)
|
||||||
|
+ " ("
|
||||||
|
+ duration
|
||||||
|
+ ")"
|
||||||
|
+ (apply.probability() < 1
|
||||||
|
? " "
|
||||||
|
+ Math.round(
|
||||||
|
apply
|
||||||
|
.probability()
|
||||||
|
* 100)
|
||||||
|
+ "%"
|
||||||
|
: "")))
|
||||||
.decoration(TextDecoration.ITALIC, false));
|
.decoration(TextDecoration.ITALIC, false));
|
||||||
}
|
}
|
||||||
} else lore.add(line(effect instanceof ConsumeEffect.TeleportRandomly ? "Случайная телепортация"
|
} else
|
||||||
: effect instanceof ConsumeEffect.ClearAllStatusEffects ? "Снятие всех эффектов"
|
lore.add(
|
||||||
: effect instanceof ConsumeEffect.RemoveStatusEffects ? "Снятие эффектов" : "Звук при употреблении", NamedTextColor.GRAY));
|
line(
|
||||||
|
effect instanceof ConsumeEffect.TeleportRandomly
|
||||||
|
? "Случайная телепортация"
|
||||||
|
: effect instanceof ConsumeEffect.ClearAllStatusEffects
|
||||||
|
? "Снятие всех эффектов"
|
||||||
|
: effect
|
||||||
|
instanceof
|
||||||
|
ConsumeEffect.RemoveStatusEffects
|
||||||
|
? "Снятие эффектов"
|
||||||
|
: "Звук при употреблении",
|
||||||
|
NamedTextColor.GRAY));
|
||||||
}
|
}
|
||||||
return lore;
|
return lore;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Component line(String s, NamedTextColor color) { return Component.text(s, color).decoration(TextDecoration.ITALIC, false); }
|
private static Component line(String s, NamedTextColor color) {
|
||||||
|
return Component.text(s, color).decoration(TextDecoration.ITALIC, false);
|
||||||
|
}
|
||||||
|
|
||||||
private Color color(List<Ingredient> ingredients) {
|
private Color color(List<Ingredient> ingredients) {
|
||||||
return Color.fromRGB((int) ingredients.stream().mapToInt(i -> i.color.getRed()).average().orElse(183),
|
return Color.fromRGB(
|
||||||
|
(int) ingredients.stream().mapToInt(i -> i.color.getRed()).average().orElse(183),
|
||||||
(int) ingredients.stream().mapToInt(i -> i.color.getGreen()).average().orElse(122),
|
(int) ingredients.stream().mapToInt(i -> i.color.getGreen()).average().orElse(122),
|
||||||
(int) ingredients.stream().mapToInt(i -> i.color.getBlue()).average().orElse(54));
|
(int) ingredients.stream().mapToInt(i -> i.color.getBlue()).average().orElse(54));
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isCombined(ItemStack item) {
|
public boolean isCombined(ItemStack item) {
|
||||||
return item.hasItemMeta() && item.getItemMeta().getPersistentDataContainer().has(plugin.soupKey, PersistentDataType.BYTE);
|
return item.hasItemMeta()
|
||||||
|
&& item.getItemMeta()
|
||||||
|
.getPersistentDataContainer()
|
||||||
|
.has(plugin.soupKey, PersistentDataType.BYTE);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean normalize(ItemStack item) {
|
public static boolean normalize(ItemStack item) {
|
||||||
if (item == null) return false;
|
if (item == null) return false;
|
||||||
if (!switch (item.getType()) { case MUSHROOM_STEW, RABBIT_STEW, BEETROOT_SOUP, SUSPICIOUS_STEW -> true; default -> false; }) return false;
|
if (!switch (item.getType()) {
|
||||||
|
case MUSHROOM_STEW, RABBIT_STEW, BEETROOT_SOUP, SUSPICIOUS_STEW -> true;
|
||||||
|
default -> false;
|
||||||
|
}) return false;
|
||||||
boolean changed = false;
|
boolean changed = false;
|
||||||
if (!Objects.equals(item.getData(DataComponentTypes.MAX_STACK_SIZE), 16)) {
|
if (!Objects.equals(item.getData(DataComponentTypes.MAX_STACK_SIZE), 16)) {
|
||||||
item.setData(DataComponentTypes.MAX_STACK_SIZE, 16);
|
item.setData(DataComponentTypes.MAX_STACK_SIZE, 16);
|
||||||
@@ -212,10 +353,19 @@ public final class Ingredients {
|
|||||||
ItemMeta meta = item.getItemMeta();
|
ItemMeta meta = item.getItemMeta();
|
||||||
FoodProperties food = item.getData(DataComponentTypes.FOOD);
|
FoodProperties food = item.getData(DataComponentTypes.FOOD);
|
||||||
Consumable consumable = item.getData(DataComponentTypes.CONSUMABLE);
|
Consumable consumable = item.getData(DataComponentTypes.CONSUMABLE);
|
||||||
if (meta.getPersistentDataContainer().has(new NamespacedKey("astrasoups", "combined_soup"), PersistentDataType.BYTE)
|
if (meta.getPersistentDataContainer()
|
||||||
&& food != null && consumable != null) {
|
.has(
|
||||||
List<Component> lore = soupLore(food.nutrition(), food.saturation(), consumable.consumeEffects());
|
new NamespacedKey("astrasoups", "combined_soup"),
|
||||||
if (!Objects.equals(meta.lore(), lore)) { meta.lore(lore); item.setItemMeta(meta); changed = true; }
|
PersistentDataType.BYTE)
|
||||||
|
&& food != null
|
||||||
|
&& consumable != null) {
|
||||||
|
List<Component> lore =
|
||||||
|
soupLore(food.nutrition(), food.saturation(), consumable.consumeEffects());
|
||||||
|
if (!Objects.equals(meta.lore(), lore)) {
|
||||||
|
meta.lore(lore);
|
||||||
|
item.setItemMeta(meta);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return changed;
|
return changed;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,13 +2,17 @@ package online.astradev.soups;
|
|||||||
|
|
||||||
final class SoupText {
|
final class SoupText {
|
||||||
private SoupText() {}
|
private SoupText() {}
|
||||||
|
|
||||||
static String roman(int level) {
|
static String roman(int level) {
|
||||||
if (level < 1 || level > 256) throw new IllegalArgumentException("Potion level out of range: " + level);
|
if (level < 1 || level > 256)
|
||||||
|
throw new IllegalArgumentException("Potion level out of range: " + level);
|
||||||
int[] values = {100, 90, 50, 40, 10, 9, 5, 4, 1};
|
int[] values = {100, 90, 50, 40, 10, 9, 5, 4, 1};
|
||||||
String[] numerals = {"C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
|
String[] numerals = {"C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
|
||||||
StringBuilder text = new StringBuilder();
|
StringBuilder text = new StringBuilder();
|
||||||
for (int i = 0; i < values.length; i++) while (level >= values[i]) {
|
for (int i = 0; i < values.length; i++)
|
||||||
text.append(numerals[i]); level -= values[i];
|
while (level >= values[i]) {
|
||||||
|
text.append(numerals[i]);
|
||||||
|
level -= values[i];
|
||||||
}
|
}
|
||||||
return text.toString();
|
return text.toString();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,11 +2,10 @@
|
|||||||
# Одна варка даёт четыре порции; каждая получает питание и эффекты всего состава.
|
# Одна варка даёт четыре порции; каждая получает питание и эффекты всего состава.
|
||||||
servings-per-brew: 4
|
servings-per-brew: 4
|
||||||
require-full-water: true
|
require-full-water: true
|
||||||
# Варка с водоворотом, в секундах (0.5–60). 20 тиков = 1 секунда.
|
# Время варки в секундах (0.5–60).
|
||||||
brew-seconds: 4.0
|
brew-seconds: 4.0
|
||||||
soup-name: 'Комбинированный суп'
|
soup-name: 'Комбинированный суп'
|
||||||
# Резервный цвет неизвестной еды. Известные продукты имеют собственные цвета,
|
# Цвет ингредиентов, для которых не задан собственный RGB.
|
||||||
# зелья передают свой RGB. Поверхность супа показывает среднее RGB четырёх ингредиентов.
|
|
||||||
default-color: '#B77A36'
|
default-color: '#B77A36'
|
||||||
# Ограничения предотвращают переполнение при многократной варке супов из супов.
|
# Ограничения предотвращают переполнение при многократной варке супов из супов.
|
||||||
max-nutrition: 1000
|
max-nutrition: 1000
|
||||||
@@ -14,7 +13,7 @@ max-saturation: 1000.0
|
|||||||
# Селекторы: material:BEEF, effect:minecraft:poison, custom:my_food,
|
# Селекторы: material:BEEF, effect:minecraft:poison, custom:my_food,
|
||||||
# itemsadder:namespace:id, soup:combined, * (любой ингредиент).
|
# itemsadder:namespace:id, soup:combined, * (любой ингредиент).
|
||||||
blocked-ingredients: []
|
blocked-ingredients: []
|
||||||
# Каждое правило запрещает одновременное присутствие двух РАЗНЫХ слотов.
|
# Правило применяется к двум разным слотам.
|
||||||
# incompatible:
|
# incompatible:
|
||||||
# - ['effect:minecraft:strength', 'effect:minecraft:weakness']
|
# - ['effect:minecraft:strength', 'effect:minecraft:weakness']
|
||||||
# - ['material:ROTTEN_FLESH', 'material:GOLDEN_APPLE']
|
# - ['material:ROTTEN_FLESH', 'material:GOLDEN_APPLE']
|
||||||
|
|||||||
@@ -1,23 +1,31 @@
|
|||||||
package online.astradev.soups;
|
package online.astradev.soups;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
class CauldronAnimationTest {
|
class CauldronAnimationTest {
|
||||||
@Test void remainsInsideCauldronAtEveryWaterLevel() {
|
@Test
|
||||||
for (int level = 1; level <= 3; level++) for (int tick = 0; tick <= 80; tick++) for (int slot = 0; slot < 4; slot++) {
|
void remainsInsideCauldronAtEveryWaterLevel() {
|
||||||
|
for (int level = 1; level <= 3; level++)
|
||||||
|
for (int tick = 0; tick <= 80; tick++)
|
||||||
|
for (int slot = 0; slot < 4; slot++) {
|
||||||
var p = CauldronAnimation.frame(slot, level, tick, tick, 80);
|
var p = CauldronAnimation.frame(slot, level, tick, tick, 80);
|
||||||
assertTrue(p.x() > .125 && p.x() < .875 && p.z() > .125 && p.z() < .875);
|
assertTrue(p.x() > .125 && p.x() < .875 && p.z() > .125 && p.z() < .875);
|
||||||
assertTrue(p.y() >= .26 && p.y() < .375 + .1875 * level);
|
assertTrue(p.y() >= .26 && p.y() < .375 + .1875 * level);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@Test void displayCenterIsPartlySubmergedWithoutNativeBobbing() {
|
|
||||||
|
@Test
|
||||||
|
void displayCenterIsPartlySubmergedWithoutNativeBobbing() {
|
||||||
for (int tick = 0; tick < 200; tick++) {
|
for (int tick = 0; tick < 200; tick++) {
|
||||||
var p = CauldronAnimation.frame(0, 3, tick, 0, 0);
|
var p = CauldronAnimation.frame(0, 3, tick, 0, 0);
|
||||||
assertTrue(.9375 - p.y() >= .05 && .9375 - p.y() <= .06);
|
assertTrue(.9375 - p.y() >= .05 && .9375 - p.y() <= .06);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@Test void whirlpoolKeepsRadiusThroughoutRotation() {
|
|
||||||
|
@Test
|
||||||
|
void whirlpoolKeepsRadiusThroughoutRotation() {
|
||||||
var start = CauldronAnimation.frame(0, 3, 0, 0, 80);
|
var start = CauldronAnimation.frame(0, 3, 0, 0, 80);
|
||||||
var middle = CauldronAnimation.frame(0, 3, 40, 40, 80);
|
var middle = CauldronAnimation.frame(0, 3, 40, 40, 80);
|
||||||
var end = CauldronAnimation.frame(0, 3, 80, 80, 80);
|
var end = CauldronAnimation.frame(0, 3, 80, 80, 80);
|
||||||
@@ -26,23 +34,40 @@ class CauldronAnimationTest {
|
|||||||
assertEquals(.23, Math.hypot(p.x() - .5, p.z() - .5), .000001);
|
assertEquals(.23, Math.hypot(p.x() - .5, p.z() - .5), .000001);
|
||||||
}
|
}
|
||||||
assertEquals(start.y(), end.y(), .008);
|
assertEquals(start.y(), end.y(), .008);
|
||||||
assertTrue(Math.atan2(middle.z() - .5, middle.x() - .5) != Math.atan2(start.z() - .5, start.x() - .5));
|
assertTrue(
|
||||||
|
Math.atan2(middle.z() - .5, middle.x() - .5)
|
||||||
|
!= Math.atan2(start.z() - .5, start.x() - .5));
|
||||||
}
|
}
|
||||||
@Test void initialPositionDoesNotJumpWhenBrewingStarts() {
|
|
||||||
assertEquals(CauldronAnimation.frame(2, 3, 15, 0, 0), CauldronAnimation.frame(2, 3, 15, 0, 80));
|
@Test
|
||||||
|
void initialPositionDoesNotJumpWhenBrewingStarts() {
|
||||||
|
assertEquals(
|
||||||
|
CauldronAnimation.frame(2, 3, 15, 0, 0), CauldronAnimation.frame(2, 3, 15, 0, 80));
|
||||||
}
|
}
|
||||||
@Test void everyPortionLowersLiquidAndUnderlyingWater() {
|
|
||||||
|
@Test
|
||||||
|
void everyPortionLowersLiquidAndUnderlyingWater() {
|
||||||
for (int remaining = 4; remaining > 0; remaining--) {
|
for (int remaining = 4; remaining > 0; remaining--) {
|
||||||
assertEquals(remaining - 1, CauldronAnimation.waterLevel(remaining, 4));
|
assertEquals(remaining - 1, CauldronAnimation.waterLevel(remaining, 4));
|
||||||
assertTrue(CauldronAnimation.liquidHeight(remaining, 4) > CauldronAnimation.liquidHeight(remaining - 1, 4));
|
assertTrue(
|
||||||
|
CauldronAnimation.liquidHeight(remaining, 4)
|
||||||
|
> CauldronAnimation.liquidHeight(remaining - 1, 4));
|
||||||
int water = CauldronAnimation.waterLevel(remaining, 4);
|
int water = CauldronAnimation.waterLevel(remaining, 4);
|
||||||
if (water > 0) assertTrue(.375 + .1875 * water <= CauldronAnimation.liquidHeight(remaining, 4));
|
if (water > 0)
|
||||||
|
assertTrue(.375 + .1875 * water <= CauldronAnimation.liquidHeight(remaining, 4));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@Test void arbitraryBatchSizesNeverExposeBlueWaterAboveSoup() {
|
|
||||||
for (int capacity = 1; capacity <= 16; capacity++) for (int remaining = 1; remaining <= capacity; remaining++) {
|
@Test
|
||||||
|
void arbitraryBatchSizesNeverExposeBlueWaterAboveSoup() {
|
||||||
|
for (int capacity = 1; capacity <= 16; capacity++)
|
||||||
|
for (int remaining = 1; remaining <= capacity; remaining++) {
|
||||||
int water = CauldronAnimation.waterLevel(remaining, capacity);
|
int water = CauldronAnimation.waterLevel(remaining, capacity);
|
||||||
if (water > 0) assertTrue(.375 + .1875 * water <= CauldronAnimation.liquidHeight(remaining, capacity) + .00001);
|
if (water > 0)
|
||||||
|
assertTrue(
|
||||||
|
.375 + .1875 * water
|
||||||
|
<= CauldronAnimation.liquidHeight(remaining, capacity)
|
||||||
|
+ .00001);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +1,63 @@
|
|||||||
package online.astradev.soups;
|
package online.astradev.soups;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import java.util.*;
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
class CombinationRulesTest {
|
class CombinationRulesTest {
|
||||||
private final List<Set<String>> four = List.of(Set.of("material:beef", "effect:minecraft:strength"), Set.of("material:carrot"), Set.of("material:beef"), Set.of("material:potion", "effect:minecraft:weakness"));
|
private final List<Set<String>> four =
|
||||||
@Test void exactlyFour() {
|
List.of(
|
||||||
|
Set.of("material:beef", "effect:minecraft:strength"),
|
||||||
|
Set.of("material:carrot"),
|
||||||
|
Set.of("material:beef"),
|
||||||
|
Set.of("material:potion", "effect:minecraft:weakness"));
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void exactlyFour() {
|
||||||
assertNotNull(CombinationRules.rejection(four.subList(0, 3), List.of(), List.of()));
|
assertNotNull(CombinationRules.rejection(four.subList(0, 3), List.of(), List.of()));
|
||||||
assertNull(CombinationRules.rejection(four, List.of(), List.of()));
|
assertNull(CombinationRules.rejection(four, List.of(), List.of()));
|
||||||
}
|
}
|
||||||
@Test void blockedSelectorsAreCaseInsensitive() {
|
|
||||||
|
@Test
|
||||||
|
void blockedSelectorsAreCaseInsensitive() {
|
||||||
assertNotNull(CombinationRules.rejection(four, List.of("material:BEEF"), List.of()));
|
assertNotNull(CombinationRules.rejection(four, List.of("material:BEEF"), List.of()));
|
||||||
}
|
}
|
||||||
@Test void compatibilityIsSymmetricAcrossSlots() {
|
|
||||||
assertNotNull(CombinationRules.rejection(four, List.of(), List.of(List.of("effect:minecraft:weakness", "effect:minecraft:strength"))));
|
@Test
|
||||||
|
void compatibilityIsSymmetricAcrossSlots() {
|
||||||
|
assertNotNull(
|
||||||
|
CombinationRules.rejection(
|
||||||
|
four,
|
||||||
|
List.of(),
|
||||||
|
List.of(
|
||||||
|
List.of(
|
||||||
|
"effect:minecraft:weakness",
|
||||||
|
"effect:minecraft:strength"))));
|
||||||
}
|
}
|
||||||
@Test void oneIngredientDoesNotConflictWithItself() {
|
|
||||||
assertNull(CombinationRules.rejection(four, List.of(), List.of(List.of("material:potion", "effect:minecraft:weakness"))));
|
@Test
|
||||||
|
void oneIngredientDoesNotConflictWithItself() {
|
||||||
|
assertNull(
|
||||||
|
CombinationRules.rejection(
|
||||||
|
four,
|
||||||
|
List.of(),
|
||||||
|
List.of(List.of("material:potion", "effect:minecraft:weakness"))));
|
||||||
}
|
}
|
||||||
@Test void duplicatesCanBeForbiddenExplicitly() {
|
|
||||||
assertNotNull(CombinationRules.rejection(four, List.of(), List.of(List.of("material:beef", "material:beef"))));
|
@Test
|
||||||
assertNull(CombinationRules.rejection(four, List.of(), List.of(List.of("material:carrot", "material:carrot"))));
|
void duplicatesCanBeForbiddenExplicitly() {
|
||||||
|
assertNotNull(
|
||||||
|
CombinationRules.rejection(
|
||||||
|
four, List.of(), List.of(List.of("material:beef", "material:beef"))));
|
||||||
|
assertNull(
|
||||||
|
CombinationRules.rejection(
|
||||||
|
four, List.of(), List.of(List.of("material:carrot", "material:carrot"))));
|
||||||
}
|
}
|
||||||
@Test void wildcardAndUnknownSelector() {
|
|
||||||
|
@Test
|
||||||
|
void wildcardAndUnknownSelector() {
|
||||||
assertNotNull(CombinationRules.rejection(four, List.of("*"), List.of()));
|
assertNotNull(CombinationRules.rejection(four, List.of("*"), List.of()));
|
||||||
assertNull(CombinationRules.rejection(four, List.of("custom:other"), List.of()));
|
assertNull(CombinationRules.rejection(four, List.of("custom:other"), List.of()));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,18 @@
|
|||||||
package online.astradev.soups;
|
package online.astradev.soups;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
class SoupTextTest {
|
class SoupTextTest {
|
||||||
@Test void formatsPotionLevelsAsRomanNumerals() {
|
@Test
|
||||||
assertEquals("I", SoupText.roman(1)); assertEquals("II", SoupText.roman(2));
|
void formatsPotionLevelsAsRomanNumerals() {
|
||||||
assertEquals("IV", SoupText.roman(4)); assertEquals("IX", SoupText.roman(9));
|
assertEquals("I", SoupText.roman(1));
|
||||||
assertEquals("XL", SoupText.roman(40)); assertEquals("XC", SoupText.roman(90));
|
assertEquals("II", SoupText.roman(2));
|
||||||
|
assertEquals("IV", SoupText.roman(4));
|
||||||
|
assertEquals("IX", SoupText.roman(9));
|
||||||
|
assertEquals("XL", SoupText.roman(40));
|
||||||
|
assertEquals("XC", SoupText.roman(90));
|
||||||
assertEquals("CCLVI", SoupText.roman(256));
|
assertEquals("CCLVI", SoupText.roman(256));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user