diff --git a/doc/COMBAT_RESTRUCTURE_NOTES.md b/doc/COMBAT_RESTRUCTURE_NOTES.md index 0a820a77..fae60eba 100644 --- a/doc/COMBAT_RESTRUCTURE_NOTES.md +++ b/doc/COMBAT_RESTRUCTURE_NOTES.md @@ -22,8 +22,10 @@ Update this file in the same pull request whenever something here stops being tr | 1. Extract the calculator (1.1) and the vanilla modifier bridge (1.2) | Done | | 2. The shared contract | Done with 2.2c, which adds the `attached-damage-types` key | | 3. Fabled migration | Next | -| 4.2 Stat snapshots | Done, in this pull request (#372). 4.1 and 4.3 are not started; 4.2b is next after them | -| 4 (rest) and 5 | Not started | +| 4.1 Formulas in `combat.yml` | In review (#387) | +| 4.2 Stat snapshots | Done (#385) | +| 4.2b Vanilla Thorns | Done (#384) | +| 4.3 and 5 | Not started | ## Rules for every pull request @@ -158,6 +160,47 @@ lift the cap in the test and restore it. roll fails or succeeds, the invulnerability reduction read, and resistance counting toward the absorption cap. Only `VanillaDamageBridgeTest` catches them, so keep that test when the bridge changes. +## Formulas in `combat.yml` (4.1) + +- **Where things are.** `config/CombatCfg` loads and migrates the file and holds what is in force. + `manager/damage/formula/` holds `CombatExpression` (the four expressions, their variables and their default + text), `CombatPreset`, `CombatFormulas` (compiled set plus overrides) and `Formulas`. + `DamageCalculator` keeps the stage order and the bookkeeping between stages; the numbers come from the expressions. +- **Expressions are compiled once with Codex's `Evaluator.compile`** (needs Codex `1.3.0-dev.2`, which is why + `MIN_CORE_VERSION` was raised). A `CompiledExpression` is immutable and safe from any thread, binds variables by + position and returns NaN and infinity as they are, so `CombatFormulas` checks every expression against the sample + values in `CombatExpression` at load. Syntax follows Javaluator: `^` is left associative. **Javaluator, which + Codex bundles, computes `x * 2^-1` wrongly without complaining** (the old string evaluator does too), so + `CombatFormulas` rejects any override with `^` followed by a minus and tells the admin to write `2^(-1)`. Remove + that check only once Codex has fixed the parser. +- **`DamageCalculator` keeps no state between calls** and builds a fresh argument array for each evaluation, so one + calculator can be shared between threads and kept across hits (the stat snapshots in 4.2 may want that). It used + to reuse arrays to avoid the allocation; measured on the benchmark that saved nothing noticeable, and it made + sharing a calculator unsafe. `CombatFormulasTest` has a test that shares one calculator between eight threads and + one that reuses it for many calls; keep both if the calculator changes. +- **`ReferenceDamageCalculator` (test sources) is the formula as it was written in Java.** The equivalence test + compares bit for bit against it for both presets. Never edit its arithmetic to make a test pass. +- **`EngineCfg.LEGACY_COMBAT` is a deprecated override and nothing sets it.** `CombatCharacterizationTest` and + `DamageCalculatorTest` still set it (or `Modifiers.legacyCombat`) to run the legacy preset, which is why the + field and `Modifiers.legacyCombat` still exist. The old `engine.yml` key is read into + `EngineCfg.LEGACY_COMBAT_OLD_KEY` only so migration can pick a preset, and is ignored once `combat.yml` exists. + Do not make production code write `LEGACY_COMBAT` again: a stale `legacy-combat: true` in an old `engine.yml` + would then override the preset in `combat.yml`. +- **Reload.** `Divinity#reload` (Codex's `CodexPlugin#reload`, what a config reload runs) goes through + `ConfigManager.setup`, which calls `Divinity#setConfig`; `CombatCfg.load` runs there after `EngineCfg`, and the + order matters because migration reads the old `legacy-combat` key `EngineCfg` has just read. `CombatReloadTest` + uses the real `plugin.reload()` under MockBukkit and fails if the order changes or `CombatCfg.load` leaves + that path. +- **Variable names use underscores** (`pvp_pve_damage`), because a hyphen is the minus operator. `pvp_pve_damage` and + `pvp_pve_defense` are the PvP values when both sides are players, which is why the names say so. +- **Presets that give NaN or infinity keep doing so.** Only a formula the config overrides is replaced by the + preset's result at hit time; a preset's own non-finite result is passed on as the Java formula always did. +- **Benchmark.** `DamageCalculatorBenchmark` (test sources, not a test, has a `main`) compares the replaced Java + formulas with the configured ones on the same inputs. Run it after changing the evaluator. With Codex + `1.3.0-dev.2` the configured formulas are about 15 times slower on this calculator-only benchmark (roughly 400 ns + against 27 ns per hit, ten evaluations at about 35 ns); that is over the 1.5x the pull request aimed for and is + discussed in its description. + ## Stat snapshots (4.2) Read this before you touch `EntityStats`, `StatSnapshot`, `ProjectileStats` or the equipment handlers in diff --git a/src/main/java/studio/magemonkey/divinity/DependencyRequirement.java b/src/main/java/studio/magemonkey/divinity/DependencyRequirement.java index ce7f403c..babd4321 100644 --- a/src/main/java/studio/magemonkey/divinity/DependencyRequirement.java +++ b/src/main/java/studio/magemonkey/divinity/DependencyRequirement.java @@ -3,10 +3,11 @@ public class DependencyRequirement { /** - * The first Codex build with damage requests, which the damage listener and Divinity's own damage dealers - * use. It is a dev build; the 1.3.0 release and anything later meet it too. + * The first Codex build with damage requests (which the damage listener and Divinity's own damage dealers + * use) and with {@code Evaluator.compile} (which the formulas in combat.yml use). It is a dev build; the 1.3.0 + * release and anything later meet it too. */ - public static final String MIN_CORE_VERSION = "1.3.0-dev.1"; + public static final String MIN_CORE_VERSION = "1.3.0-dev.2"; /** * Whether providedVersion is at least requiredVersion, see {@link #compareVersions}. diff --git a/src/main/java/studio/magemonkey/divinity/Divinity.java b/src/main/java/studio/magemonkey/divinity/Divinity.java index 9c36d58e..103fcdc4 100644 --- a/src/main/java/studio/magemonkey/divinity/Divinity.java +++ b/src/main/java/studio/magemonkey/divinity/Divinity.java @@ -16,6 +16,7 @@ import studio.magemonkey.divinity.command.ModifyCommand; import studio.magemonkey.divinity.command.SetCommand; import studio.magemonkey.divinity.config.Config; +import studio.magemonkey.divinity.config.CombatCfg; import studio.magemonkey.divinity.config.EngineCfg; import studio.magemonkey.divinity.config.Lang; import studio.magemonkey.divinity.data.DivinityUserData; @@ -209,6 +210,8 @@ public void setConfig() { return; } + CombatCfg.load(this); + this.lang = new Lang(this); this.lang.setup(); diff --git a/src/main/java/studio/magemonkey/divinity/config/CombatCfg.java b/src/main/java/studio/magemonkey/divinity/config/CombatCfg.java new file mode 100644 index 00000000..644f6bdb --- /dev/null +++ b/src/main/java/studio/magemonkey/divinity/config/CombatCfg.java @@ -0,0 +1,216 @@ +package studio.magemonkey.divinity.config; + +import com.google.common.annotations.VisibleForTesting; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import studio.magemonkey.divinity.Divinity; +import studio.magemonkey.divinity.manager.damage.formula.CombatExpression; +import studio.magemonkey.divinity.manager.damage.formula.CombatFormulas; +import studio.magemonkey.divinity.manager.damage.formula.CombatPreset; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + +/** + * Loads {@code combat.yml}, the damage formulas, and keeps the result for the damage calculator. + *

+ * Loading never throws and never overwrites an existing {@code combat.yml}. When there is none, one is written: + * from the shipped file, with the preset that matches the old {@code combat.legacy-combat} key of + * {@code engine.yml}. That key is read for this one purpose and is ignored afterwards. + */ +public final class CombatCfg { + + public static final String FILE_NAME = "combat.yml"; + + private static final String PRESET_KEY = "preset"; + private static final String EXPRESSIONS_KEY = "expressions"; + + /** What is in force. Replaced as a whole, so a hit always sees one consistent set. */ + private static volatile State state = State.defaults(); + + private CombatCfg() { + } + + /** Loads (and if needed creates) {@code combat.yml} in the plugin's data folder. Call again to reload. */ + public static void load(@NotNull Divinity plugin) { + load(plugin.getDataFolder(), + EngineCfg.LEGACY_COMBAT_OLD_KEY, + plugin.getLogger()::info, + plugin.getLogger()::warning); + } + + /** + * @param folder the folder that holds (or will hold) {@code combat.yml} + * @param oldLegacyKey the value of {@code combat.legacy-combat} in {@code engine.yml}, or null if it is not there + * @param info receives the one line that reports a migration + * @param warn receives every problem, each once + */ + public static void load(@NotNull File folder, + @Nullable Boolean oldLegacyKey, + @NotNull Consumer info, + @NotNull Consumer warn) { + File file = new File(folder, FILE_NAME); + + CombatPreset migrated = null; + if (!file.exists()) { + migrated = migrate(file, oldLegacyKey, info, warn); + } + + CombatPreset preset = migrated != null ? migrated : CombatPreset.DEFAULT; + Map overrides = new HashMap<>(); + + if (file.exists()) { + YamlConfiguration yaml = new YamlConfiguration(); + try { + yaml.load(file); + preset = readPreset(yaml, warn); + overrides = readOverrides(yaml, warn); + } catch (IOException | InvalidConfigurationException | RuntimeException e) { + warn.accept(FILE_NAME + " could not be read (" + e.getMessage() + "). Using the " + + CombatPreset.DEFAULT.key() + " preset. The file is left as it is."); + preset = CombatPreset.DEFAULT; + overrides.clear(); + } + } + + // Only the preset in use reports its problems; the other one is built for the deprecated override below + CombatFormulas[] byPreset = new CombatFormulas[CombatPreset.values().length]; + for (CombatPreset each : CombatPreset.values()) { + byPreset[each.ordinal()] = CombatFormulas.build(each, overrides, each == preset ? warn : null); + } + state = new State(preset, byPreset); + } + + /** + * The formulas the damage calculator uses. + * + * @param forceLegacy selects the legacy preset whatever {@code combat.yml} says. Nothing in the plugin sets + * this; it exists for callers of the old {@code EngineCfg.LEGACY_COMBAT} switch. + */ + @NotNull + public static CombatFormulas formulas(boolean forceLegacy) { + State current = state; + return current.byPreset[(forceLegacy ? CombatPreset.LEGACY : current.preset).ordinal()]; + } + + /** The preset {@code combat.yml} selects. */ + @NotNull + public static CombatPreset preset() { + return state.preset; + } + + /** Back to the shipped default preset with no overrides, as before anything was loaded. */ + @VisibleForTesting + public static void resetToDefaults() { + state = State.defaults(); + } + + /** + * Writes {@code combat.yml} for a server that has none. + * + * @return the preset the old key selects, or null if nothing was migrated (no old key, and no file written) + */ + @Nullable + private static CombatPreset migrate(@NotNull File file, + @Nullable Boolean oldLegacyKey, + @NotNull Consumer info, + @NotNull Consumer warn) { + CombatPreset preset = Boolean.TRUE.equals(oldLegacyKey) ? CombatPreset.LEGACY : CombatPreset.DEFAULT; + + String shipped = readShipped(); + if (shipped == null) { + warn.accept(FILE_NAME + " is missing from the plugin jar, so none was written."); + return preset; + } + String text = shipped.replaceFirst("(?m)^preset: default\\s*$", "preset: " + preset.key()); + + try { + File parent = file.getParentFile(); + if (parent != null) parent.mkdirs(); + // CREATE_NEW: an existing file is never overwritten, even if one appears after the check above + Files.write(file.toPath(), text.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE_NEW); + } catch (FileAlreadyExistsException e) { + return null; + } catch (IOException e) { + warn.accept(FILE_NAME + " could not be written (" + e.getMessage() + "). Using the " + + preset.key() + " preset for this run."); + return preset; + } + + if (oldLegacyKey != null) { + info.accept("Moved 'combat.legacy-combat: " + oldLegacyKey + "' from engine.yml to " + FILE_NAME + + " (preset: " + preset.key() + "). The old key is now ignored."); + } + return preset; + } + + @Nullable + private static String readShipped() { + try (InputStream in = CombatCfg.class.getResourceAsStream("/" + FILE_NAME)) { + if (in == null) return null; + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + return null; + } + } + + @NotNull + private static CombatPreset readPreset(@NotNull YamlConfiguration yaml, @NotNull Consumer warn) { + Object value = yaml.get(PRESET_KEY); + if (value == null) return CombatPreset.DEFAULT; + + CombatPreset preset = CombatPreset.byKey(String.valueOf(value)); + if (preset == null) { + warn.accept(FILE_NAME + ": unknown preset '" + value + "' (use 'default' or 'legacy'). Using '" + + CombatPreset.DEFAULT.key() + "'."); + return CombatPreset.DEFAULT; + } + return preset; + } + + @NotNull + private static Map readOverrides(@NotNull YamlConfiguration yaml, + @NotNull Consumer warn) { + Map overrides = new HashMap<>(); + ConfigurationSection section = yaml.getConfigurationSection(EXPRESSIONS_KEY); + if (section == null) return overrides; + + for (String key : section.getKeys(false)) { + if (CombatExpression.byKey(key) == null) { + warn.accept(FILE_NAME + ": '" + key + "' is not a formula and is ignored."); + continue; + } + overrides.put(key, section.get(key)); + } + return overrides; + } + + private static final class State { + final CombatPreset preset; + final CombatFormulas[] byPreset; + + State(@NotNull CombatPreset preset, @NotNull CombatFormulas[] byPreset) { + this.preset = preset; + this.byPreset = byPreset; + } + + static State defaults() { + CombatFormulas[] all = new CombatFormulas[CombatPreset.values().length]; + for (CombatPreset each : CombatPreset.values()) { + all[each.ordinal()] = CombatFormulas.of(each); + } + return new State(CombatPreset.DEFAULT, all); + } + } +} diff --git a/src/main/java/studio/magemonkey/divinity/config/EngineCfg.java b/src/main/java/studio/magemonkey/divinity/config/EngineCfg.java index 84a3f4ac..04da7de6 100644 --- a/src/main/java/studio/magemonkey/divinity/config/EngineCfg.java +++ b/src/main/java/studio/magemonkey/divinity/config/EngineCfg.java @@ -56,7 +56,19 @@ public EngineCfg(@NotNull Divinity plugin) throws InvalidConfigurationException public static double COMBAT_SHIELD_BLOCK_BONUS_RATE; public static double COMBAT_SHIELD_BLOCK_BONUS_DAMAGE_MOD; public static int COMBAT_SHIELD_BLOCK_COOLDOWN; + /** + * Forces the legacy preset's formulas, whatever {@code combat.yml} says. + * + * @deprecated Nothing sets this any more: {@code combat.legacy-combat} moved to {@code combat.yml}'s + * {@code preset}, see {@code CombatCfg}. It stays so that code written against the old switch keeps working. + */ + @Deprecated public static boolean LEGACY_COMBAT; + /** + * The value of the old {@code combat.legacy-combat} key in {@code engine.yml}, or null if it is not there. + * Read only so that {@code CombatCfg} can choose the matching preset when it writes {@code combat.yml}. + */ + public static Boolean LEGACY_COMBAT_OLD_KEY; /** Longest time, in ticks, that what was worked out from an entity's gear is reused. 0 turns the cache off. */ public static int PERFORMANCE_STAT_SNAPSHOT_MAX_AGE = 20; public static boolean COMBAT_DISABLE_VANILLA_SWEEP; @@ -219,7 +231,8 @@ public void setup() { // C O M B A T // path = "combat."; - EngineCfg.LEGACY_COMBAT = cfg.getBoolean(path + "legacy-combat", false); + EngineCfg.LEGACY_COMBAT_OLD_KEY = + cfg.contains(path + "legacy-combat") ? cfg.getBoolean(path + "legacy-combat") : null; EngineCfg.COMBAT_DISABLE_VANILLA_SWEEP = cfg.getBoolean(path + "disable-vanilla-sweep-attack"); EngineCfg.COMBAT_REDUCE_PLAYER_HEALTH_BAR = cfg.getBoolean(path + "compress-player-health-bar"); EngineCfg.COMBAT_FISHING_HOOK_DO_DAMAGE = cfg.getBoolean(path + "fishing-hook-do-damage"); diff --git a/src/main/java/studio/magemonkey/divinity/manager/damage/DamageCalculator.java b/src/main/java/studio/magemonkey/divinity/manager/damage/DamageCalculator.java index 4f1833f2..f5fcb3f0 100644 --- a/src/main/java/studio/magemonkey/divinity/manager/damage/DamageCalculator.java +++ b/src/main/java/studio/magemonkey/divinity/manager/damage/DamageCalculator.java @@ -2,20 +2,33 @@ import lombok.Value; import org.jetbrains.annotations.Nullable; +import studio.magemonkey.divinity.config.CombatCfg; +import studio.magemonkey.divinity.manager.damage.formula.CombatExpression; +import studio.magemonkey.divinity.manager.damage.formula.CombatFormulas; /** - * The damage formula, on plain numbers. It needs no Bukkit and no plugin instance. + * The damage calculation, on plain numbers. It needs no Bukkit and no plugin instance. *

* {@link DamageManager} does the lookups (stats, attributes, hooks, enchantments) and passes the results in. - * The order of the floating-point operations is deliberately the same as it was when the formula lived in - * {@code DamageManager#onDamageRPGStart}; do not reorder them. + * The numbers come from the expressions in {@code combat.yml} ({@link CombatExpression}); what stays here is the + * order of the stages and the bookkeeping between them. With the shipped default the results are bit for bit what + * the formulas gave when they were written in Java, and the same holds for the legacy preset. + *

+ * A calculator holds no state between calls, so one may be shared between threads and kept across hits. */ public final class DamageCalculator { - private final Modifiers modifiers; + private final Modifiers modifiers; + private final CombatFormulas formulas; + /** Uses the formulas of {@code combat.yml} (or the legacy preset's when {@link Modifiers#legacyCombat}). */ public DamageCalculator(Modifiers modifiers) { + this(modifiers, CombatCfg.formulas(modifiers.legacyCombat)); + } + + public DamageCalculator(Modifiers modifiers, CombatFormulas formulas) { this.modifiers = modifiers; + this.formulas = formulas; } /** @@ -32,31 +45,29 @@ public Result calculate(double damage, double factionModifier, @Nullable Double defense, double protectionFactor) { - double dmgType = damage; - - dmgType *= modifiers.pveDamage; - dmgType *= modifiers.critical; - dmgType *= entityTypeModifier; - dmgType *= factionModifier; - dmgType *= modifiers.enchantProtection; - if (modifiers.applyAttackPower) dmgType *= modifiers.attackPower; - dmgType *= modifiers.block; - double directType = dmgType * modifiers.direct; // Get direct value for this damage type + // The values are passed in the order CombatExpression lists the variables. Each call builds its own + // argument array, so a calculator keeps no state between calls and may be shared between threads. + double dmgType = formulas.eval(CombatExpression.DAMAGE_SCALING, + damage, + modifiers.pveDamage, + modifiers.critical, + entityTypeModifier, + factionModifier, + modifiers.enchantProtection, + // Attack power is not applied to exempt events; 1 is the neutral value of the product + modifiers.applyAttackPower ? modifiers.attackPower : 1D, + modifiers.block); + double directType = formulas.eval(CombatExpression.DIRECT_DAMAGE, dmgType, modifiers.direct); dmgType = Math.max(0, dmgType - directType); // Deduct this value from damage boolean defenseApplied = false; double defended = 0; if (dmgType > 0 && defense != null) { - double def = Math.max(0, defense * modifiers.pveDefense * modifiers.penetrate); + double def = formulas.eval(CombatExpression.DEFENSE_VALUE, + defense, modifiers.pveDefense, modifiers.penetrate); - double defCalced; - if (modifiers.legacyCombat) { - defCalced = Math.max(0, dmgType * (1 - (def * protectionFactor * 0.01))); - } else { - defCalced = Math.max(0, - dmgType * (1 - Math.max(def / 5, def - 4 * dmgType / Math.max(1, modifiers.toughness + 8)) - * protectionFactor * 0.05)); - } + double defCalced = formulas.eval(CombatExpression.DEFENSE_MITIGATION, + dmgType, def, protectionFactor, modifiers.toughness); defenseApplied = true; defended = dmgType - defCalced; dmgType = defCalced; @@ -79,9 +90,12 @@ public static class Modifiers { double direct; double pveDefense; double penetrate; - /** The victim's armor toughness. Only the current formula uses it. */ + /** The victim's armor toughness. Only the default preset's defense formula uses it. */ double toughness; - /** Selects the old defense formula ({@code EngineCfg.LEGACY_COMBAT}). */ + /** + * Uses the legacy preset's formulas for this hit, whatever {@code combat.yml} selects + * ({@code EngineCfg.LEGACY_COMBAT}, deprecated: false unless something sets it). + */ boolean legacyCombat; } diff --git a/src/main/java/studio/magemonkey/divinity/manager/damage/formula/CombatExpression.java b/src/main/java/studio/magemonkey/divinity/manager/damage/formula/CombatExpression.java new file mode 100644 index 00000000..cb85c29d --- /dev/null +++ b/src/main/java/studio/magemonkey/divinity/manager/damage/formula/CombatExpression.java @@ -0,0 +1,102 @@ +package studio.magemonkey.divinity.manager.damage.formula; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Every formula of the damage calculator that can be changed in {@code combat.yml}, with the variables it is + * given and the default expression of each preset. {@code combat.yml} documents the same variables; keep the two + * in step ({@code CombatFormulasTest} checks the defaults and the variables against the shipped file). + *

+ * The order of the variables is part of the contract with the compiled expression: the calculator passes values + * by position. + */ +public enum CombatExpression { + + /** The damage of one type after every multiplier. */ + DAMAGE_SCALING("damage-scaling", + new String[]{"damage", "pvp_pve_damage", "critical", "entity_type", "faction", "enchant_protection", + "attack_power", "block"}, + new double[]{10D, 1.2D, 1.5D, 0.9D, 1.1D, 0.8D, 1D, 0.7D}, + "damage * pvp_pve_damage * critical * entity_type * faction * enchant_protection * attack_power * block", + null), + + /** The part of the scaled damage that skips the defense. */ + DIRECT_DAMAGE("direct-damage", + new String[]{"damage", "direct"}, + new double[]{10D, 0.2D}, + "damage * direct", + null), + + /** The victim's defense value, before the mitigation formula uses it. */ + DEFENSE_VALUE("defense-value", + new String[]{"defense", "pvp_pve_defense", "penetration"}, + new double[]{30D, 1.1D, 0.9D}, + "max(0, defense * pvp_pve_defense * penetration)", + null), + + /** The damage left after the defense. */ + DEFENSE_MITIGATION("defense-mitigation", + new String[]{"damage", "defense", "protection", "toughness"}, + new double[]{20D, 30D, 0.8D, 4D}, + "max(0, damage * (1 - max(defense / 5, defense - 4 * damage / max(1, toughness + 8)) * protection * 0.05))", + "max(0, damage * (1 - (defense * protection * 0.01)))"); + + private final String key; + private final String[] variables; + private final double[] sample; + private final String defaultExpression; + private final String legacyDefault; + + CombatExpression(@NotNull String key, + @NotNull String[] variables, + @NotNull double[] sample, + @NotNull String defaultExpression, + @Nullable String legacyDefault) { + this.key = key; + this.variables = variables; + this.sample = sample; + this.defaultExpression = defaultExpression; + this.legacyDefault = legacyDefault; + } + + /** The key under {@code expressions:} in {@code combat.yml}. */ + @NotNull + public String key() { + return key; + } + + /** The variable names, in the order the values are passed. */ + @NotNull + public String[] variables() { + return variables.clone(); + } + + /** + * Ordinary values for every variable, used to check a formula at load time. A formula that is NaN or + * infinite for these values is rejected. + */ + @NotNull + double[] sample() { + return sample.clone(); + } + + @NotNull + public String defaultExpression() { + return defaultExpression; + } + + /** The legacy preset's expression, or null when it is the same as the default. */ + @Nullable + public String legacyDefault() { + return legacyDefault; + } + + @Nullable + public static CombatExpression byKey(@NotNull String key) { + for (CombatExpression expression : values()) { + if (expression.key.equals(key)) return expression; + } + return null; + } +} diff --git a/src/main/java/studio/magemonkey/divinity/manager/damage/formula/CombatFormulas.java b/src/main/java/studio/magemonkey/divinity/manager/damage/formula/CombatFormulas.java new file mode 100644 index 00000000..797cae8e --- /dev/null +++ b/src/main/java/studio/magemonkey/divinity/manager/damage/formula/CombatFormulas.java @@ -0,0 +1,173 @@ +package studio.magemonkey.divinity.manager.damage.formula; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import studio.magemonkey.codex.util.eval.CompiledExpression; +import studio.magemonkey.codex.util.eval.Evaluator; + +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.regex.Pattern; +import java.util.function.Consumer; + +/** + * The compiled expressions of one preset plus the overrides from {@code combat.yml}. Immutable once built, and + * safe to use from any thread (Codex's {@code CompiledExpression} is). + *

+ * An expression that cannot be used is replaced by the preset's own when this is built, and a result that is NaN + * or infinite at hit time is replaced by the preset's result for that hit. {@link #eval} never throws. + */ +public final class CombatFormulas { + + /** + * A '^' followed by a unary minus. Codex's parser (Javaluator) can compute such an expression wrongly without + * complaining ('x * 2^-1' gives a wrong number), so it is not accepted until that is fixed in Codex. + */ + private static final Pattern NEGATIVE_EXPONENT = Pattern.compile("\\^\\s*-"); + + private static final Consumer SILENT = message -> { + }; + + private final CombatPreset preset; + private final CompiledExpression[] active; + private final CompiledExpression[] fallback; + private final boolean[] overridden; + private final AtomicBoolean[] warned; + private final Consumer warn; + + private CombatFormulas(@NotNull CombatPreset preset, + @NotNull CompiledExpression[] active, + @NotNull CompiledExpression[] fallback, + @NotNull boolean[] overridden, + @NotNull Consumer warn) { + this.preset = preset; + this.active = active; + this.fallback = fallback; + this.overridden = overridden; + this.warn = warn; + this.warned = new AtomicBoolean[active.length]; + for (int i = 0; i < warned.length; i++) { + warned[i] = new AtomicBoolean(); + } + } + + /** The preset as shipped, with no overrides. */ + @NotNull + public static CombatFormulas of(@NotNull CombatPreset preset) { + return build(preset, null, null); + } + + /** + * Compiles the preset's expressions, then the overrides on top of them. + * + * @param overrides expression key to expression (a string, or a number), or null for none. A value that is + * not usable is reported to {@code warn} once, here, and that expression keeps the + * preset's. + * @param warn receives one message per problem found now, and one per expression that later gives NaN + * or infinity during a hit. Null to stay silent. + */ + @NotNull + public static CombatFormulas build(@NotNull CombatPreset preset, + @Nullable Map overrides, + @Nullable Consumer warn) { + Consumer sink = warn == null ? SILENT : warn; + CombatExpression[] all = CombatExpression.values(); + CompiledExpression[] active = new CompiledExpression[all.length]; + CompiledExpression[] fallback = new CompiledExpression[all.length]; + boolean[] overridden = new boolean[all.length]; + + for (CombatExpression expression : all) { + int i = expression.ordinal(); + String presetText = preset.expressionFor(expression); + try { + fallback[i] = compile(expression, presetText); + } catch (IllegalArgumentException e) { + // The shipped expressions are checked by a test, so this is a programming error + throw new IllegalStateException("The " + preset.key() + " preset's " + expression.key() + + " does not compile: " + e.getMessage(), e); + } + active[i] = fallback[i]; + + Object value = overrides == null ? null : overrides.get(expression.key()); + if (value == null) continue; + + String text = value instanceof Number || value instanceof String ? String.valueOf(value).trim() : null; + try { + if (text == null) throw new IllegalArgumentException("it must be text or a number"); + active[i] = compile(expression, text); + overridden[i] = true; + } catch (IllegalArgumentException e) { + sink.accept("combat.yml: '" + expression.key() + "' is ignored (" + e.getMessage() + + "). Using the " + preset.key() + " preset's: " + presetText); + } + } + return new CombatFormulas(preset, active, fallback, overridden, sink); + } + + /** + * Compiles {@code text} for {@code expression} and checks it against the expression's sample values. + * + * @throws IllegalArgumentException with the reason when it cannot be used + */ + @NotNull + private static CompiledExpression compile(@NotNull CombatExpression expression, @NotNull String text) { + if (text.isEmpty()) { + throw new IllegalArgumentException("the expression is empty"); + } + if (NEGATIVE_EXPONENT.matcher(text).find()) { + throw new IllegalArgumentException( + "a negative exponent has to be bracketed: write 2^(-1), not 2^-1, which can be computed wrongly"); + } + CompiledExpression formula = Evaluator.compile(text, expression.variables()); + double result; + try { + result = formula.eval(expression.sample()); + } catch (RuntimeException e) { + throw new IllegalArgumentException("it fails to evaluate: " + e.getMessage(), e); + } + if (Double.isNaN(result)) { + throw new IllegalArgumentException("it gives NaN for ordinary values"); + } + if (Double.isInfinite(result)) { + throw new IllegalArgumentException("it gives infinity for ordinary values"); + } + return formula; + } + + @NotNull + public CombatPreset preset() { + return preset; + } + + /** Whether {@code expression} is the config's own and not the preset's. */ + public boolean isOverridden(@NotNull CombatExpression expression) { + return overridden[expression.ordinal()]; + } + + /** + * Evaluates one expression. Never throws. If the expression gives NaN or infinity, the preset's expression + * answers instead. + * + * @param values the variables, in the order {@link CombatExpression#variables()} lists them. Passing an + * array that the caller reuses avoids an allocation per call; it is not kept. + */ + public double eval(@NotNull CombatExpression expression, double... values) { + int i = expression.ordinal(); + double result; + try { + result = active[i].eval(values); + } catch (RuntimeException e) { + result = Double.NaN; + } + if (Double.isFinite(result) || !overridden[i]) { + // A preset expression is the reference: its own NaN or infinity is what the hit gets, as it always did + return result; + } + + if (warned[i].compareAndSet(false, true)) { + warn.accept("combat.yml: '" + expression.key() + "' gave " + result + " during a hit. The " + + preset.key() + " preset's expression is used for such hits. (Reported once.)"); + } + return fallback[i].eval(values); + } +} diff --git a/src/main/java/studio/magemonkey/divinity/manager/damage/formula/CombatPreset.java b/src/main/java/studio/magemonkey/divinity/manager/damage/formula/CombatPreset.java new file mode 100644 index 00000000..a3168165 --- /dev/null +++ b/src/main/java/studio/magemonkey/divinity/manager/damage/formula/CombatPreset.java @@ -0,0 +1,43 @@ +package studio.magemonkey.divinity.manager.damage.formula; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * A named set of default expressions. + */ +public enum CombatPreset { + /** The combat of current versions. */ + DEFAULT("default"), + /** As {@link #DEFAULT}, with the old defense formula. What {@code legacy-combat: true} used to select. */ + LEGACY("legacy"); + + private final String key; + + CombatPreset(@NotNull String key) { + this.key = key; + } + + /** The name used in {@code combat.yml}. */ + @NotNull + public String key() { + return key; + } + + /** The preset's expression for {@code expression}. */ + @NotNull + public String expressionFor(@NotNull CombatExpression expression) { + return this == LEGACY && expression.legacyDefault() != null + ? expression.legacyDefault() + : expression.defaultExpression(); + } + + @Nullable + public static CombatPreset byKey(@Nullable String key) { + if (key == null) return null; + for (CombatPreset preset : values()) { + if (preset.key.equalsIgnoreCase(key.trim())) return preset; + } + return null; + } +} diff --git a/src/main/resources/combat.yml b/src/main/resources/combat.yml new file mode 100644 index 00000000..17f613bb --- /dev/null +++ b/src/main/resources/combat.yml @@ -0,0 +1,65 @@ +# Divinity combat formulas. +# +# Every number the damage calculator computes with a formula is an expression in this file. Expressions are +# compiled when the plugin loads and evaluated once per damage type of every hit. Rolls (dodge, block, critical +# chance), event firing and ordering are not formulas and cannot be changed here. +# +# Changing nothing keeps the combat Divinity has always had. This file replaces 'combat.legacy-combat' in +# engine.yml: servers that had it set to true were moved to 'preset: legacy' automatically, and the old key is now +# ignored. +# +# A formula that does not compile, uses a variable that is not listed for it, or gives NaN or infinity when tested +# at load is reported once in the console and that one expression falls back to the chosen preset's own. If a +# formula gives NaN or infinity in the middle of a fight (for example a division by zero on an unusual hit), the +# preset's expression is used for that hit instead. Combat never stops because of a formula in this file. +# +# Syntax: numbers, variables, + - * / % ^, unary minus, brackets, and the functions min, max, abs, sqrt, sum, avg, +# floor, ceil, round, sin, cos, tan, ln, log, plus the constants pi and e. Notes: '^' is left associative +# (2^3^2 is (2^3)^2). A '^' followed by a minus is rejected: write '2^(-1)', not '2^-1', because Codex's parser can +# compute the second form wrongly without complaint. Variable names are written exactly as listed below (lowercase, +# with underscores). + +# Which set of default expressions to start from. +# default - the combat of current versions. +# legacy - as 'default', but with the old defense formula (what 'legacy-combat: true' used to give). +preset: default + +# Override single expressions here. Only the keys you list are changed, everything else follows the preset. +# Each commented line below is the expression the 'default' preset uses. Remove the '#' and edit it to override. +# Where the 'legacy' preset differs, its expression is shown too. +# +# The expressions of one damage type are evaluated in this order for every hit: +# damage-scaling -> direct-damage -> (when a defense applies) defense-value -> defense-mitigation +expressions: + # damage-scaling: the damage of one damage type after every multiplier. + # damage the damage of this type before any modifier + # pvp_pve_damage 1 + the attacker's PvE or PvP damage stat / 100 (PvP when both sides are players) + # critical 1, or the attacker's critical damage when the critical roll succeeded + # entity_type the damage type's modifier for the victim's entity type (1 if none) + # faction the damage type's modifier for the victim's MythicMobs faction (1 if none) + # enchant_protection the victim's enchantment protection factor against this cause of damage + # attack_power the attacker's attack cooldown modifier (always 1 for hits that are exempt from it) + # block 1, or 1 - the victim's block damage stat / 100 when the block roll succeeded + # damage-scaling: "damage * pvp_pve_damage * critical * entity_type * faction * enchant_protection * attack_power * block" + + # direct-damage: the part of the scaled damage that skips the defense. The calculator itself takes it out of the + # damage (never below 0) and adds it back after the defense; that bookkeeping is not configurable. + # damage the result of damage-scaling + # direct the fraction of the damage that is direct (0 today: direct damage is switched off) + # direct-damage: "damage * direct" + + # defense-value: the victim's defense value for the damage type, before it is used by defense-mitigation. + # Only evaluated when the damage type has a defense and there is damage left after the direct part. + # defense the victim's value of the defense attached to this damage type + # pvp_pve_defense 1 + the victim's PvE or PvP defense stat / 100 (PvP when both sides are players) + # penetration 1 - the attacker's penetration stat / 100 + # defense-value: "max(0, defense * pvp_pve_defense * penetration)" + + # defense-mitigation: the damage left after the defense. The calculator reports damage minus this as 'defended'. + # damage the damage after the direct part was taken out + # defense the result of defense-value + # protection the defense's protection factor + # toughness the victim's armor toughness (used by the default formula only) + # defense-mitigation: "max(0, damage * (1 - max(defense / 5, defense - 4 * damage / max(1, toughness + 8)) * protection * 0.05))" + # legacy preset: + # defense-mitigation: "max(0, damage * (1 - (defense * protection * 0.01)))" diff --git a/src/main/resources/engine.yml b/src/main/resources/engine.yml index 85a2eca0..48f98742 100644 --- a/src/main/resources/engine.yml +++ b/src/main/resources/engine.yml @@ -75,8 +75,7 @@ attributes: hide-flags: true combat: - # Whether to use the old combat formula for calculating defenses - legacy-combat: false + # The combat formulas, including the old defense formula that 'legacy-combat' used to switch on, are in combat.yml. # Shield settings. shield: block: diff --git a/src/test/java/studio/magemonkey/divinity/DependencyRequirementTest.java b/src/test/java/studio/magemonkey/divinity/DependencyRequirementTest.java index 0cb4b212..e13a7e2d 100644 --- a/src/test/java/studio/magemonkey/divinity/DependencyRequirementTest.java +++ b/src/test/java/studio/magemonkey/divinity/DependencyRequirementTest.java @@ -67,9 +67,9 @@ void legacyAndUnusualVersions() { } @Test - void minimumCodexVersion_isTheFirstBuildWithDamageRequests() { + void minimumCodexVersion_isTheFirstBuildWithCompiledExpressions() { String min = DependencyRequirement.MIN_CORE_VERSION; - assertTrue(meetsVersion(min, "1.3.0-dev.1")); + assertFalse(meetsVersion(min, "1.3.0-dev.1"), "Has damage requests but no Evaluator.compile"); assertTrue(meetsVersion(min, "1.3.0-dev.2")); assertTrue(meetsVersion(min, "1.3.0")); assertTrue(meetsVersion(min, "1.3.1-dev.1")); diff --git a/src/test/java/studio/magemonkey/divinity/config/CombatCfgTest.java b/src/test/java/studio/magemonkey/divinity/config/CombatCfgTest.java new file mode 100644 index 00000000..ae1ff13f --- /dev/null +++ b/src/test/java/studio/magemonkey/divinity/config/CombatCfgTest.java @@ -0,0 +1,281 @@ +package studio.magemonkey.divinity.config; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import studio.magemonkey.divinity.manager.damage.DamageCalculator; +import studio.magemonkey.divinity.manager.damage.DamageCalculator.Modifiers; +import studio.magemonkey.divinity.manager.damage.formula.CombatExpression; +import studio.magemonkey.divinity.manager.damage.formula.CombatPreset; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class CombatCfgTest { + + private static final double DELTA = 1e-9; + + @TempDir + File folder; + + private final List info = new ArrayList<>(); + private final List warn = new ArrayList<>(); + + @AfterEach + void reset() { + CombatCfg.resetToDefaults(); + } + + private void load(Boolean oldKey) { + CombatCfg.load(folder, oldKey, info::add, warn::add); + } + + private File file() { + return new File(folder, CombatCfg.FILE_NAME); + } + + private String read() throws IOException { + return new String(Files.readAllBytes(file().toPath()), StandardCharsets.UTF_8); + } + + private void write(String text) throws IOException { + Files.write(file().toPath(), text.getBytes(StandardCharsets.UTF_8)); + } + + /** 20 damage against 30 defense at protection factor 0.8, toughness 0, nothing else. Default 4, legacy 15.2. */ + private static double hit() { + Modifiers m = new Modifiers(1, 1, 1, true, 1, 1, 0, 1, 1, 0, false); + return new DamageCalculator(m).calculate(20, 1, 1, 30D, 0.8).getDamage(); + } + + // ------------------------------------------------------------------ // + // Before anything is loaded + // ------------------------------------------------------------------ // + + @Test + void beforeLoading_theDefaultPresetIsInForce() { + assertEquals(CombatPreset.DEFAULT, CombatCfg.preset()); + assertEquals(4D, hit(), DELTA); + } + + // ------------------------------------------------------------------ // + // Migration + // ------------------------------------------------------------------ // + + @Test + void migration_oldKeyTrue_writesTheLegacyPreset() throws IOException { + load(true); + + assertTrue(read().contains("\npreset: legacy\n")); + assertEquals(CombatPreset.LEGACY, CombatCfg.preset()); + assertEquals(15.2D, hit(), DELTA); + assertEquals(1, info.size(), info.toString()); + assertTrue(info.get(0).contains("legacy-combat: true") && info.get(0).contains("legacy"), info.get(0)); + assertTrue(warn.isEmpty(), warn.toString()); + } + + @Test + void migration_oldKeyFalse_writesTheDefaultPreset() throws IOException { + load(false); + + assertTrue(read().contains("\npreset: default\n")); + assertEquals(CombatPreset.DEFAULT, CombatCfg.preset()); + assertEquals(4D, hit(), DELTA); + assertEquals(1, info.size(), info.toString()); + assertTrue(info.get(0).contains("legacy-combat: false"), info.get(0)); + } + + @Test + void migration_noOldKey_writesTheDefaultFileWithoutAMessage() throws IOException { + load(null); + + assertTrue(file().isFile()); + assertEquals(CombatPreset.DEFAULT, CombatCfg.preset()); + assertTrue(info.isEmpty(), info.toString()); + assertTrue(warn.isEmpty(), warn.toString()); + } + + @Test + void migration_writtenFileIsTheShippedOneApartFromThePresetLine() throws IOException { + load(false); + String defaults = read(); + file().delete(); + load(true); + assertEquals(defaults.replace("\npreset: default\n", "\npreset: legacy\n"), read()); + } + + @Test + void migration_neverOverwritesAnExistingFile() throws IOException { + String mine = "preset: default\nexpressions:\n defense-value: \"defense * 0.5\"\n# my own notes\n"; + write(mine); + + load(true); // the old key says legacy, the file says default: the file wins + + assertEquals(mine, read()); + assertEquals(CombatPreset.DEFAULT, CombatCfg.preset()); + assertTrue(info.isEmpty(), "nothing was migrated, so nothing is reported: " + info); + // and its override is in force: 1 - max(3, 15 - 4 * 20 / 8 = 5) * 0.8 * 0.05 = 0.84 + assertEquals(20 * (1 - 5 * 0.8 * 0.05), hit(), DELTA); + } + + @Test + void migration_isIdempotent() throws IOException { + load(true); + String first = read(); + + load(true); + load(false); // even if the old key changed in engine.yml afterwards + + assertEquals(first, read()); + assertEquals(CombatPreset.LEGACY, CombatCfg.preset()); + assertEquals(1, info.size(), "reported once, on the run that migrated: " + info); + } + + @Test + void oldKeyIsIgnoredOnceTheFileExists() throws IOException { + load(true); + write(read().replace("\npreset: legacy\n", "\npreset: default\n")); // the admin switches presets by hand + + load(true); // engine.yml still says legacy-combat: true + + assertEquals(CombatPreset.DEFAULT, CombatCfg.preset()); + assertEquals(4D, hit(), DELTA); + } + + @Test + void migration_cannotWriteTheFile_stillHonoursTheOldKeyForThisRun() throws IOException { + File notAFolder = new File(folder, "plain-file"); + assertTrue(notAFolder.createNewFile()); + + CombatCfg.load(new File(notAFolder, "inside"), true, info::add, warn::add); + + assertEquals(CombatPreset.LEGACY, CombatCfg.preset()); + assertEquals(1, warn.size(), warn.toString()); + assertTrue(warn.get(0).contains("could not be written"), warn.get(0)); + } + + // ------------------------------------------------------------------ // + // Reload + // ------------------------------------------------------------------ // + + @Test + void reload_picksUpChangesToThePresetAndToExpressions() throws IOException { + load(false); + assertEquals(4D, hit(), DELTA); + + write("preset: legacy\n"); + load(false); + assertEquals(15.2D, hit(), DELTA); + + write("preset: legacy\nexpressions:\n defense-mitigation: \"damage - 1\"\n"); + load(false); + assertEquals(19D, hit(), DELTA); + + write("preset: default\n"); + load(false); + assertEquals(4D, hit(), DELTA); + } + + @Test + void reload_ofABrokenFile_neverLeavesCombatWithoutFormulas() throws IOException { + load(true); + write("preset: [unclosed\n - : :\n"); + + load(true); + + assertEquals(CombatPreset.DEFAULT, CombatCfg.preset()); + assertEquals(4D, hit(), DELTA); + assertEquals(1, warn.size(), warn.toString()); + assertTrue(warn.get(0).contains("could not be read"), warn.get(0)); + assertTrue(read().contains("[unclosed"), "the broken file is left for the admin to fix"); + } + + // ------------------------------------------------------------------ // + // Problems in the file + // ------------------------------------------------------------------ // + + @Test + void brokenFormula_isReportedOnceAndOnlyThatOneFallsBack() throws IOException { + write("preset: legacy\nexpressions:\n" + + " defense-value: \"defense *\"\n" + + " direct-damage: \"damage * 0.5\"\n"); + + load(null); + + assertEquals(1, warn.size(), warn.toString()); + assertTrue(warn.get(0).contains("'defense-value'") && warn.get(0).contains("legacy"), warn.get(0)); + // legacy mitigation with the preset's defense value: 1 - 30 * 0.8 * 0.01, and half the damage is direct + Modifiers m = new Modifiers(1, 1, 1, true, 1, 1, 0, 1, 1, 0, false); + assertEquals(10 * 0.76 + 10, new DamageCalculator(m).calculate(20, 1, 1, 30D, 0.8).getDamage(), DELTA); + } + + @Test + void unknownPreset_isReportedAndTheDefaultIsUsed() throws IOException { + write("preset: legcay\n"); + load(null); + + assertEquals(CombatPreset.DEFAULT, CombatCfg.preset()); + assertEquals(1, warn.size()); + assertTrue(warn.get(0).contains("legcay"), warn.get(0)); + } + + @Test + void unknownExpressionKey_isReportedAndIgnored() throws IOException { + write("expressions:\n defence-value: \"defense * 0.5\"\n"); + load(null); + + assertEquals(1, warn.size()); + assertTrue(warn.get(0).contains("defence-value"), warn.get(0)); + assertEquals(4D, hit(), DELTA); + } + + @Test + void emptyFile_meansTheDefaultPresetWithoutComplaint() throws IOException { + write(""); + load(null); + + assertEquals(CombatPreset.DEFAULT, CombatCfg.preset()); + assertTrue(warn.isEmpty(), warn.toString()); + } + + @Test + void shippedFile_loadsCleanlyAndChangesNothing() { + load(null); + + assertTrue(warn.isEmpty(), warn.toString()); + for (CombatExpression expression : CombatExpression.values()) { + assertFalse(CombatCfg.formulas(false).isOverridden(expression), expression.key()); + } + } + + // ------------------------------------------------------------------ // + // The deprecated switch + // ------------------------------------------------------------------ // + + @Test + @SuppressWarnings("deprecation") + void forcingLegacy_usesTheLegacyPresetWhateverTheFileSays() throws IOException { + load(false); + Modifiers legacy = new Modifiers(1, 1, 1, true, 1, 1, 0, 1, 1, 0, true); + + assertEquals(15.2D, new DamageCalculator(legacy).calculate(20, 1, 1, 30D, 0.8).getDamage(), DELTA); + assertEquals(4D, hit(), DELTA); + assertFalse(EngineCfg.LEGACY_COMBAT, "nothing sets the deprecated switch"); + } + + @Test + void forcingLegacy_keepsOverridesFromTheFile() throws IOException { + write("expressions:\n defense-value: \"defense * 0.5\"\n"); + load(null); + Modifiers legacy = new Modifiers(1, 1, 1, true, 1, 1, 0, 1, 1, 0, true); + + // legacy: 1 - 15 * 0.8 * 0.01 = 0.88 + assertEquals(20 * 0.88, new DamageCalculator(legacy).calculate(20, 1, 1, 30D, 0.8).getDamage(), DELTA); + } +} diff --git a/src/test/java/studio/magemonkey/divinity/config/CombatReloadTest.java b/src/test/java/studio/magemonkey/divinity/config/CombatReloadTest.java new file mode 100644 index 00000000..eb3eb7d4 --- /dev/null +++ b/src/test/java/studio/magemonkey/divinity/config/CombatReloadTest.java @@ -0,0 +1,106 @@ +package studio.magemonkey.divinity.config; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import studio.magemonkey.divinity.manager.damage.formula.CombatExpression; +import studio.magemonkey.divinity.manager.damage.formula.CombatPreset; +import studio.magemonkey.divinity.testutil.MockedTest; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Goes through the plugin's real reload ({@code Divinity#reload}, which is what a config reload runs), not through + * {@link CombatCfg#load} directly. The reload reads {@code engine.yml} first and {@code combat.yml} after it, which + * the migration test depends on. + */ +class CombatReloadTest extends MockedTest { + + private File combatFile; + private File engineFile; + private String originalEngine; + + @BeforeAll + void findFiles() throws IOException { + combatFile = new File(plugin.getDataFolder(), CombatCfg.FILE_NAME); + engineFile = new File(plugin.getDataFolder(), "engine.yml"); + assertTrue(engineFile.isFile(), "engine.yml is written when the plugin starts"); + originalEngine = read(engineFile); + } + + @AfterEach + void restore() throws IOException { + write(engineFile, originalEngine); + Files.deleteIfExists(combatFile.toPath()); + plugin.reload(); + } + + @AfterAll + void leaveDefaults() { + CombatCfg.resetToDefaults(); + } + + private static String read(File file) throws IOException { + return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); + } + + private static void write(File file, String text) throws IOException { + Files.write(file.toPath(), text.getBytes(StandardCharsets.UTF_8)); + } + + @Test + void startingThePlugin_wroteTheShippedFile() throws IOException { + // The plugin was loaded by MockedTest; with no old key in engine.yml that is the default preset + assertTrue(combatFile.isFile()); + assertTrue(read(combatFile).contains("\npreset: default\n")); + assertEquals(CombatPreset.DEFAULT, CombatCfg.preset()); + } + + @Test + void reload_picksUpEditsToCombatYml() throws IOException { + write(combatFile, "preset: legacy\n"); + plugin.reload(); + assertEquals(CombatPreset.LEGACY, CombatCfg.preset()); + assertFalse(CombatCfg.formulas(false).isOverridden(CombatExpression.DEFENSE_VALUE)); + + write(combatFile, "preset: default\nexpressions:\n defense-value: \"defense * 0.5\"\n"); + plugin.reload(); + assertEquals(CombatPreset.DEFAULT, CombatCfg.preset()); + assertTrue(CombatCfg.formulas(false).isOverridden(CombatExpression.DEFENSE_VALUE)); + // 1 - max(3, 15 - 4 * 20 / 8 = 5) * 0.8 * 0.05 = 0.84 of 20 + assertEquals(20 * (1 - 5 * 0.8 * 0.05), CombatCfg.formulas(false) + .eval(CombatExpression.DEFENSE_MITIGATION, 20D, CombatCfg.formulas(false) + .eval(CombatExpression.DEFENSE_VALUE, 30D, 1D, 1D), 0.8D, 0D), 1e-9); + } + + @Test + void reload_readsTheOldKeyFromEngineYmlBeforeMigrating() throws IOException { + // An old server: legacy-combat is on in engine.yml and there is no combat.yml yet + assertTrue(originalEngine.contains("\ncombat:\n"), "engine.yml has a combat section"); + write(engineFile, originalEngine.replace("\ncombat:\n", "\ncombat:\n legacy-combat: true\n")); + Files.delete(combatFile.toPath()); + + plugin.reload(); + + assertTrue(read(combatFile).contains("\npreset: legacy\n"), "migrated from the key just read"); + assertEquals(CombatPreset.LEGACY, CombatCfg.preset()); + } + + @Test + void reload_ofAnExistingFile_ignoresTheOldKeyAndKeepsTheFile() throws IOException { + String mine = "preset: default\n# kept\n"; + write(combatFile, mine); + write(engineFile, originalEngine.replace("\ncombat:\n", "\ncombat:\n legacy-combat: true\n")); + + plugin.reload(); + + assertEquals(mine, read(combatFile)); + assertEquals(CombatPreset.DEFAULT, CombatCfg.preset()); + } +} diff --git a/src/test/java/studio/magemonkey/divinity/manager/damage/DamageCalculatorBenchmark.java b/src/test/java/studio/magemonkey/divinity/manager/damage/DamageCalculatorBenchmark.java new file mode 100644 index 00000000..95571de5 --- /dev/null +++ b/src/test/java/studio/magemonkey/divinity/manager/damage/DamageCalculatorBenchmark.java @@ -0,0 +1,95 @@ +package studio.magemonkey.divinity.manager.damage; + +import studio.magemonkey.divinity.manager.damage.DamageCalculator.Modifiers; +import studio.magemonkey.divinity.manager.damage.formula.CombatFormulas; +import studio.magemonkey.divinity.manager.damage.formula.CombatPreset; + +import java.util.Arrays; +import java.util.Random; + +/** + * Scratch benchmark, not a test (no test runner picks it up). Run it from the test classpath: + *

java -cp target/test-classes:target/classes:$(cat classpath.txt) \
+ *     studio.magemonkey.divinity.manager.damage.DamageCalculatorBenchmark
+ * One "hit" is what {@code DamageManager} does for a hit with three damage types, one of them undefended: build a + * calculator, then calculate each type. The same pre-generated inputs go through the Java formulas that were + * replaced ({@link ReferenceDamageCalculator}) and through the one that reads {@code combat.yml}. + */ +public final class DamageCalculatorBenchmark { + + private static final int HITS = 4096; + + private static final Modifiers[] MODS = new Modifiers[HITS]; + private static final double[][] DAMAGE = new double[HITS][3]; + private static final double[] DEFENSE = new double[HITS]; + private static final double[] PROTECT = new double[HITS]; + + static { + Random random = new Random(371); + for (int i = 0; i < HITS; i++) { + MODS[i] = new Modifiers(0.8 + random.nextDouble() * 0.5, random.nextBoolean() ? 1 : 1.5, 0.9, true, + 0.5 + random.nextDouble() / 2, 1, 0, 1, 0.9, random.nextInt(10), false); + for (int t = 0; t < 3; t++) DAMAGE[i][t] = 5 + random.nextDouble() * 60; + DEFENSE[i] = random.nextDouble() * 80; + PROTECT[i] = 0.5 + random.nextDouble(); + } + } + + private static double sink; + + private static double reference(int i) { + ReferenceDamageCalculator calc = new ReferenceDamageCalculator(MODS[i]); + double sum = 0; + sum += calc.calculate(DAMAGE[i][0], 1, 1, DEFENSE[i], PROTECT[i]).getDamage(); + sum += calc.calculate(DAMAGE[i][1], 1, 1, DEFENSE[i] / 2, PROTECT[i]).getDamage(); + sum += calc.calculate(DAMAGE[i][2], 1, 1, null, 0).getDamage(); + return sum; + } + + private static double configured(int i, CombatFormulas formulas) { + DamageCalculator calc = new DamageCalculator(MODS[i], formulas); + double sum = 0; + sum += calc.calculate(DAMAGE[i][0], 1, 1, DEFENSE[i], PROTECT[i]).getDamage(); + sum += calc.calculate(DAMAGE[i][1], 1, 1, DEFENSE[i] / 2, PROTECT[i]).getDamage(); + sum += calc.calculate(DAMAGE[i][2], 1, 1, null, 0).getDamage(); + return sum; + } + + private interface Run { + double hit(int i); + } + + /** Hits per second, as the median of several timed rounds after a warm-up. */ + private static double measure(Run run, int hitsPerRound) { + for (int i = 0; i < hitsPerRound; i++) sink += run.hit(i % HITS); + double[] rates = new double[7]; + for (int round = 0; round < rates.length; round++) { + long start = System.nanoTime(); + for (int i = 0; i < hitsPerRound; i++) sink += run.hit(i % HITS); + rates[round] = hitsPerRound / ((System.nanoTime() - start) / 1e9); + } + Arrays.sort(rates); + return rates[rates.length / 2]; + } + + public static void main(String[] args) { + CombatFormulas formulas = CombatFormulas.of(CombatPreset.DEFAULT); + + // Same inputs, same answers, before timing anything + for (int i = 0; i < HITS; i++) { + if (Double.doubleToLongBits(reference(i)) != Double.doubleToLongBits(configured(i, formulas))) { + throw new IllegalStateException("results differ at hit " + i); + } + } + + int rounds = args.length > 0 ? Integer.parseInt(args[0]) : 200_000; + double before = measure(DamageCalculatorBenchmark::reference, rounds); + double after = measure(i -> configured(i, formulas), rounds); + + System.out.printf("before (Java formulas): %,14.0f hits/s%n", before); + System.out.printf("after (combat.yml formulas): %,14.0f hits/s%n", after); + System.out.printf("after is %.1fx %s%n", before > after ? before / after : after / before, + before > after ? "slower" : "faster"); + if (sink == 42) System.out.println(); + } +} diff --git a/src/test/java/studio/magemonkey/divinity/manager/damage/ReferenceDamageCalculator.java b/src/test/java/studio/magemonkey/divinity/manager/damage/ReferenceDamageCalculator.java new file mode 100644 index 00000000..e6573504 --- /dev/null +++ b/src/test/java/studio/magemonkey/divinity/manager/damage/ReferenceDamageCalculator.java @@ -0,0 +1,57 @@ +package studio.magemonkey.divinity.manager.damage; + +import org.jetbrains.annotations.Nullable; +import studio.magemonkey.divinity.manager.damage.DamageCalculator.Modifiers; +import studio.magemonkey.divinity.manager.damage.DamageCalculator.Result; + +/** + * The damage formula exactly as {@link DamageCalculator} had it in Java before the formulas moved to + * {@code combat.yml}: the arithmetic is copied unchanged from that version. It is the oracle for the equivalence + * tests and the "before" of the benchmark. Do not edit the arithmetic; if the real formulas change on purpose, + * this class stays and the tests that compare against it change with a stated reason. + */ +public final class ReferenceDamageCalculator { + + private final Modifiers modifiers; + + public ReferenceDamageCalculator(Modifiers modifiers) { + this.modifiers = modifiers; + } + + public Result calculate(double damage, + double entityTypeModifier, + double factionModifier, + @Nullable Double defense, + double protectionFactor) { + double dmgType = damage; + + dmgType *= modifiers.getPveDamage(); + dmgType *= modifiers.getCritical(); + dmgType *= entityTypeModifier; + dmgType *= factionModifier; + dmgType *= modifiers.getEnchantProtection(); + if (modifiers.isApplyAttackPower()) dmgType *= modifiers.getAttackPower(); + dmgType *= modifiers.getBlock(); + double directType = dmgType * modifiers.getDirect(); // Get direct value for this damage type + dmgType = Math.max(0, dmgType - directType); // Deduct this value from damage + + boolean defenseApplied = false; + double defended = 0; + if (dmgType > 0 && defense != null) { + double def = Math.max(0, defense * modifiers.getPveDefense() * modifiers.getPenetrate()); + + double defCalced; + if (modifiers.isLegacyCombat()) { + defCalced = Math.max(0, dmgType * (1 - (def * protectionFactor * 0.01))); + } else { + defCalced = Math.max(0, + dmgType * (1 - Math.max(def / 5, def - 4 * dmgType / Math.max(1, modifiers.getToughness() + 8)) + * protectionFactor * 0.05)); + } + defenseApplied = true; + defended = dmgType - defCalced; + dmgType = defCalced; + } + return new Result(dmgType + directType, defenseApplied, defended); + } +} diff --git a/src/test/java/studio/magemonkey/divinity/manager/damage/formula/CombatFormulasTest.java b/src/test/java/studio/magemonkey/divinity/manager/damage/formula/CombatFormulasTest.java new file mode 100644 index 00000000..e21a6568 --- /dev/null +++ b/src/test/java/studio/magemonkey/divinity/manager/damage/formula/CombatFormulasTest.java @@ -0,0 +1,383 @@ +package studio.magemonkey.divinity.manager.damage.formula; + +import org.junit.jupiter.api.Test; +import studio.magemonkey.divinity.manager.damage.DamageCalculator; +import studio.magemonkey.divinity.manager.damage.DamageCalculator.Modifiers; +import studio.magemonkey.divinity.manager.damage.DamageCalculator.Result; +import studio.magemonkey.divinity.manager.damage.ReferenceDamageCalculator; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.*; + +class CombatFormulasTest { + + private static final double DELTA = 1e-9; + + /** A hit with a defense: 20 damage, 30 defense, protection factor 0.8, toughness 0, everything else neutral. */ + private static Modifiers neutral(boolean legacy) { + return new Modifiers(1, 1, 1, true, 1, 1, 0, 1, 1, 0, legacy); + } + + private static Result hit(CombatFormulas formulas, Modifiers m) { + return new DamageCalculator(m, formulas).calculate(20, 1, 1, 30D, 0.8); + } + + // ------------------------------------------------------------------ // + // The shipped file and the code agree + // ------------------------------------------------------------------ // + + @Test + void shippedFile_documentsEveryExpressionItsVariablesAndItsDefault() throws IOException { + String file; + try (InputStream in = getClass().getResourceAsStream("/combat.yml")) { + assertNotNull(in, "combat.yml is not on the classpath"); + file = new String(in.readAllBytes(), StandardCharsets.UTF_8); + } + + for (CombatExpression expression : CombatExpression.values()) { + String key = expression.key(); + assertTrue(file.contains("# " + key + ": \"" + expression.defaultExpression() + "\""), + key + ": the default expression in combat.yml differs from the code"); + if (expression.legacyDefault() != null) { + assertTrue(file.contains("# " + key + ": \"" + expression.legacyDefault() + "\""), + key + ": the legacy expression in combat.yml differs from the code"); + } + for (String variable : expression.variables()) { + assertTrue(file.matches("(?s).*# " + key + ":.*# " + variable + " .*"), + key + ": variable '" + variable + "' is not documented in combat.yml"); + } + } + assertTrue(file.contains("\npreset: default\n")); + } + + @Test + void everyPresetExpressionCompilesAndIsFiniteForItsSample() { + for (CombatPreset preset : CombatPreset.values()) { + List warnings = new ArrayList<>(); + CombatFormulas formulas = CombatFormulas.build(preset, null, warnings::add); + assertTrue(warnings.isEmpty(), preset + ": " + warnings); + for (CombatExpression expression : CombatExpression.values()) { + assertFalse(formulas.isOverridden(expression)); + assertTrue(Double.isFinite(formulas.eval(expression, expression.sample())), + preset + "/" + expression); + } + } + } + + @Test + void legacyPresetDiffersFromDefaultOnlyInTheMitigation() { + for (CombatExpression expression : CombatExpression.values()) { + boolean differs = !CombatPreset.DEFAULT.expressionFor(expression) + .equals(CombatPreset.LEGACY.expressionFor(expression)); + assertEquals(expression == CombatExpression.DEFENSE_MITIGATION, differs, expression.key()); + } + } + + // ------------------------------------------------------------------ // + // The numbers did not change + // ------------------------------------------------------------------ // + + @Test + void presets_giveTheSameBitsAsTheJavaFormulasTheyReplaced() { + Random random = new Random(371); + for (CombatPreset preset : CombatPreset.values()) { + CombatFormulas formulas = CombatFormulas.of(preset); + for (int i = 0; i < 20_000; i++) { + Modifiers m = new Modifiers( + 0.5 + random.nextDouble(), 1 + random.nextInt(3) * random.nextDouble(), + random.nextDouble(), random.nextBoolean(), 0.2 + random.nextDouble(), + random.nextBoolean() ? 1 : random.nextDouble(), + random.nextInt(4) == 0 ? random.nextDouble() * 0.5 : 0, + 0.5 + random.nextDouble(), random.nextDouble(), random.nextInt(21), + preset == CombatPreset.LEGACY); + double damage = random.nextInt(10) == 0 ? 0 : random.nextDouble() * 300; + double entity = random.nextBoolean() ? 1 : 0.5 + random.nextDouble(); + double faction = random.nextBoolean() ? 1 : 0.5 + random.nextDouble(); + Double defense = random.nextInt(4) == 0 ? null : random.nextDouble() * 200 - 20; + double protect = random.nextDouble() * 3; + + Result expected = new ReferenceDamageCalculator(m).calculate(damage, entity, faction, defense, protect); + Result actual = new DamageCalculator(m, formulas).calculate(damage, entity, faction, defense, protect); + + assertEquals(Double.doubleToLongBits(expected.getDamage()), Double.doubleToLongBits(actual.getDamage()), + preset + " damage, hit " + i + ": " + expected + " vs " + actual); + assertEquals(Double.doubleToLongBits(expected.getDefended()), + Double.doubleToLongBits(actual.getDefended()), preset + " defended, hit " + i); + assertEquals(expected.isDefenseApplied(), actual.isDefenseApplied(), preset + " applied, hit " + i); + } + } + } + + @Test + void oneCalculatorForSeveralDamageTypes_doesNotLeakArgumentsBetweenCalls() { + // A call must not see anything the one before it left behind + Random random = new Random(4_1); + for (CombatPreset preset : CombatPreset.values()) { + Modifiers m = new Modifiers(1.1, 1.5, 0.9, true, 0.8, 0.7, 0.1, 1.2, 0.9, 6, preset == CombatPreset.LEGACY); + DamageCalculator shared = new DamageCalculator(m, CombatFormulas.of(preset)); + ReferenceDamageCalculator reference = new ReferenceDamageCalculator(m); + for (int i = 0; i < 5_000; i++) { + double damage = random.nextDouble() * 100; + Double defense = random.nextBoolean() ? null : random.nextDouble() * 100; + double protect = random.nextDouble() * 2; + double entity = 0.5 + random.nextDouble(); + double faction = 0.5 + random.nextDouble(); + Result expected = reference.calculate(damage, entity, faction, defense, protect); + Result actual = shared.calculate(damage, entity, faction, defense, protect); + assertEquals(expected, actual, preset + ", call " + i); + } + } + } + + @Test + void oneCalculatorSharedBetweenThreads_givesEveryThreadItsOwnResults() throws Exception { + // A calculator keeps no state between calls, so threads using the same one must not disturb each other + Modifiers m = new Modifiers(1.1, 1.5, 0.9, true, 0.8, 0.7, 0.1, 1.2, 0.9, 6, false); + for (CombatPreset preset : CombatPreset.values()) { + DamageCalculator shared = new DamageCalculator(m, CombatFormulas.of(preset)); + ReferenceDamageCalculator reference = new ReferenceDamageCalculator( + new Modifiers(1.1, 1.5, 0.9, true, 0.8, 0.7, 0.1, 1.2, 0.9, 6, preset == CombatPreset.LEGACY)); + int threads = 8; + java.util.concurrent.atomic.AtomicInteger wrong = new java.util.concurrent.atomic.AtomicInteger(); + java.util.concurrent.CountDownLatch start = new java.util.concurrent.CountDownLatch(1); + List workers = new ArrayList<>(); + for (int t = 0; t < threads; t++) { + final int seed = t; + Thread worker = new Thread(() -> { + Random random = new Random(seed); + try { + start.await(); + } catch (InterruptedException e) { + return; + } + for (int i = 0; i < 20_000; i++) { + double damage = 1 + random.nextDouble() * 200; + double entity = 0.5 + random.nextDouble(); + double faction = 0.5 + random.nextDouble(); + Double defense = random.nextInt(4) == 0 ? null : random.nextDouble() * 100; + double protect = random.nextDouble() * 2; + Result expected = reference.calculate(damage, entity, faction, defense, protect); + Result actual = shared.calculate(damage, entity, faction, defense, protect); + if (!expected.equals(actual)) wrong.incrementAndGet(); + } + }); + workers.add(worker); + worker.start(); + } + start.countDown(); + for (Thread worker : workers) worker.join(); + assertEquals(0, wrong.get(), preset + ": calls from other threads changed results"); + } + } + + // ------------------------------------------------------------------ // + // Each expression, overridden, changes the result as expected + // ------------------------------------------------------------------ // + + private static CombatFormulas with(String key, String expression) { + List warnings = new ArrayList<>(); + CombatFormulas formulas = CombatFormulas.build(CombatPreset.DEFAULT, Map.of(key, expression), warnings::add); + assertTrue(warnings.isEmpty(), warnings.toString()); + return formulas; + } + + @Test + void override_damageScaling() { + // Pretend a critical hit is twice as strong again + CombatFormulas formulas = with("damage-scaling", "damage * critical * critical"); + Modifiers m = new Modifiers(1, 3, 1, true, 1, 1, 0, 1, 1, 0, false); + Result r = new DamageCalculator(m, formulas).calculate(10, 1, 1, null, 0); + assertEquals(90D, r.getDamage(), DELTA); // 10 * 3 * 3, the default would give 30 + assertTrue(formulas.isOverridden(CombatExpression.DAMAGE_SCALING)); + } + + @Test + void override_directDamage() { + // A fifth of the scaled damage skips the defense, whatever the direct modifier says + CombatFormulas formulas = with("direct-damage", "damage * 0.2"); + Result r = new DamageCalculator(neutral(false), formulas).calculate(100, 1, 1, null, 0); + assertEquals(100D, r.getDamage(), DELTA); // 80 + 20 direct, no defense + Result defended = hit(formulas, neutral(false)); + // 20 damage: 4 direct. 16 left, defense 30: 1 - max(6, 30 - 4 * 16 / 8 = 22) * 0.8 * 0.05 = 0.12 + assertEquals(16 * 0.12 + 4, defended.getDamage(), DELTA); + assertEquals(16 * 0.88, defended.getDefended(), DELTA); + } + + @Test + void override_defenseValue() { + // Halve every defense. The default gives 30 + CombatFormulas formulas = with("defense-value", "defense * 0.5"); + Result r = hit(formulas, neutral(true)); + // legacy-style check on the default preset: 1 - max(3, 15 - 4 * 20 / 8 = 5) * 0.8 * 0.05 = 0.8 + assertEquals(20 * (1 - 5 * 0.8 * 0.05), r.getDamage(), DELTA); + } + + @Test + void override_defenseMitigation() { + // No defense formula at all: the defense value is a flat amount taken off + CombatFormulas formulas = with("defense-mitigation", "max(0, damage - defense / 10)"); + Result r = hit(formulas, neutral(false)); + assertEquals(17D, r.getDamage(), DELTA); + assertEquals(3D, r.getDefended(), DELTA); + } + + @Test + void override_numberIsAccepted() { + // A plain number is a valid expression: no direct damage at all, written as 0 + CombatFormulas formulas = CombatFormulas.build(CombatPreset.DEFAULT, Map.of("direct-damage", 0), null); + assertTrue(formulas.isOverridden(CombatExpression.DIRECT_DAMAGE)); + assertEquals(0D, formulas.eval(CombatExpression.DIRECT_DAMAGE, 10D, 0.5D), DELTA); + } + + @Test + void override_appliesToTheLegacyPresetToo() { + List warnings = new ArrayList<>(); + CombatFormulas formulas = CombatFormulas.build(CombatPreset.LEGACY, + Map.of("defense-value", "defense * 0.5"), warnings::add); + // legacy: 1 - 15 * 0.8 * 0.01 = 0.88 + assertEquals(20 * 0.88, hit(formulas, neutral(true)).getDamage(), DELTA); + } + + // ------------------------------------------------------------------ // + // A broken formula is reported once and the preset's takes over + // ------------------------------------------------------------------ // + + private static final String DEFAULT_DEFENSE_VALUE = CombatPreset.DEFAULT.expressionFor(CombatExpression.DEFENSE_VALUE); + + private void assertFallsBack(String key, Object broken, String reasonPart) { + List warnings = new ArrayList<>(); + CombatFormulas formulas = CombatFormulas.build(CombatPreset.DEFAULT, Map.of(key, broken), warnings::add); + + assertEquals(1, warnings.size(), warnings.toString()); + assertTrue(warnings.get(0).contains("'" + key + "'"), "names the key: " + warnings.get(0)); + assertTrue(warnings.get(0).contains(reasonPart), "gives the reason '" + reasonPart + "': " + warnings.get(0)); + CombatExpression expression = CombatExpression.byKey(key); + assertFalse(formulas.isOverridden(expression)); + assertEquals(CombatFormulas.of(CombatPreset.DEFAULT).eval(expression, expression.sample()), + formulas.eval(expression, expression.sample()), 0D); + } + + @Test + void brokenFormula_syntaxError() { + assertFallsBack("defense-value", "max(defense, ", "mismatched"); + } + + @Test + void brokenFormula_unknownVariable() { + assertFallsBack("defense-value", "defense * armour", "armour"); + } + + @Test + void brokenFormula_unknownFunction() { + assertFallsBack("defense-value", "cbrt(defense)", "cbrt"); + } + + @Test + void brokenFormula_negativeExponentWithoutBrackets_isRejected() { + // Codex 1.3.0-dev.2 computes 'x * 2^-1' wrongly without complaining (-900 for x = 30, not 15), so any + // '^' followed by a minus is refused at load, with or without spaces + assertFallsBack("defense-value", "2^-1", "bracketed"); + assertFallsBack("defense-value", "defense * 2^-1", "bracketed"); + assertFallsBack("defense-value", "defense * 2 ^ -1", "bracketed"); + assertFallsBack("defense-value", "defense * 2 ^\t- 1", "bracketed"); + assertFallsBack("defense-value", "defense * (2 ^ -defense)", "bracketed"); + } + + @Test + void negativeExponentWithBrackets_isAccepted() { + List warnings = new ArrayList<>(); + CombatFormulas ok = CombatFormulas.build(CombatPreset.DEFAULT, Map.of("defense-value", "defense * 2^(-1)"), + warnings::add); + assertTrue(warnings.isEmpty(), warnings.toString()); + assertTrue(ok.isOverridden(CombatExpression.DEFENSE_VALUE)); + assertEquals(15D, ok.eval(CombatExpression.DEFENSE_VALUE, 30D, 1D, 1D), DELTA); + + // A minus that is not an exponent's sign is fine + CombatFormulas minus = CombatFormulas.build(CombatPreset.DEFAULT, + Map.of("defense-value", "max(0, defense - 2^2)"), warnings::add); + assertTrue(warnings.isEmpty(), warnings.toString()); + assertEquals(26D, minus.eval(CombatExpression.DEFENSE_VALUE, 30D, 1D, 1D), DELTA); + } + + @Test + void brokenFormula_divisionByZero() { + assertFallsBack("defense-mitigation", "damage / (damage - damage)", "infinity"); + } + + @Test + void brokenFormula_notANumber() { + assertFallsBack("damage-scaling", "0 / 0", "NaN"); + } + + @Test + void brokenFormula_empty() { + assertFallsBack("direct-damage", " ", "empty"); + } + + @Test + void brokenFormula_wrongType() { + assertFallsBack("direct-damage", Collections.singletonList("damage"), "text or a number"); + } + + @Test + void brokenFormula_fallsBackToTheChosenPresetNotToTheDefault() { + List warnings = new ArrayList<>(); + CombatFormulas formulas = CombatFormulas.build(CombatPreset.LEGACY, + Map.of("defense-mitigation", "damage * nonsense"), warnings::add); + + assertEquals(1, warnings.size()); + assertTrue(warnings.get(0).contains("legacy"), warnings.get(0)); + // 1 - 30 * 0.8 * 0.01 = 0.76, the legacy result, not the default's 0.2 + assertEquals(15.2D, hit(formulas, neutral(true)).getDamage(), DELTA); + } + + @Test + void oneBrokenFormulaDoesNotAffectTheOthers() { + CombatFormulas formulas = CombatFormulas.build(CombatPreset.DEFAULT, + Map.of("defense-value", "nonsense +", "direct-damage", "damage * 0.2"), null); + assertFalse(formulas.isOverridden(CombatExpression.DEFENSE_VALUE)); + assertTrue(formulas.isOverridden(CombatExpression.DIRECT_DAMAGE)); + } + + @Test + void formulaThatBreaksDuringAHit_usesThePresetsForThatHitAndReportsOnce() { + List warnings = new ArrayList<>(); + // Fine for the sample (defense 30), a division by zero when the defense is exactly 31 + CombatFormulas formulas = CombatFormulas.build(CombatPreset.DEFAULT, + Map.of("defense-value", "defense * 10 / (defense - 31)"), warnings::add); + assertTrue(warnings.isEmpty()); + assertTrue(formulas.isOverridden(CombatExpression.DEFENSE_VALUE)); + + double expected = CombatFormulas.of(CombatPreset.DEFAULT).eval(CombatExpression.DEFENSE_VALUE, 31D, 1D, 1D); + assertEquals(expected, formulas.eval(CombatExpression.DEFENSE_VALUE, 31D, 1D, 1D), 0D); + assertEquals(expected, formulas.eval(CombatExpression.DEFENSE_VALUE, 31D, 1D, 1D), 0D); + + assertEquals(1, warnings.size(), warnings.toString()); + assertTrue(warnings.get(0).contains("'defense-value'")); + + // And through the calculator: it returns a number rather than throwing + Result r = new DamageCalculator(neutral(false), formulas).calculate(20, 1, 1, 31D, 0.8); + assertTrue(Double.isFinite(r.getDamage())); + } + + @Test + void presetExpressions_keepTheirOwnNonFiniteResultsAsTheyAlwaysDid() { + // No override, so nothing to fall back from: the result is what the Java formula gave (and no message) + List warnings = new ArrayList<>(); + CombatFormulas formulas = CombatFormulas.build(CombatPreset.DEFAULT, null, warnings::add); + Modifiers m = new Modifiers(1, 1, 1, true, 1, 1, 0, 1, 1, 0, false); + Result expected = new ReferenceDamageCalculator(m).calculate(Double.POSITIVE_INFINITY, 1, 1, 10D, 1); + Result actual = new DamageCalculator(m, formulas).calculate(Double.POSITIVE_INFINITY, 1, 1, 10D, 1); + assertEquals(expected.getDamage(), actual.getDamage(), 0D); + assertEquals(Double.doubleToLongBits(expected.getDefended()), Double.doubleToLongBits(actual.getDefended())); + assertTrue(warnings.isEmpty()); + } +}