diff --git a/README.md b/README.md index 0b2bd1f..1994b1b 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ works with. The maintainers publish the releases of the mods in this repository. | [itemquantity](mods/itemquantity/) | 10× as many item drops | | [pob](mods/pob/) | preview and import character builds through an external converter; requires LocalExile #639 | | [itemrarity](mods/itemrarity/) | 10× the chance of magic, rare and unique equipment | +| [excitingitems](mods/excitingitems/) | rare drop surprises: unique modifiers as extra implicits, empowered modifiers and a fractured extra modifier, all configurable | ## Contributing People and AI agents are both welcome. Start with [AGENTS.md](AGENTS.md): how a mod is laid out, the rules, and how to diff --git a/mods.json b/mods.json index 89582f9..06f04ca 100644 --- a/mods.json +++ b/mods.json @@ -2,6 +2,7 @@ "version": 1, "mods": [ { "id": "backpack", "name": "Extra Backpack", "description": "An optional native 20-slot extra backpack for every character class.", "author": "zj1022", "version": "1.0.3", "compatibleClientVersions": ["0.5.1-beta", "0.5.2-beta"], "kind": "feature", "type": "script", "path": "mods/backpack", "depends": [], "settings": false }, + { "id": "excitingitems", "name": "Exciting Items", "description": "Rare chances on magic, rare and unique drops: a unique item's modifier as an extra implicit, an empowered modifier 10-100% above its roll, and one modifier more than the item could have, fractured with its side; they can all land on one item.", "author": "marshmellion", "version": "1.1.0", "compatibleClientVersions": ["0.5.2-beta"], "kind": "feature", "type": "script", "path": "mods/excitingitems", "depends": ["Game"], "settings": true }, { "id": "fastcampaign", "name": "Fast Campaign", "description": "A faster campaign: 5x kill experience, +50% movement speed, and /fast lists the commands that skip ahead.", "author": "LocalExile", "version": "1.1.4", "compatibleClientVersions": ["0.4.3-beta", "0.5.0-beta", "0.5.1-beta", "0.5.2-beta"], "kind": "feature", "type": "project", "path": "mods/fastcampaign", "depends": [], "settings": true }, { "id": "globalchat", "name": "Global Chat", "description": "Talk to other LocalExile players: global, trade and whisper chat go through the LocalExile global chat server.", "author": "JetStream", "version": "1.1.4", "compatibleClientVersions": ["0.4.3-beta", "0.5.0-beta", "0.5.1-beta", "0.5.2-beta"], "kind": "feature", "type": "project", "path": "mods/globalchat", "depends": [], "settings": true }, { "id": "gm-commands", "name": "GM Commands", "description": "The development and testing chat commands: teleport, items, monsters, experience, quest flags, test hits and protocol probes.", "author": "LocalExile", "version": "1.5.0", "compatibleClientVersions": ["0.5.2-beta"], "kind": "feature", "type": "project", "path": "mods/gm-commands", "depends": ["Game"], "settings": false }, diff --git a/mods/excitingitems/ExcitingItems.cs b/mods/excitingitems/ExcitingItems.cs new file mode 100644 index 0000000..b8e03de --- /dev/null +++ b/mods/excitingitems/ExcitingItems.cs @@ -0,0 +1,513 @@ +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; +using GameServer.Core.Protocol.Instance; +using GameServer.Modding; + +/// +/// Rare chances on magic, rare and unique drops, each its own and all able to land on one item: +/// - a unique item's modifier as an extra implicit (one, two or three; which ones by the chosen mode); +/// - an empowered modifier: one implicit or explicit modifier's values times 1.1 to 2; +/// - an extra modifier, one more than the item could have, and every modifier of its side (prefixes or suffixes) +/// fractured. +/// There is no hook on a rolled drop, so the mod watches the instance's ground for new items on the player tick, takes +/// a chosen one off the ground and puts the changed item down in its place; the Gateway's ground sync removes the old +/// object from the client and creates the new one. The game's own refusals (no fracturing of influenced or synthesised +/// items) are its crafting rules, not a drop's: an item gets these whatever it is. +/// +public sealed class ExcitingItemsMod : IMod +{ + sealed record ImplicitChoices(int Chance, int ChanceTwo, int ChanceThree, string Mode, bool RarityWeights, string[] Rarities); + sealed record EmpoweredChoices(int Chance, int[] Percent, string[] Rarities); + sealed record ExtraChoices(int Chance, string[] Rarities, bool InfluencedMods = true); + sealed record Choices(ImplicitChoices Implicits, EmpoweredChoices Empowered, ExtraChoices ExtraModifier, string[] Blacklist, + bool Mark, bool ShowInFilters, bool Announce, string FilterFolder); + + const string FilterStart = "# >>> excitingitems (LocalExile mod): always show exciting items >>>"; + const string FilterEnd = "# <<< excitingitems <<<"; + const string OwnFilter = "LocalExile Exciting Items.filter"; + // What Unique Implicits, this mod's old name, put in the filters: taken out again. + const string OldStart = "# >>> uniqueimplicits (LocalExile mod): always show items with a unique implicit >>>"; + const string OldEnd = "# <<< uniqueimplicits <<<"; + const string OldOwnFilter = "LocalExile Unique Implicits.filter"; + static readonly string[] FilterRule = + [ + "Show", + " SynthesisedItem True", + " SetFontSize 45", + " SetTextColor 255 255 255 255", + " SetBorderColor 255 215 0 255", + " SetBackgroundColor 110 0 150 255", + " PlayAlertSound 6 300", + " PlayEffect Yellow", + " MinimapIcon 0 Yellow Star", + ]; + + // A modifier that names a slot or a kind of item, or changes the item it is on, belongs on the kinds of item the + // uniques that have it are. The others can go on any gear. + static readonly string[] SlotWords = + [ + "local_", "socketed", "ring", "amulet", "belt", "quiver", "shield", "off_hand", "main_hand", "weapon", "boots", + "gloves", "helmet", "body_armour", "flask", "jewel", "wand", "bow", "staff", "sword", "axe", "mace", "claw", + "dagger", "sceptre", "one_hand", "two_hand", "dual_wield", "wielding", "while_holding", "unarmed", "this_item", + "item_", "radius", "passive", + ]; + static readonly HashSet JewelClasses = new(StringComparer.OrdinalIgnoreCase) { "Jewel", "AbyssJewel" }; + static readonly HashSet NotGear = new(StringComparer.OrdinalIgnoreCase) + { "Jewel", "AbyssJewel", "AnimalCharm", "Map", "MapFragment", "Relic", "SanctumRelic", "Tincture" }; + + [Flags] enum Theme { None = 0, Offence = 1, Defence = 2, Speed = 4, Ailment = 8, Scaling = 16, Utility = 32 } + + sealed class Source(ModCatalog.Mod mod, bool bound, Dictionary ranges, string unique, Theme theme) + { + public ModCatalog.Mod Mod => mod; + public bool Bound => bound; + public Dictionary Ranges => ranges; + public string Unique => unique; + public Theme Theme => theme; + public HashSet Classes { get; } = new(StringComparer.OrdinalIgnoreCase); + public bool Jewel => Classes.Overlaps(JewelClasses); + public bool Gear => Classes.Any(c => !NotGear.Contains(c)); + /// The drop weight of the most common unique that has the modifier (0 to 1; Mageblood about 0.001). + public double Weight; + } + sealed class Watch { public uint Next; public bool Started; } + sealed record Forced(int Implicits, bool Empowered, bool Extra); + + readonly ConditionalWeakTable> _pools = new(); + readonly ConditionalWeakTable _watches = new(); + Choices _choices = new(new(1000, 100000, 1000000, "wild", true, ["magic", "rare", "unique"]), new(500, [10, 100], ["magic", "rare", "unique"]), + new(1000, ["magic", "rare", "unique"]), [], true, true, true, ""); + Forced? _forced; + Action _log = _ => { }; + + public void Load(IModContext mod) + { + string id = mod.Manifest.Id; + _choices = mod.Settings(); + _log = mod.Log; + try { mod.Log(Filters(_choices)); } + catch (Exception e) { mod.Log($"loot filters not updated: {e.Message}"); } + GameEvents.Tick.Add(id, (conn, _) => Scan(conn)); + GameEvents.Command(id, "exciting", + "/exciting (Exciting Items: the chances) | /exciting next implicit [1-3] | empowered | extra | all (the next magic, rare or unique drop gets it)", + async (conn, args) => + { + var player = Program.PlayerOf(conn); + if (args.Length > 0 && args[0].Equals("next", StringComparison.OrdinalIgnoreCase)) + { + string what = args.Length > 1 ? args[1].ToLowerInvariant() : "all"; + int count = args.Length > 2 && int.TryParse(args[2], out int n) ? Math.Clamp(n, 1, 3) : 1; + var forced = what switch + { + "implicit" or "implicits" => new Forced(count, false, false), + "empowered" or "boost" => new Forced(0, true, false), + "extra" or "fractured" => new Forced(0, false, true), + _ => new Forced(count, true, true), + }; + Volatile.Write(ref _forced, forced); + await player.Tell($"Exciting Items: the next magic, rare or unique drop gets {Effects(forced.Implicits, forced.Empowered, forced.Extra)}."); + return; + } + var c = _choices; + int known = Pool(Game.ItemsFor(conn), Game.UniquesFor(conn), Game.DropsFor(conn)).Count; + await player.Tell($"Exciting Items: unique implicits 1 in {c.Implicits.Chance} / {c.Implicits.ChanceTwo} / {c.Implicits.ChanceThree} " + + $"({c.Implicits.Mode}, {known} modifiers known); empowered 1 in {c.Empowered.Chance} (+{Low(c)}-{High(c)}%); " + + $"extra fractured modifier 1 in {c.ExtraModifier.Chance}. /exciting next implicit|empowered|extra|all forces one."); + }); + } + + static int Low(Choices c) => Math.Max(1, c.Empowered.Percent.ElementAtOrDefault(0)); + static int High(Choices c) => Math.Max(Low(c), c.Empowered.Percent.ElementAtOrDefault(1)); + + static string Effects(int implicits, bool empowered, bool extra) => string.Join(", ", new[] + { + implicits > 0 ? (implicits == 1 ? "a unique implicit" : $"{implicits} unique implicits") : null, + empowered ? "an empowered modifier" : null, + extra ? "an extra fractured modifier" : null, + }.Where(s => s is not null)); + + static bool Takes(string[] rarities, ItemRarity rarity) => rarities.Contains(rarity.ToString(), StringComparer.OrdinalIgnoreCase); + + // ---- which items and which modifiers ---- + + /// Gear and jewels with modifiers; not flasks, maps, cluster jewels (their modifiers come from their + /// enchantments) or Timeless Jewels. + static bool Target(ItemCatalog.BaseType type) => type.Components.Contains("Mods") && !type.Components.Contains("Flask") + && !type.Components.Contains("Map") && !type.Components.Contains("MapKey") + && (JewelClasses.Contains(type.Class) ? !type.Id.Contains("PassiveTreeExpansion") && !type.Id.Contains("Timeless") : !NotGear.Contains(type.Class)); + + bool Blacklisted(ModCatalog.Mod mod) => _choices.Blacklist.Any(entry => entry.StartsWith("stat:", StringComparison.OrdinalIgnoreCase) + ? mod.Stats.Any(s => s.Id.Contains(entry[5..], StringComparison.OrdinalIgnoreCase)) + : !entry.StartsWith("class:", StringComparison.OrdinalIgnoreCase) && mod.Id.StartsWith(entry, StringComparison.OrdinalIgnoreCase)); + + /// A modifier only uniques of blacklisted kinds of item have ("class:UtilityFlask"). + bool BlacklistedClasses(IEnumerable classes) + { + var listed = _choices.Blacklist.Where(e => e.StartsWith("class:", StringComparison.OrdinalIgnoreCase)).Select(e => e[6..].Trim()).ToHashSet(StringComparer.OrdinalIgnoreCase); + return listed.Count > 0 && classes.All(listed.Contains); + } + + static readonly (Theme Theme, Regex Words)[] Themes = + [ + (Theme.Speed, new(@"movement_velocity|movement_speed|onslaught|phasing|flask_effect|action_speed")), + (Theme.Ailment, new(@"ailment|ignite|chill|freez|shock|poison|bleed|stun|curse|elusive|blind|maim|hinder|avoid_|immun|_on_self")), + (Theme.Scaling, new(@"_per_|per_\d|for_each|_charge|charges|aura|reservation|gem_level|_gems_|socketed|minion|totem|brand")), + (Theme.Defence, new(@"life|energy_shield|armour|evasion|resist|block|suppress|damage_taken|damage_reduction|regenerat|recoup|fortif|dodge|recover|leech_from")), + (Theme.Offence, new(@"damage|attack_speed|cast_speed|critical|penetrat|accuracy|projectile|area_of_effect|chain|pierce|impale|skill_effect_duration|added_")), + ]; + + /// What a modifier is for, told by its stats' names; a modifier of none of these is utility. + static Theme ThemeOf(ModCatalog.Mod mod) + { + string words = string.Join(' ', mod.Stats.Select(s => s.Id)).ToLowerInvariant(); + var theme = Theme.None; + foreach (var (t, regex) in Themes) if (regex.IsMatch(words)) theme |= t; + // "damage taken" and "leech" are defence and sustain, not offence. + if (theme.HasFlag(Theme.Offence) && Regex.IsMatch(words, "damage_taken|damage_reduction") && !Regex.IsMatch(words, @"damage_\+%|added_|_damage_%")) theme &= ~Theme.Offence; + return theme == Theme.None ? Theme.Utility : theme; + } + + /// The themes a slot takes in thematic mode. + static Theme Wants(ItemCatalog.BaseType type) => type.Class switch + { + "Gloves" or "Quiver" => Theme.Offence, + "Body Armour" or "Shield" => Theme.Defence, + "Boots" => Theme.Speed | Theme.Ailment, + "Helmet" => Theme.Defence | Theme.Scaling, + "Amulet" or "Ring" or "Belt" => Theme.Utility, + _ => type.Tags.Contains("weapon") ? Theme.Offence : Theme.Utility, + }; + + // Every unique's modifiers, once per data set: which kinds of item have each, and how it rolls there. + List Pool(ItemCatalog catalog, UniqueCatalog uniques, ItemDrops drops) => _pools.GetValue(_catalog = catalog, _ => + { + var byId = new Dictionary(StringComparer.Ordinal); + foreach (var unique in uniques.All) + { + string? baseClass = catalog.Find(unique.BaseTypeId)?.Class; + var ids = unique.Mods.Concat(unique.Variants?.SelectMany(v => v.Mods) ?? []); + foreach (string modId in ids.Distinct()) + { + if (catalog.Mods.ById(modId) is not { Stats.Count: > 0 } mod || Blacklisted(mod)) continue; + if (!byId.TryGetValue(modId, out var source)) + { + string words = (mod.Id + " " + string.Join(' ', mod.Stats.Select(s => s.Id))).ToLowerInvariant(); + bool bound = mod.Stats.Any(s => s.Local) || SlotWords.Any(words.Contains); + var ranges = (unique.Ranges ?? []).Where(r => r.Mod == modId && !r.Implicit) + .GroupBy(r => r.Stat).ToDictionary(g => g.Key, g => (g.First().Min, g.First().Max)); + byId[modId] = source = new(mod, bound, ranges, unique.Name, ThemeOf(mod)); + } + if (baseClass is not null) source.Classes.Add(baseClass); + source.Weight = Math.Max(source.Weight, drops.UniqueWeight(unique.Name)); + } + } + // A modifier only flasks, maps or the like have stays with them, so it never reaches gear or a jewel. + var pool = byId.Values.Where(s => s.Classes.Count > 0 && !BlacklistedClasses(s.Classes)).ToList(); + // A unique with no drop weight (a boss's, a league's) counts as the rarest there is. + double rarest = pool.Where(s => s.Weight > 0).Select(s => s.Weight).DefaultIfEmpty(1).Min(); + foreach (var source in pool) if (source.Weight <= 0) source.Weight = rarest; + return pool; + }); + + /// Whether a modifier may go on this kind of item. Jewels and gear never mix, and a modifier is always + /// welcome on its own kind of item. Every modifier not blacklisted has somewhere to go: one the chosen mode leaves + /// without a slot that drops follows Wild's rules, and one tied to kinds of item that never drop (a fishing rod's) + /// goes on any gear. + bool Fits(Source source, ItemCatalog.BaseType type) + { + string mode = _choices.Implicits.Mode.ToLowerInvariant(); + if (Rule(source, type, mode)) return true; + if (Placeable(source, mode)) return false; + if (mode != "wild" && Rule(source, type, "wild")) return true; + return !Placeable(source, "wild") && JewelClasses.Contains(type.Class) == source.Jewel; + } + + static bool Rule(Source source, ItemCatalog.BaseType type, string mode) + { + bool jewel = JewelClasses.Contains(type.Class); + if (jewel ? !source.Jewel : !source.Gear) return false; + if (source.Classes.Contains(type.Class)) return true; + if (source.Bound) return false; + return mode switch + { + "sanity" => false, + "thematic" => jewel || (source.Theme & Wants(type)) != 0, + _ => true, + }; + } + + readonly ConditionalWeakTable> _placeable = new(); + readonly ConditionalWeakTable> _slots = new(); + ItemCatalog? _catalog; + + /// Whether some kind of item that drops (and the jewels) takes the modifier by the mode's rule. + bool Placeable(Source source, string mode) + { + if (_catalog is not { } catalog) return true; + var known = _placeable.GetValue(catalog, _ => new()); + lock (known) + if (!known.TryGetValue((source, mode), out bool placeable)) + known[(source, mode)] = placeable = Slots(catalog).Any(t => Rule(source, t, mode)); + else return placeable; + return known[(source, mode)]; + } + + /// One base of each kind of item a monster drops, and of each jewel. + List Slots(ItemCatalog catalog) => _slots.GetValue(catalog, c => + { + var slots = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + for (int row = 0; c.Row(row) is { } t; row++) + if (Target(t) && (JewelClasses.Contains(t.Class) || ItemDrops.EquipmentClasses.Contains(t.Class) && ItemDrops.Droppable(t)) && seen.Add(t.Class)) + slots.Add(t); + return slots; + }); + + // One by weight: a modifier of a rarer unique comes up that much less often. Without the setting, every one alike. + Source Pick(List pool, Random rng, out int index) + { + index = rng.Next(pool.Count); + if (!_choices.Implicits.RarityWeights) return pool[index]; + double at = rng.NextDouble() * pool.Sum(s => s.Weight); + for (int i = 0; i < pool.Count; i++) + if ((at -= pool[i].Weight) < 0) { index = i; break; } + return pool[index]; + } + + // ---- the three effects ---- + + // How many implicits a drop gets: the rarest roll that succeeds, three before two before one. + int ImplicitsRolled(Random rng) => + rng.Next(Math.Max(1, _choices.Implicits.ChanceThree)) == 0 ? 3 + : rng.Next(Math.Max(1, _choices.Implicits.ChanceTwo)) == 0 ? 2 + : rng.Next(Math.Max(1, _choices.Implicits.Chance)) == 0 ? 1 : 0; + + Item? WithUniqueImplicits(ClientState conn, Item item, ItemCatalog.BaseType type, int count, Random rng, List log) + { + var catalog = Game.ItemsFor(conn); + var have = item.Mods.Select(m => m.Hash).ToHashSet(); + var pool = Pool(catalog, Game.UniquesFor(conn), Game.DropsFor(conn)).Where(s => !have.Contains(s.Mod.Hash) && Fits(s, type)).ToList(); + var mods = item.Mods.ToList(); + var families = new HashSet(item.Mods.SelectMany(m => catalog.Mods.ByHash(m.Hash)?.Families ?? [])); + int added = 0; + while (added < count && pool.Count > 0) + { + var source = Pick(pool, rng, out int pick); + pool.RemoveAt(pick); + // Two modifiers of one family would be the same line twice. + if (source.Mod.Families.Any(families.Contains)) continue; + foreach (int family in source.Mod.Families) families.Add(family); + var rolled = source.Mod.Roll(ModSection.Implicit, rng, stat => source.Ranges.TryGetValue(stat, out var range) ? range : null); + int at = mods.FindLastIndex(m => m.Section == ModSection.Implicit) + 1; + if (at == 0) at = mods.FindIndex(m => m.Section == ModSection.Explicit) is int first and >= 0 ? first : mods.Count; + mods.Insert(at, rolled); + log.Add($"implicit \"{catalog.Mods.Describe(rolled)}\" (from {source.Unique})"); + added++; + } + return added == 0 ? null : item with { Mods = mods }; + } + + /// One implicit or explicit modifier (a unique implicit this mod added included), every value of it better + /// than it is by the chosen percent. A modifier with a downside or a value that picks something (a granted gem, a + /// seed) is not chosen. + Item? WithEmpowered(ClientState conn, Item item, Random rng, List log) + { + var mods = Game.ItemsFor(conn).Mods; + var own = Game.UniquesFor(conn).RollsOf(item); + // A value its modifier cannot roll otherwise (a fixed 1) is a switch: "has no sockets", "cannot leech". + bool Switch(ModCatalog.Mod mod, ModSection section, int stat, int value) => + Math.Abs(value) == 1 && (own?.Invoke(mod, section, stat) ?? mod.RangeAt(stat)) is var (min, max) && min == max; + var candidates = item.Mods.Select((m, i) => (m, i)).Where(p => p.m.Section is ModSection.Explicit or ModSection.Implicit && mods.ByHash(p.m.Hash) is { } mod + && p.m.Values.Any(v => v != 0) + && p.m.Values.Select((v, s) => s < mod.Stats.Count && !PicksSomething(mod.Stats[s].Id) && !Switch(mod, p.m.Section, s, v) + && (v == 0 || (v > 0) != LessIsBetter(mod.Stats[s].Id))).All(ok => ok)).ToList(); + if (candidates.Count == 0) return null; + var (chosen, index) = candidates[rng.Next(candidates.Count)]; + int percent = rng.Next(Low(_choices), High(_choices) + 1); + var values = chosen.Values.Select(v => v == 0 ? 0 : (int)Math.Clamp(Math.Round(v * (1 + percent / 100.0), MidpointRounding.AwayFromZero) is var x && x == v ? v + Math.Sign(v) : x, int.MinValue, int.MaxValue)).ToList(); + var changed = item.Mods.ToList(); + changed[index] = chosen with { Values = values }; + log.Add($"empowered +{percent}%: \"{mods.Describe(chosen)}\" -> {string.Join(", ", values)}"); + return item with { Mods = changed }; + } + + /// One modifier more than the item could have, and its side fractured: a rare (or magic item) is first + /// filled to its most prefixes and suffixes, then gets one more of a side; a unique gets one rare-style prefix or + /// suffix. The fractured modifiers go to the front of the explicits, where the client reads them. + Item? WithExtraModifier(ClientState conn, Item item, ItemCatalog.BaseType type, Random rng, List log) + { + if (item.FracturedCount > 0) return null; + var catalog = Game.ItemsFor(conn); + var rolls = Game.RollsFor(conn); + var pool = rolls.Pool(type, item).Where(p => p.Weight > 0 && !Blacklisted(p.Mod)).ToList(); + string? influencedBy = null; + if (_choices.ExtraModifier.InfluencedMods) + { + // The modifiers one influence (not the item's own) adds to this base's pool at this item level, as an item + // with that influence would roll them; the item does not get the influence. + var have = pool.Select(p => p.Mod.Hash).ToHashSet(); + var options = Enum.GetValues().Where(i => i != ItemInfluence.None && !item.Influences.HasFlag(i)) + .Select(i => (Influence: i, Mods: rolls.Pool(type, item.ItemLevel, item.Influences | i, null) + .Where(p => p.Weight > 0 && !have.Contains(p.Mod.Hash) && !Blacklisted(p.Mod)).ToList())) + .Where(o => o.Mods.Count > 0).ToList(); + if (options.Count > 0) + { + var chosen = options[rng.Next(options.Count)]; + influencedBy = chosen.Influence.ToString(); + pool.AddRange(chosen.Mods); + } + } + if (pool.Count == 0) return null; + var mods = item.Mods.ToList(); + int SideOf(ItemMod m) => catalog.Mods.ByHash(m.Hash)?.GenerationType ?? 0; + var families = new HashSet(mods.SelectMany(m => catalog.Mods.ByHash(m.Hash)?.Families ?? [])); + var added = new List(); + ItemMod? Add(int side) + { + var open = pool.Where(p => p.Mod.GenerationType == side && !p.Mod.Families.Any(families.Contains) && mods.All(m => m.Hash != p.Mod.Hash)).ToList(); + if (open.Count == 0) return null; + int at = rng.Next(open.Sum(p => p.Weight)); + var mod = open.First(p => (at -= p.Weight) < 0).Mod; + foreach (int f in mod.Families) families.Add(f); + var rolled = mod.Roll(ModSection.Explicit, rng); + mods.Add(rolled); + added.Add(rolled); + return rolled; + } + const int Prefix = ItemRolls.Prefix, Suffix = ItemRolls.Suffix; + int chosenSide = rng.Next(2) == 0 ? Prefix : Suffix; + if (item.Rarity is ItemRarity.Rare or ItemRarity.Magic) + { + var (most, mostSuffixes) = item.Rarity == ItemRarity.Rare ? rolls.RareMaxAffixes(item) : (1, 1); + while (mods.Count(m => m.Section == ModSection.Explicit && SideOf(m) == Prefix) < most && Add(Prefix) is not null) { } + while (mods.Count(m => m.Section == ModSection.Explicit && SideOf(m) == Suffix) < mostSuffixes && Add(Suffix) is not null) { } + } + if (Add(chosenSide) is null && Add(chosenSide == Prefix ? Suffix : Prefix) is null) return null; + chosenSide = SideOf(added[^1]); + // A unique's own modifiers have no side: only the one added is fractured there. + bool Fractured(ItemMod m) => m.Section == ModSection.Explicit && (item.Rarity == ItemRarity.Unique ? ReferenceEquals(m, added[^1]) : SideOf(m) == chosenSide); + var ordered = mods.Where(m => m.Section != ModSection.Explicit) + .Concat(mods.Where(Fractured)).Concat(mods.Where(m => m.Section == ModSection.Explicit && !Fractured(m))).ToList(); + log.Add($"extra {(chosenSide == Prefix ? "prefix" : "suffix")} \"{catalog.Mods.Describe(added[^1])}\"" + + (influencedBy is null ? "" : $" ({influencedBy} modifiers in the pool)") + + (added.Count > 1 ? $" after {added.Count - 1} to fill the item" : "") + $", {ordered.Count(Fractured)} fractured"); + return item with { Mods = ordered, FracturedCount = (byte)ordered.Count(Fractured), RequiredLevel = null }; + } + + /// A stat whose value says which one and not how much: a granted support gem and its socket, a Timeless + /// Jewel's seed, conqueror and version, Thread of Hope's ring, a veiled modifier's seed. + static bool PicksSomething(string stat) => stat.Contains("_index", StringComparison.Ordinal) + || stat.StartsWith("local_unique_jewel_alternate_tree_", StringComparison.Ordinal) + || stat is "local_jewel_variable_ring_radius_value" or "veiled_mod_seed"; + + /// A stat where less is better: damage the character takes, what a skill costs, flask charges used, + /// requirements, and ailments, curses and self-damage on the character. Told by the stat's name. + static bool LessIsBetter(string stat) => LowerIsBetter.IsMatch(stat) && !OnEnemies.IsMatch(stat); + + static readonly Regex LowerIsBetter = new( + @"damage_taken_(from_hits_|over_time_|from_crit_)?\+|_cost_\+|charges_used_\+|requirements?_\+" + + @"|^(local_)?self_.*(duration|effect)_\+%|(curse|chill|shocked)_effect(iveness)?_on_self_\+%|ailment_on_self_duration_\+%" + + @"|against_self|^self_.*damage_on_.*skill_use|life_taken_per_minute|reservation_efficiency_-2%_per_1|^-%_of_your", + RegexOptions.CultureInvariant); + + // "Enemies take increased damage" is damage taken too, and there more is better. + static readonly Regex OnEnemies = new(@"enem(y|ies).*damage_taken|ailment_types|chilling_areas", RegexOptions.CultureInvariant); + + /// The drop with whatever effects come up (or were forced), or null with none. + Item? Excite(ClientState conn, Item item, Random rng, Forced? forced, out string effects, List log) + { + effects = ""; + var c = _choices; + if (item.Rarity is not (ItemRarity.Magic or ItemRarity.Rare or ItemRarity.Unique) || item.Mirrored || item.Corrupted + || Game.ItemsFor(conn).ByHash(item.TypeHash) is not { } type || !Target(type)) return null; + bool extra = forced?.Extra ?? (Takes(c.ExtraModifier.Rarities, item.Rarity) && rng.Next(Math.Max(1, c.ExtraModifier.Chance)) == 0); + bool empowered = forced?.Empowered ?? (Takes(c.Empowered.Rarities, item.Rarity) && rng.Next(Math.Max(1, c.Empowered.Chance)) == 0); + int implicits = forced?.Implicits ?? (Takes(c.Implicits.Rarities, item.Rarity) ? ImplicitsRolled(rng) : 0); + if (!extra && !empowered && implicits == 0) return null; + var now = item; + bool gotExtra = false, gotEmpowered = false; int gotImplicits = 0; + if (extra && WithExtraModifier(conn, now, type, rng, log) is { } withExtra) { now = withExtra; gotExtra = true; } + if (implicits > 0 && WithUniqueImplicits(conn, now, type, implicits, rng, log) is { } withImplicits) + { + gotImplicits = withImplicits.Mods.Count(m => m.Section == ModSection.Implicit) - now.Mods.Count(m => m.Section == ModSection.Implicit); + now = withImplicits; + } + // Last, so it can land on any of them, a unique implicit just added included. + if (empowered && WithEmpowered(conn, now, rng, log) is { } withEmpowered) { now = withEmpowered; gotEmpowered = true; } + if (ReferenceEquals(now, item)) return null; + effects = Effects(gotImplicits, gotEmpowered, gotExtra); + return now with { Synthesised = c.Mark || now.Synthesised }; + } + + async Task Scan(ClientState conn) + { + var ground = conn.Instance.Ground; + var watch = _watches.GetValue(ground, _ => new Watch()); + var found = new List(); + lock (watch) + { + var all = ground.All(); + uint last = all.Count == 0 ? 0 : all.Max(e => e.Id); + // What already lay there when the mod first saw this ground is left alone. + if (!watch.Started) { watch.Started = true; watch.Next = last + 1; return; } + foreach (var (id, lying) in all) + { + if (id < watch.Next || lying.Item.Rarity is not (ItemRarity.Magic or ItemRarity.Rare or ItemRarity.Unique)) continue; + var forced = Volatile.Read(ref _forced); + var log = new List(); + if (Excite(conn, lying.Item, Random.Shared, forced, out string effects, log) is not { } changed) continue; + // Only one caller gets the item, so a pickup in the same moment cannot duplicate it. + if (ground.Take(id, lying) is null) continue; + uint replaced = ground.Add(new WorldItemObject(lying.GridX, lying.GridY, changed)); + last = Math.Max(last, replaced); + if (forced is not null) Interlocked.CompareExchange(ref _forced, null, forced); + string name = Game.ItemsFor(conn).ByHash(changed.TypeHash)?.Name ?? "item"; + found.Add($"{changed.Rarity} {name} with {effects}"); + _log($"{changed.Rarity} {name} at ({lying.GridX}, {lying.GridY}): {string.Join("; ", log)}"); + } + watch.Next = last + 1; + } + if (!_choices.Announce) return; + foreach (string text in found) await Program.PlayerOf(conn).Tell("* Exciting item dropped: " + text); + } + + // ---- loot filters ---- + + // The rule goes at the top of every loot filter in the folder, between its two marker lines, or comes out again. + // The old name's rule comes out in any case. + static string Filters(Choices choices) + { + string folder = choices.FilterFolder.Trim().Length > 0 ? choices.FilterFolder.Trim() + : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "My Games", "Path of Exile", "LocalExile"); + if (!Directory.Exists(folder)) return $"no loot filter folder at {folder}"; + bool wanted = choices.ShowInFilters && choices.Mark; + string own = Path.Combine(folder, OwnFilter), oldOwn = Path.Combine(folder, OldOwnFilter); + if (File.Exists(oldOwn)) File.Delete(oldOwn); + var filters = Directory.GetFiles(folder, "*.filter").Where(f => !f.Equals(own, StringComparison.OrdinalIgnoreCase)).ToList(); + int changed = 0; + string[] block = [FilterStart, .. FilterRule, FilterEnd]; + static bool Cut(List lines, string start, string end) + { + int from = lines.FindIndex(l => l.Trim() == start), to = lines.FindIndex(l => l.Trim() == end); + if (from < 0 || to < from) return false; + lines.RemoveRange(from, to - from + 1); + if (from < lines.Count && lines[from].Trim().Length == 0) lines.RemoveAt(from); + return true; + } + foreach (string file in filters) + { + var lines = File.ReadAllLines(file).ToList(); + var before = string.Join('\n', lines); + Cut(lines, OldStart, OldEnd); + Cut(lines, FilterStart, FilterEnd); + if (wanted) lines.InsertRange(0, block.Append("")); + if (string.Join('\n', lines) == before) continue; + File.WriteAllLines(file, lines); + changed++; + } + // With no filter of the player's own, one that holds only the rule: it hides nothing. + if (wanted && filters.Count == 0 && (!File.Exists(own) || !File.ReadAllLines(own).SequenceEqual(block))) { File.WriteAllLines(own, block); changed++; } + if (!wanted && File.Exists(own)) { File.Delete(own); changed++; } + return $"loot filters in {folder}: {filters.Count} found, {changed} changed (rule {(wanted ? "on" : "off")})"; + } +} diff --git a/mods/excitingitems/README.md b/mods/excitingitems/README.md new file mode 100644 index 0000000..b5eef20 --- /dev/null +++ b/mods/excitingitems/README.md @@ -0,0 +1,74 @@ +# Exciting Items + +Rare chances on magic, rare and unique drops, each with its own chance and all able to land on the same item: + +- **Unique implicits.** The item gets one, two or three modifiers of unique items as extra implicits. A modifier of a + rarer unique comes up as seldom as that unique drops. +- **An empowered modifier.** One of its modifiers, implicit or explicit (a unique implicit from above included), rolls 10-100% higher than it did (a random amount in the + range the settings give), past the top of its tier. A modifier with a downside, or a switch such as "has no + sockets", is never chosen. +- **An extra fractured modifier.** The item gets one modifier more than it could have: a rare is filled to three + prefixes and three suffixes and gets a seventh (a rare jewel a fifth), a magic item a third, a unique one rare-style + prefix or suffix. Every modifier of that side, prefixes or suffixes, is fractured (on a unique, the one added). + These modifiers can also be ones only an influenced item rolls (one influence the item does not have, at the tiers its + item level allows), without the item becoming influenced. + +They apply to influenced items too: the game's crafting rules against fracturing influenced or synthesised items are +for currency, not for drops. An item with any of them drops synthesised, so it looks special on the ground, and a rule +put at the top of your loot filters shows it with a beam and a sound. Chat names which effects a drop got, not what +they are: identify it to see. + +## Which unique modifiers can come + +`implicits.mode` picks one: + +| Mode | Gets | +|---|---| +| Wild (default) | any unique modifier on any gear | +| Sanity | only modifiers of uniques of the same kind of item: swords' on swords, belts' on belts | +| Thematic | offence on weapons, quivers and gloves; defence on body armours and shields; speed and ailments on boots; defence and scaling (per charge, per stat, auras, minions) on helmets; utility and odd unique effects on rings, amulets and belts | + +In every mode a modifier is welcome on its own kind of item (a helmet unique's on helmets), and every modifier not blacklisted can come somewhere: one the chosen mode leaves without a slot that drops follows Wild's rules, and one of a kind of item that never drops (a fishing rod's) can go on any gear. Rare and magic jewels get unique jewels' modifiers in every mode, and gear never gets those. A modifier that names a +kind of item or is local to it (adds to the item's own armour, its sockets) stays on that kind of item. Cluster jewels +and Timeless Jewels get nothing. + +`blacklist` lists modifiers never used: a Mods id or its start, `stat:` and a piece of a stat id, or `class:` and a +kind of item whose uniques' modifiers stay with it. The defaults are the modifiers tied to their own item: radius +jewels' and Timeless Jewels' tree effects, Thread of Hope's ring, granted supports chosen by index (Forbidden Shako), +effects only that unique has (`local_unique_` stats), Tabula Rasa's and level-requirement modifiers, and flasks', +tinctures', maps', idols' and Sanctum relics' modifiers (`class:`). Every other unique modifier can come on some kind +of item in every mode. + +## Commands + +| Command | Does | +|---|---| +| `/exciting` | the chances and the mode | +| `/exciting next implicit [1-3]` | the next magic, rare or unique drop gets that many unique implicits | +| `/exciting next empowered` | the next one gets an empowered modifier | +| `/exciting next extra` | the next one gets an extra fractured modifier | +| `/exciting next all` | the next one gets all three | + +## Settings + +| Setting | Default | Does | +|---|---|---| +| `implicits.chance`, `chanceTwo`, `chanceThree` | 1000, 100000, 1000000 | one, two or three unique implicits: 1 in this many drops | +| `implicits.mode` | wild | wild, sanity or thematic (above) | +| `implicits.rarityWeights` | on | rarer uniques' modifiers come up less often | +| `implicits.rarities`, `empowered.rarities`, `extraModifier.rarities` | magic, rare, unique | which drops can get each effect | +| `empowered.chance` | 500 | 1 in this many drops | +| `empowered.percent` | 10-100 | how much stronger, picked at random | +| `extraModifier.chance` | 1000 | 1 in this many drops | +| `extraModifier.influencedMods` | on | the extra modifier can also be an influenced item's modifier (the item stays uninfluenced) | +| `blacklist` | (above) | modifiers never used as implicits | +| `mark`, `showInFilters` | on, on | the synthesised look, and the loot filter rule | +| `announce` | on | the chat line | +| `filterFolder` | (empty) | the loot filter folder; empty is Documents\My Games\Path of Exile\LocalExile | + +The loot filter rule goes between two marker lines at the top of every `.filter` file in the folder, and comes out +again when the setting is off. Without a filter of your own the mod writes one that holds only the rule. + +Formerly Unique Implicits: its loot filter rule and filter file are taken out when this mod loads. + +Works with LocalExile 0.5.2-beta and its main branch; it needs no change in LocalExile. diff --git a/mods/excitingitems/mod.json b/mods/excitingitems/mod.json new file mode 100644 index 0000000..ce7873e --- /dev/null +++ b/mods/excitingitems/mod.json @@ -0,0 +1,14 @@ +{ + "id": "excitingitems", + "name": "Exciting Items", + "description": "Rare chances on magic, rare and unique drops: a unique item's modifier as an extra implicit, an empowered modifier 10-100% above its roll, and one modifier more than the item could have, fractured with its side; they can all land on one item.", + "author": "marshmellion", + "version": "1.1.0", + "compatibleClientVersions": [ + "0.5.2-beta" + ], + "kind": "feature", + "depends": [ + "Game" + ] +} diff --git a/mods/excitingitems/settings.json b/mods/excitingitems/settings.json new file mode 100644 index 0000000..baae8b7 --- /dev/null +++ b/mods/excitingitems/settings.json @@ -0,0 +1,238 @@ +{ + "version": 1, + "settings": { + "implicits": { + "type": "group", + "label": "Unique implicits", + "description": "A dropped item gets a unique item's modifier as an extra implicit.", + "settings": { + "chance": { + "type": "integer", + "default": 1000, + "min": 1, + "max": 100000000, + "label": "One implicit: 1 in", + "description": "The chance of one unique implicit, as 1 in this many drops." + }, + "chanceTwo": { + "type": "integer", + "default": 100000, + "min": 1, + "max": 100000000, + "label": "Two implicits: 1 in" + }, + "chanceThree": { + "type": "integer", + "default": 1000000, + "min": 1, + "max": 100000000, + "label": "Three implicits: 1 in" + }, + "mode": { + "type": "choice", + "default": "wild", + "options": [ + { + "value": "wild", + "label": "Wild: any modifier on any gear" + }, + { + "value": "sanity", + "label": "Sanity: only modifiers of uniques of the same kind of item" + }, + { + "value": "thematic", + "label": "Thematic: modifiers that suit the slot" + } + ], + "label": "Which modifiers can come", + "description": "Thematic: offence on weapons, quivers and gloves; defence on body armours and shields; speed and ailments on boots; defence and scaling (per charge, per stat, auras) on helmets; utility and odd unique effects on rings, amulets and belts. Jewels get unique jewels' modifiers in every mode, and gear never gets those." + }, + "rarityWeights": { + "type": "bool", + "default": true, + "label": "Rarer uniques, rarer modifiers", + "description": "A modifier of a rare unique (a Mageblood) comes up as seldom as that unique drops. Off: every modifier alike." + }, + "rarities": { + "type": "choices", + "default": [ + "magic", + "rare", + "unique" + ], + "options": [ + { + "value": "magic", + "label": "Magic" + }, + { + "value": "rare", + "label": "Rare" + }, + { + "value": "unique", + "label": "Unique" + } + ], + "label": "Drops that can get them" + } + } + }, + "empowered": { + "type": "group", + "label": "Empowered modifier", + "description": "One of the drop's modifiers, implicit or explicit (a unique implicit included), rolls higher than it can: its value times 1.1 to 2.", + "settings": { + "chance": { + "type": "integer", + "default": 500, + "min": 1, + "max": 100000000, + "label": "Chance: 1 in" + }, + "percent": { + "type": "range", + "of": "integer", + "default": [ + 10, + 100 + ], + "min": 1, + "max": 1000, + "unit": "%", + "label": "How much stronger", + "description": "Picked at random in this range for each empowered modifier." + }, + "rarities": { + "type": "choices", + "default": [ + "magic", + "rare", + "unique" + ], + "options": [ + { + "value": "magic", + "label": "Magic" + }, + { + "value": "rare", + "label": "Rare" + }, + { + "value": "unique", + "label": "Unique" + } + ], + "label": "Drops that can get it" + } + } + }, + "extraModifier": { + "type": "group", + "label": "Extra fractured modifier", + "description": "The drop gets one modifier more than it could have: a rare 7 (a rare jewel 5), a magic item 3, a unique one rare-style prefix or suffix. Its side (prefixes or suffixes) is fractured.", + "settings": { + "chance": { + "type": "integer", + "default": 1000, + "min": 1, + "max": 100000000, + "label": "Chance: 1 in" + }, + "rarities": { + "type": "choices", + "default": [ + "magic", + "rare", + "unique" + ], + "options": [ + { + "value": "magic", + "label": "Magic" + }, + { + "value": "rare", + "label": "Rare" + }, + { + "value": "unique", + "label": "Unique" + } + ], + "label": "Drops that can get it" + }, + "influencedMods": { + "type": "bool", + "default": true, + "label": "Influenced modifiers too", + "description": "The extra modifier (and the ones that fill the item first) can also be one that only an influenced item rolls: one influence the item does not have is picked, and its modifiers for this base and item level join the pool. The item does not become influenced." + } + } + }, + "blacklist": { + "type": "list", + "item": { + "type": "text", + "minLength": 1 + }, + "default": [ + "LevelRequirementOverride", + "RemoveStats", + "LocalNoWhiteSockets", + "stat:in_radius", + "stat:jewel_radius", + "stat:radius_jewel", + "stat:alternate_tree", + "stat:variable_ring", + "stat:_index", + "stat:unique_jewel", + "stat:allocated", + "stat:notable", + "stat:cluster_jewel", + "stat:local_unique_", + "class:LifeFlask", + "class:ManaFlask", + "class:HybridFlask", + "class:UtilityFlask", + "class:Tincture", + "class:MapKey", + "class:AtlasRelic", + "class:Relic", + "class:SanctumRelic" + ], + "label": "Modifiers never used as implicits", + "description": "A Mods id or the start of one (LevelRequirementOverride), stat: and a piece of a stat id (stat:in_radius), or class: and a kind of item whose uniques' modifiers stay with it (class:UtilityFlask). The defaults are modifiers tied to their own item: radius jewels and tree effects, granted supports by index, effects only that unique has, and flasks', tinctures', maps' and idols' modifiers. Every other unique modifier can come on some kind of item in every mode." + }, + "mark": { + "type": "bool", + "default": true, + "label": "Mark exciting items", + "description": "An item with any of these effects drops synthesised, so it looks special on the ground and in its tooltip." + }, + "showInFilters": { + "type": "bool", + "default": true, + "label": "Loot filter beam", + "description": "Puts a rule at the top of every loot filter in the filter folder that always shows marked items, with a beam and a sound.", + "when": { + "mark": true + } + }, + "announce": { + "type": "bool", + "default": true, + "label": "Tell me in chat", + "description": "A chat line when an exciting item drops, naming which effects it got (not what they are)." + }, + "filterFolder": { + "type": "text", + "default": "", + "label": "Loot filter folder", + "description": "Empty: Documents\\My Games\\Path of Exile\\LocalExile.", + "advanced": true + } + } +}