diff --git a/mods.json b/mods.json
index 4b07959..2ff2eec 100644
--- a/mods.json
+++ b/mods.json
@@ -9,7 +9,7 @@
{ "id": "itemrarity", "name": "Item Rarity", "description": "10 times the chance of magic, rare and unique equipment.", "author": "LocalExile", "version": "1.1.3", "compatibleClientVersions": ["0.4.3-beta", "0.5.0-beta", "0.5.1-beta"], "kind": "feature", "type": "project", "path": "mods/itemrarity", "depends": [], "settings": true },
{ "id": "liveeconomy", "name": "Live Economy", "description": "Faustus's Currency Exchange as a live market: the official Path of Exile leagues' prices, a spread, depth, and orders that fill with time.", "author": "JetStream", "version": "1.1.3", "compatibleClientVersions": ["0.4.3-beta", "0.5.0-beta", "0.5.1-beta"], "kind": "feature", "type": "project", "path": "mods/liveeconomy", "depends": [], "settings": true },
{ "id": "petloot", "name": "Pet Loot", "description": "Worn pets collect selected currency with per-character filters and an immediate pause switch.", "author": "zj1022", "version": "1.0.5", "compatibleClientVersions": ["0.5.1-beta"], "kind": "feature", "type": "script", "path": "mods/petloot", "depends": ["Game", "Cosmetics"], "settings": true },
- { "id": "pob", "name": "POB", "description": "Preview and import a character build through a configured external PoB converter.", "author": "nikolos89", "version": "1.0.2", "compatibleClientVersions": ["0.4.3-beta", "0.5.0-beta", "0.5.1-beta"], "kind": "feature", "type": "project", "path": "mods/pob", "depends": [], "settings": true },
+ { "id": "pob", "name": "POB", "description": "Preview and import a character build through a configured external PoB converter.", "author": "nikolos89", "version": "1.0.3", "compatibleClientVersions": ["0.5.1-beta"], "kind": "feature", "type": "project", "path": "mods/pob", "depends": [], "settings": true },
{ "id": "waypoint-tools", "name": "Waypoint Tools", "description": "Lets Waypoint's tools reach the game without the client control bridge: the item crafter gives its items through it.", "author": "Waypoint", "version": "1.0.3", "compatibleClientVersions": ["0.4.3-beta", "0.5.0-beta", "0.5.1-beta"], "kind": "feature", "type": "project", "path": "mods/waypoint-tools", "depends": ["Game"], "settings": false },
{ "id": "zoom", "name": "Zoom", "description": "A wider view in normal play: the camera stands further back, and /zoom sets how far.", "author": "evrydayjunglist", "version": "1.0.0", "compatibleClientVersions": ["0.5.1-beta"], "kind": "feature", "type": "project", "path": "mods/zoom", "depends": ["Game"], "settings": true }
]
diff --git a/mods/pob/Converter/Directory.Build.props b/mods/pob/Converter/Directory.Build.props
new file mode 100644
index 0000000..03ad84a
--- /dev/null
+++ b/mods/pob/Converter/Directory.Build.props
@@ -0,0 +1,11 @@
+
+
+ net10.0
+ enable
+ enable
+ latest
+ $([MSBuild]::GetDirectoryNameOfFileAbove('$(MSBuildThisFileDirectory)', 'GameServer.slnx'))
+ $(MSBuildThisFileDirectory)..\..\..\..\LocalExile\
+ $([MSBuild]::EnsureTrailingSlash('$(LocalExileRoot)'))
+
+
diff --git a/mods/pob/Converter/LICENSE b/mods/pob/Converter/LICENSE
new file mode 100644
index 0000000..d159169
--- /dev/null
+++ b/mods/pob/Converter/LICENSE
@@ -0,0 +1,339 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, write to the Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ , 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/mods/pob/Converter/NOTICE.txt b/mods/pob/Converter/NOTICE.txt
new file mode 100644
index 0000000..ef9a932
--- /dev/null
+++ b/mods/pob/Converter/NOTICE.txt
@@ -0,0 +1,18 @@
+The bounded PoB parser, item conversion, passive validation and native table readers were adapted from
+LocalExile feature/pob-import commit 5394de0a5208bb2407491cf986fab5455714bdc8:
+https://github.com/evrydayjunglist/evryPath/tree/5394de0a5208bb2407491cf986fab5455714bdc8
+The tattoo catalogue, target-set and limit rules (PathOfBuildingTattoos.cs) were adapted from LocalExile main
+commit ec522f1876690c0b203636bf78b508f308365163:
+https://github.com/LocalExile/LocalExile/tree/ec522f1876690c0b203636bf78b508f308365163
+
+This standalone converter is supplied as source with the POB mod. It prepares builds using the server's extracted
+tables and read-only catalogue; the Gateway owns the final save transaction. No Path of Building executable,
+game tables, client files or .NET runtime are distributed in this source folder.
+
+Microsoft.Data.Sqlite and its SQLite native dependencies retain their upstream license notices in operator-built output.
+.NET and Microsoft.Data.Sqlite: Copyright Microsoft Corporation and contributors, MIT.
+SQLitePCLRaw: Copyright SourceGear, LLC, Apache License 2.0.
+Native SQLite is in the public domain: https://www.sqlite.org/copyright.html
+
+Converter sources adapted from LocalExile retain its GNU GPL version 2 license (LICENSE).
+The Apache-licensed mod front end communicates with the separate converter over JSON stdin/stdout.
diff --git a/mods/pob/Converter/PobImport.csproj b/mods/pob/Converter/PobImport.csproj
new file mode 100644
index 0000000..53cf9b6
--- /dev/null
+++ b/mods/pob/Converter/PobImport.csproj
@@ -0,0 +1,16 @@
+
+
+ Exe
+ PobImport
+ true
+ $(NoWarn);CS8618;CS8632
+
+
+
+
+
+
+
+
+
+
diff --git a/mods/pob/Converter/Source/IndexedMods.cs b/mods/pob/Converter/Source/IndexedMods.cs
new file mode 100644
index 0000000..e31a8d1
--- /dev/null
+++ b/mods/pob/Converter/Source/IndexedMods.cs
@@ -0,0 +1,101 @@
+using System.Globalization;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using GameServer.Core.Protocol.Instance;
+
+// 3.29.3b FUN_1424c6020 cases 0x27/0x28/0x3a resolve the numeric stat through the
+// Index column of these tables, not a zero-based row number or a displayed numeric roll.
+static class IndexedMods
+{
+ // PoB combines identical stat lines: two tattoos expose one "-2" line, while each
+ // native modifier still carries its own -1 and companion stat. Expand only a complete
+ // set of native tattoo companions; never reinterpret a lone penalty or a Heist enchant.
+ public static (IReadOnlyList Lines, int[] Source) ExpandSockets(
+ IReadOnlyList lines, IReadOnlyDictionary entries)
+ {
+ var expanded = new List();
+ var source = new List();
+ for (int i = 0; i < lines.Count; i++)
+ {
+ var line = lines[i];
+ var match = Match(line.Text, @"^-(?[2-3]) to maximum Sockets$");
+ int copies = 1;
+ if (match.Success)
+ {
+ int count = Number(match, "count");
+ int companions = lines.Count(other => other.Section == line.Section && entries.Any(e =>
+ e.Key.StartsWith("DeepwaterTattooEnchant", StringComparison.Ordinal)
+ && e.Value.Length == 2 && e.Value.Contains("-1 to maximum Sockets")
+ && e.Value.Any(text => text != "-1 to maximum Sockets" && string.Equals(text, other.Text, StringComparison.OrdinalIgnoreCase))));
+ if (companions == count) copies = count;
+ }
+ for (int n = 0; n < copies; n++)
+ {
+ expanded.Add(copies > 1 ? line with { Text = "-1 to maximum Sockets" } : line);
+ source.Add(i);
+ }
+ }
+ return (expanded, source.ToArray());
+ }
+
+ static readonly Lazy> Skills = new(() => Names("IndexableSkillGems", "Name1"));
+ static readonly Lazy> Supports = new(() => Names("IndexableSupportGems", "Name"));
+ static readonly Lazy> NonActive = new(() => Names("IndexableNonActiveSupportGems", "Name"));
+
+ static Dictionary Names(string table, string field)
+ {
+ using var doc = NativeData.Read($"data/tables/{table}.json");
+ return doc.RootElement.EnumerateArray().GroupBy(r => r.GetProperty(field).GetString()!, StringComparer.OrdinalIgnoreCase)
+ .ToDictionary(g => g.Key, g => g.First().GetProperty("Index").GetInt32(), StringComparer.OrdinalIgnoreCase);
+ }
+
+ static Match Match(string line, string pattern) => Regex.Match(line, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
+ static int Number(Match m, string group) => int.Parse(m.Groups[group].Value, CultureInfo.InvariantCulture);
+
+ public static IReadOnlyList Resolve(IReadOnlyList lines, Item item, ModCatalog mods)
+ {
+ var result = new List();
+ var used = new HashSet();
+ for (int i = 0; i < lines.Count; i++)
+ {
+ var line = lines[i];
+ if (item.Rarity != ItemRarity.Unique || line.Section != ModSection.Explicit) continue;
+ string? id = null;
+ Dictionary? values = null;
+ var skill = Match(line.Text, @"^(?[+-]\d+) to Level of all (?.+) Gems$");
+ var pearl = Match(line.Text, @"^Skills Socketed in your (?Helmet|Gloves|Boots) are Supported by level (?\d+) (?.+)$");
+ var tree = Match(line.Text, @"^Skills granted by your Passive Tree are Supported by level (?\d+) (?.+)$");
+ var support = Match(line.Text, @"^Socketed Gems are Supported by Level (?\d+) (?.+)$");
+ if (skill.Success && Skills.Value.TryGetValue(skill.Groups["name"].Value, out int skillIndex))
+ {
+ id = "RandomSkillUnique__1";
+ values = new() { ["random_skill_gem_level_+_level"] = Number(skill, "level"), ["random_skill_gem_level_+_index"] = skillIndex };
+ }
+ else if ((pearl.Success || tree.Success) && NonActive.Value.TryGetValue((pearl.Success ? pearl : tree).Groups["name"].Value, out int pearlIndex))
+ {
+ var match = pearl.Success ? pearl : tree;
+ int slot = !pearl.Success ? 4 : pearl.Groups["slot"].Value.ToLowerInvariant() switch { "helmet" => 1, "gloves" => 2, _ => 3 };
+ int n = used.Contains("UniquePearlSupportOne") ? 2 : 1;
+ id = n == 1 ? "UniquePearlSupportOne" : "UniquePearlSupportTwo";
+ values = new() { [$"local_pearl_random_support_gem_{n}_slot_index"] = slot,
+ [$"local_pearl_random_support_gem_{n}_index"] = pearlIndex, [$"local_pearl_random_support_gem_{n}_level"] = Number(match, "level") };
+ }
+ else if (support.Success && Supports.Value.TryGetValue(support.Groups["name"].Value, out int supportIndex))
+ {
+ int level = Number(support, "level");
+ bool high = level >= 25;
+ id = high ? "RandomSupportUnique__2" : "RandomSupportUnique__1";
+ string suffix = high ? "_1" : "";
+ values = new() { [$"local_random_support_gem_index{suffix}"] = supportIndex, [$"local_random_support_gem_level{suffix}"] = level };
+ }
+ if (id is null || values is null || used.Contains(id) || mods.ById(id) is not { } mod
+ || mod.Stats.Any(s => !values.ContainsKey(s.Id))) continue;
+ // Out-of-roll levels can be retained, but an index must always name an actual native entry.
+ int[] native = [.. mod.Stats.Select(s => values[s.Id])];
+ bool outside = mod.Stats.Where((s, n) => native[n] < Math.Min(s.Min, s.Max) || native[n] > Math.Max(s.Min, s.Max)).Any();
+ used.Add(id);
+ result.Add(new(new(line.Section, mod.Hash, native), [i], outside));
+ }
+ return result;
+ }
+}
diff --git a/mods/pob/Converter/Source/ItemCatalog.cs b/mods/pob/Converter/Source/ItemCatalog.cs
new file mode 100644
index 0000000..bf6ca8a
--- /dev/null
+++ b/mods/pob/Converter/Source/ItemCatalog.cs
@@ -0,0 +1,290 @@
+using System.Text.Json;
+using GameServer.Core.Protocol.Instance;
+sealed class ItemCatalog
+{
+ readonly Lazy<(List Rows, string? Error)> rows;
+ readonly Lazy> gems;
+ readonly Lazy> defences;
+ public ModCatalog Mods { get; }
+ public ItemCatalog(string folder)
+ {
+ Mods = new(folder); rows = new(() => Load(folder, Mods));
+ gems = new(() => LoadGems(folder, false)); defences = new(() => LoadDefences(folder));
+ }
+ public string? Error => rows.Value.Error;
+ public IReadOnlyList All => rows.Value.Rows;
+ public GemType? Gem(BaseType type) => gems.Value.GetValueOrDefault(type.Row);
+ public BaseDefences? Defences(BaseType type) => defences.Value.TryGetValue(type.Row, out var value) ? value : null;
+ public IEnumerable GemEffects(Item gem)
+ {
+ byHash ??= All.GroupBy(t => t.Hash).ToDictionary(g => g.Key, g => g.First());
+ var type = byHash.GetValueOrDefault(gem.TypeHash);
+ if (type is null || Gem(type) is not { IsSupport: false } g) yield break;
+ var v = g.Variant(gem.GemVariant);
+ if (NativeActiveEffects.Contains(v.Effect)) yield return v.Effect;
+ if (NativeActiveEffects.Contains(v.Effect2)) yield return v.Effect2;
+ }
+ Dictionary? byHash;
+ public static Item Create(BaseType type, IReadOnlyList? sockets = null, IReadOnlyList? links = null, byte? defenceBaseRoll = null) =>
+ new(type.Hash, type.Components, type.VisualIdentity) { Charges = type.MaxCharges, Sockets = sockets ?? [], Links = links,
+ DefenceBaseRoll = defenceBaseRoll ?? 0, Mods = [] };
+ public sealed record BaseType(int Row, string Id, string Name, uint Hash, byte Width, byte Height, ushort VisualIdentity,
+ IReadOnlyList Components, int MaxCharges, string Class = "", byte Stance = 0xff, int DropLevel = 0, ushort MaxStack = 1,
+ int FullStackRow = -1, IReadOnlyList? Implicits = null)
+ {
+ /// Tags.dat Ids for mod spawn weights: the .it chain's Base tags (item-types.json) and the row's TagsKeys.
+ public IReadOnlySet Tags { get; init; } = new HashSet();
+
+ /// BaseItemTypes ModDomain: the Mods.dat Domain its affixes come from (1 items, 2 flasks, …).
+ public int ModDomain { get; init; } = 1;
+
+ /// Its ItemClasses row (-1 unknown): the worn item's weapon type the client checks skills against is this
+ /// row + 1 (11-skills.md "Weapon restrictions").
+ public int ClassRow { get; init; } = -1;
+
+ public bool Supported => Components.Count > 0 && Item.CanSerialize(Components);
+ /// Several of the type share one cell (a Stack component and a CurrencyItems StackSize above 1).
+ public bool Stackable => MaxStack > 1;
+ /// A full stack becomes one of this BaseItemTypes row (CurrencyItems FullStack_BaseItemTypesKey: 5 Scroll
+ /// Fragments → a Scroll of Wisdom, 20 shards → their orb), or -1.
+ public bool BecomesWhenFull => FullStackRow >= 0;
+ public override string ToString() => $"{Name} ({Id}, row {Row})";
+ }
+
+ public sealed record GemVariant(int Index, string Name, int Effect, int Effect2, bool Creatable)
+ {
+ /// Stable GemEffects.dat Id used by build export tools (it can differ from GrantedEffects Id).
+ public string Id { get; init; } = "";
+ }
+
+ /// A gem type (a SkillGems row): its variants (the first is the normal gem) and its experience thresholds,
+ /// ItemExperiencePerLevel's Experience for levels 1, 2, … of its experience type; the last level is the cap.
+ public sealed record GemType(int Row, bool IsSupport, IReadOnlyList Variants, IReadOnlyList Thresholds)
+ {
+ /// SkillGems GemColour: 1 red (strength), 2 green (dexterity), 3 blue (intelligence), 4 white.
+ public int Colour { get; init; }
+
+ /// A Vaal gem's own row (IsVaalVariant) or an awakened one (RegularVariant set).
+ public bool IsVaalOrAwakened { get; init; }
+
+ /// Vaal gems are intrinsically corrupted, independently of their level and quality.
+ public bool IsVaal { get; init; }
+
+ /// SkillGems MtxSlotTypes: the MicrotransactionSkillGemEffectSlotTypes rows its Cosmetics tab skill slots
+ /// take (0 the skill's effect, 1 a totem skin).
+ public IReadOnlyList MtxSlotTypes { get; init; } = [];
+
+ /// SkillGems StrengthRequirementPercent: the strength share of the gem's attribute requirement
+ /// (SkillCatalog.GemAttributeRequirement), 0 for a pure dexterity or intelligence gem.
+ public int StrengthPercent { get; init; }
+
+ /// SkillGems DexterityRequirementPercent ().
+ public int DexterityPercent { get; init; }
+
+ /// SkillGems IntelligenceRequirementPercent ().
+ public int IntelligencePercent { get; init; }
+
+ public int MaxLevel => Thresholds.Count;
+
+ /// The level as the client derives it (0x14246f900): the levels whose threshold the experience reaches, up
+ /// to the cap. Experience -1 is the cap + 1 (0x14246eb00; a guess: the corrupted gems over their cap).
+ public int Level(int experience) => experience == -1 ? MaxLevel + 1 : Thresholds.Count(t => t <= experience);
+
+ /// The experience a gem of this level starts with (the level clamped to 1 … the cap).
+ public int ExperienceFor(int level) => Thresholds.Count == 0 ? 0 : Thresholds[Math.Clamp(level, 1, MaxLevel) - 1];
+
+ /// The variant the client uses: an index outside the list is the normal gem (0x14246fa50 resets it).
+ public GemVariant Variant(int index) => index > 0 && index < Variants.Count ? Variants[index] : Variants[0];
+ }
+
+ public readonly record struct BaseDefences(int ArmourMin, int ArmourMax, int EvasionMin, int EvasionMax,
+ int EnergyShieldMin = 0, int EnergyShieldMax = 0, int WardMin = 0, int WardMax = 0)
+ {
+ /// Resolve the saved native roll before local modifiers; wire 32 selects the minimum base.
+ public (int Armour, int Evasion, int EnergyShield) AtRoll(byte roll)
+ {
+ if (roll > Item.SpecialDefenceBaseRoll)
+ throw new ArgumentOutOfRangeException(nameof(roll), roll, "Defence base roll must be 0..32.");
+ int effective = roll == Item.SpecialDefenceBaseRoll ? 0 : roll;
+ int At(int minimum, int maximum) =>
+ (int)(minimum + (((long)maximum - minimum) * effective + 15) / Item.MaximumDefenceBaseRoll);
+ return (At(ArmourMin, ArmourMax), At(EvasionMin, EvasionMax), At(EnergyShieldMin, EnergyShieldMax));
+ }
+ }
+
+ private static Dictionary LoadDefences(string folder)
+ {
+ string path = Path.Combine(folder, "tables", "ArmourTypes.json");
+ var result = new Dictionary();
+ if (!NativeData.Exists(path)) return result;
+ using var d = NativeData.Read(path);
+ foreach (var r in d.RootElement.EnumerateArray())
+ {
+ if (r.GetProperty("BaseItemTypesKey") is not { ValueKind: JsonValueKind.Number } key) continue;
+ result[(int)Math.Max(0, key.GetInt32())] = new BaseDefences(
+ r.GetProperty("ArmourMin").GetInt32(), r.GetProperty("ArmourMax").GetInt32(),
+ r.GetProperty("EvasionMin").GetInt32(), r.GetProperty("EvasionMax").GetInt32(),
+ r.TryGetProperty("EnergyShieldMin", out var esMin) ? esMin.GetInt32() : 0,
+ r.TryGetProperty("EnergyShieldMax", out var esMax) ? esMax.GetInt32() : 0,
+ r.TryGetProperty("WardMin", out var wardMin) ? wardMin.GetInt32() : 0,
+ r.TryGetProperty("WardMax", out var wardMax) ? wardMax.GetInt32() : 0);
+ }
+ return result;
+ }
+ private static Dictionary LoadGems(string folder, bool ruthless)
+ {
+ string Table(string n) => Path.Combine(folder, "tables", n + ".json");
+ var result = new Dictionary();
+ string[] needed = ["SkillGems", "GemEffects", "BaseItemTypes", "ItemExperiencePerLevel", "ItemExperienceTypes"];
+ if (needed.Any(n => !NativeData.Exists(Table(n)))) return result;
+ using var g = NativeData.Read(Table("SkillGems"));
+ using var e = NativeData.Read(Table("GemEffects"));
+ using var b = NativeData.Read(Table("BaseItemTypes"));
+ using var x = NativeData.Read(Table("ItemExperiencePerLevel"));
+ using var xt = NativeData.Read(Table("ItemExperienceTypes"));
+ static int Row(JsonElement r, string name) => r.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number ? v.GetInt32() : -1;
+ // Null or absent means no alternate; row zero remains a real effect, and must not be treated as missing.
+ int Effect(JsonElement r, string name) => ruthless && Row(r, name + "Hardmode") is int alternate and >= 0
+ ? alternate : Row(r, name);
+ var thresholds = x.RootElement.EnumerateArray().GroupBy(r => Row(r, "ItemExperienceType")).ToDictionary(t => t.Key,
+ t => (IReadOnlyList)[.. t.OrderBy(r => Row(r, "ItemCurrentLevel")).Select(r => Row(r, "Experience"))]);
+ var effects = e.RootElement;
+ string Name(int row) => effects[row].GetProperty("Name").GetString() ?? "";
+ static IEnumerable<(int Row, int Index)> Variants(JsonElement r) =>
+ r.GetProperty("GemVariants").EnumerateArray().Select((v, i) => (v.GetInt32(), i));
+ // A regular skill's GrantedEffects row → its variant's name, for the Vaal variants that grant it as their base.
+ var regular = new Dictionary();
+ var rows = new List<(int BaseRow, JsonElement Row, string BaseName)>();
+ foreach (var r in g.RootElement.EnumerateArray())
+ {
+ int baseRow = Row(r, "BaseItemTypesKey");
+ if (baseRow < 0) continue;
+ string baseName = b.RootElement[baseRow].GetProperty("Name").GetString() ?? "";
+ rows.Add((baseRow, r, baseName));
+ if (r.GetProperty("IsVaalVariant").GetBoolean() || baseName.StartsWith('[')) continue;
+ foreach (var (v, i) in Variants(r))
+ if (Effect(effects[v], "GrantedEffect") is int ge and >= 0 && !Name(v).StartsWith("[DNT]"))
+ regular.TryAdd(ge, i == 0 ? baseName : Name(v));
+ }
+ foreach (var (baseRow, r, baseName) in rows)
+ {
+ bool vaal = r.GetProperty("IsVaalVariant").GetBoolean();
+ int expType = Row(r, "ItemExperienceType");
+ bool awakened = Row(r, "RegularVariant") >= 0
+ && (expType < 0 || xt.RootElement[expType].GetProperty("Id").GetString() != "GemProgressionExceptionalPlus");
+ bool rowCreatable = !baseName.StartsWith('[') && !baseName.StartsWith("WIP");
+ var variants = new List();
+ foreach (var (v, i) in Variants(r))
+ {
+ int effect = Effect(effects[v], "GrantedEffect"), effect2 = Effect(effects[v], "GrantedEffect2");
+ string name = i == 0 ? baseName : Name(v);
+ bool creatable = rowCreatable && !name.StartsWith("[DNT]");
+ if (vaal && effect2 >= 0)
+ {
+ creatable &= regular.TryGetValue(effect2, out var baseSkill);
+ if (i > 0 && baseSkill is not null) name = "Vaal " + baseSkill;
+ }
+ variants.Add(new GemVariant(i, name, effect, effect2, creatable)
+ { Id = effects[v].TryGetProperty("Id", out var variantId) ? variantId.GetString() ?? "" : "" });
+ }
+ result.TryAdd(baseRow, new GemType(baseRow, r.GetProperty("IsSupport").GetBoolean(), variants,
+ thresholds.GetValueOrDefault(expType) ?? [])
+ {
+ Colour = Row(r, "GemColour"), IsVaal = vaal, IsVaalOrAwakened = vaal || Row(r, "RegularVariant") >= 0,
+ MtxSlotTypes = r.TryGetProperty("MtxSlotTypes", out var st) ? [.. st.EnumerateArray().Select(t => t.GetInt32())] : [],
+ StrengthPercent = Row(r, "StrengthRequirementPercent"), DexterityPercent = Row(r, "DexterityRequirementPercent"),
+ IntelligencePercent = Row(r, "IntelligenceRequirementPercent"),
+ });
+ }
+ return result;
+ }
+ private static (List, string?) Load(string folder, ModCatalog mods)
+ {
+ string bases = Path.Combine(folder, "tables", "BaseItemTypes.json"), visuals = Path.Combine(folder, "tables", "ItemVisualIdentity.json");
+ if (!NativeData.Exists(bases) || !NativeData.Exists(visuals)) return ([], $"{bases} is missing: extract the game tables (Tools/PoEDataExtractor)");
+ var components = new Dictionary>();
+ var itemTags = new Dictionary>();
+ string types = Path.Combine(folder, "item-types.json");
+ if (!NativeData.Exists(types)) return ([], $"{types} is missing: run scripts/dev/extract-data.ps1");
+ using (var doc = NativeData.Read(types))
+ foreach (var t in doc.RootElement.GetProperty("types").EnumerateArray())
+ {
+ components[t.GetProperty("type").GetString()!] =
+ [.. t.GetProperty("components").EnumerateArray().Take(t.GetProperty("read").GetInt32()).Select(c => c.GetString()!)];
+ // "tags" since 2026-10-20; older files have none (regenerate with ot_components.py --items).
+ if (t.TryGetProperty("tags", out var tg)) itemTags[t.GetProperty("type").GetString()!] = [.. tg.EnumerateArray().Select(x => x.GetString()!)];
+ }
+ List visualHashes;
+ using (var doc = NativeData.Read(visuals))
+ visualHashes = [.. doc.RootElement.EnumerateArray().Select(r => (ushort)r.GetProperty("HASH16").GetInt32())];
+ var charges = new Dictionary();
+ string chargesPath = Path.Combine(folder, "tables", "ComponentCharges.json");
+ if (NativeData.Exists(chargesPath))
+ {
+ using var doc = NativeData.Read(chargesPath);
+ foreach (var r in doc.RootElement.EnumerateArray())
+ charges[r.GetProperty("BaseItemTypesKey").GetString() ?? ""] = r.GetProperty("MaxCharges").GetInt32();
+ }
+ // CurrencyItems StackSize by BaseItemTypes row (Orb of Transmutation 40, Scroll of Wisdom 40, Portal Scroll 40 …);
+ // only types with a Stack component stack.
+ var stackSizes = new Dictionary();
+ var fullStacks = new Dictionary();
+ string currencyPath = Path.Combine(folder, "tables", "CurrencyItems.json");
+ if (NativeData.Exists(currencyPath))
+ {
+ using var doc = NativeData.Read(currencyPath);
+ foreach (var r in doc.RootElement.EnumerateArray())
+ if (r.GetProperty("BaseItemTypesKey") is { ValueKind: JsonValueKind.Number } b && r.GetProperty("StackSize").GetInt32() is > 1 and var size)
+ {
+ stackSizes.TryAdd(b.GetInt32(), (ushort)Math.Min(size, ushort.MaxValue));
+ if (r.GetProperty("FullStack_BaseItemTypesKey") is { ValueKind: JsonValueKind.Number } full) fullStacks.TryAdd(b.GetInt32(), full.GetInt32());
+ }
+ }
+ var classes = new List();
+ var stances = new List();
+ string classesPath = Path.Combine(folder, "tables", "ItemClasses.json");
+ if (NativeData.Exists(classesPath))
+ {
+ using var doc = NativeData.Read(classesPath);
+ classes = [.. doc.RootElement.EnumerateArray().Select(r => r.GetProperty("Id").GetString() ?? "")];
+ stances = [.. doc.RootElement.EnumerateArray().Select(r => r.GetProperty("ItemStance") is { ValueKind: JsonValueKind.Number } s ? (byte)s.GetInt32() : (byte)0xff)];
+ }
+ List tagIds = [];
+ string tagsPath = Path.Combine(folder, "tables", "Tags.json");
+ if (NativeData.Exists(tagsPath))
+ {
+ using var doc = NativeData.Read(tagsPath);
+ tagIds = [.. doc.RootElement.EnumerateArray().Select(r => r.GetProperty("Id").GetString() ?? "")];
+ }
+ var rows = new List();
+ using (var doc = NativeData.Read(bases))
+ {
+ foreach (var r in doc.RootElement.EnumerateArray())
+ {
+ string id = r.GetProperty("Id").GetString() ?? "";
+ var itemComponents = components.GetValueOrDefault(id) ?? [];
+ int visual = r.GetProperty("ItemVisualIdentity").GetInt32();
+ rows.Add(new BaseType(rows.Count, id, r.GetProperty("Name").GetString() ?? "", r.GetProperty("HASH32").GetUInt32(),
+ (byte)r.GetProperty("Width").GetInt32(), (byte)r.GetProperty("Height").GetInt32(),
+ visual >= 0 && visual < visualHashes.Count ? visualHashes[visual] : (ushort)0,
+ itemComponents, charges.GetValueOrDefault(id),
+ r.GetProperty("ItemClassesKey") is { ValueKind: JsonValueKind.Number } c && c.GetInt32() < classes.Count ? classes[c.GetInt32()] : "",
+ // the row's own ItemStance, else its class's (ItemStances: Wand = 2)
+ r.GetProperty("ItemStance") is { ValueKind: JsonValueKind.Number } st ? (byte)st.GetInt32()
+ : r.GetProperty("ItemClassesKey") is { ValueKind: JsonValueKind.Number } c2 && c2.GetInt32() < stances.Count ? stances[c2.GetInt32()] : (byte)0xff,
+ r.GetProperty("DropLevel").GetInt32(),
+ itemComponents.Contains("Stack") ? stackSizes.GetValueOrDefault(rows.Count, (ushort)1) : (ushort)1,
+ fullStacks.GetValueOrDefault(rows.Count, -1),
+ // Implicit_ModsKeys: Mods.dat rows every item of the type has (Driftwood Wand: 8-12% increased Spell Damage)
+ [.. r.GetProperty("Implicit_ModsKeys").EnumerateArray().Select(k => mods.Row(k.GetInt32())).OfType()])
+ {
+ Tags = new HashSet([.. itemTags.GetValueOrDefault(id) ?? [],
+ .. r.GetProperty("TagsKeys").EnumerateArray().Select(k => k.GetInt32()).Where(k => k < tagIds.Count).Select(k => tagIds[k])]),
+ ModDomain = r.GetProperty("ModDomain").GetInt32(),
+ ClassRow = r.GetProperty("ItemClassesKey") is { ValueKind: JsonValueKind.Number } cr ? cr.GetInt32() : -1,
+ });
+ }
+ }
+ return (rows, null);
+ }
+}
diff --git a/mods/pob/Converter/Source/ItemDefences.cs b/mods/pob/Converter/Source/ItemDefences.cs
new file mode 100644
index 0000000..c681f3c
--- /dev/null
+++ b/mods/pob/Converter/Source/ItemDefences.cs
@@ -0,0 +1,55 @@
+// Adapted from LocalExile feature/pob-import, 5394de0a. See NOTICE.md.
+using GameServer.Core.Protocol.Instance;
+
+/// The native item-tooltip defences, before character-wide modifiers and slot conversions.
+static class ItemDefences
+{
+ public static (int Armour, int Evasion, int EnergyShield) Calculate(Item item, ItemCatalog.BaseDefences defences,
+ ModCatalog mods, byte? baseRoll = null) =>
+ CalculateLocal(defences.AtRoll(baseRoll ?? item.DefenceBaseRoll), ItemModStats.Local(item, mods), item.Quality);
+
+ public static int Ward(Item item, ItemCatalog.BaseDefences defences, ModCatalog mods, byte? baseRoll = null)
+ {
+ int roll = baseRoll ?? item.DefenceBaseRoll;
+ if (roll > Item.SpecialDefenceBaseRoll) throw new ArgumentOutOfRangeException(nameof(baseRoll));
+ if (roll == Item.SpecialDefenceBaseRoll) roll = 0;
+ long basis = defences.WardMin + (((long)defences.WardMax - defences.WardMin) * roll + 15) / 31;
+ var local = ItemModStats.Local(item, mods);
+ long quality = local.GetValueOrDefault("local_quality_does_not_increase_defences") != 0 ? 0
+ : Math.Max(0L, (long)item.Quality + local.GetValueOrDefault("local_item_quality_+"));
+ float factor = Math.Max(0f, 1f + local.GetValueOrDefault("local_ward_+%") * 0.01f) * (1f + quality * 0.01f);
+ float value = Math.Max(0L, basis + local.GetValueOrDefault("local_ward")) * factor + 0.5f;
+ return value >= int.MaxValue ? int.MaxValue : (int)value;
+ }
+
+ /// Local defences from an already resolved modifier map, using the minimum base roll.
+ public static (int Armour, int Evasion, int EnergyShield) Of(
+ ItemCatalog.BaseDefences baseDefences, IReadOnlyDictionary local, int quality) =>
+ CalculateLocal(baseDefences.AtRoll(0), local, quality);
+
+ static (int Armour, int Evasion, int EnergyShield) CalculateLocal(
+ (int Armour, int Evasion, int EnergyShield) basis, IReadOnlyDictionary local, int itemQuality)
+ {
+ long Get(string name) => local.GetValueOrDefault(name);
+ long quality = Get("local_quality_does_not_increase_defences") != 0 ? 0
+ : Math.Max(0L, (long)itemQuality + Get("local_item_quality_+"));
+ int Rating(int basis, long added, long increased)
+ {
+ float factor = Math.Max(0f, 1f + increased * 0.01f) * (1f + quality * 0.01f);
+ float value = Math.Max(0L, basis + added) * factor + 0.5f;
+ return value >= int.MaxValue ? int.MaxValue : (int)value;
+ }
+ long shared = Get("local_armour_and_evasion_+%") + Get("local_armour_and_evasion_and_energy_shield_+%");
+ int armour = Rating(basis.Armour, Get("local_base_physical_damage_reduction_rating"),
+ Get("local_physical_damage_reduction_rating_+%") + Get("local_armour_and_energy_shield_+%") + shared);
+ int evasion = Rating(basis.Evasion, Get("local_base_evasion_rating") + Get("local_evasion_rating_and_energy_shield"),
+ Get("local_evasion_rating_+%") + Get("local_evasion_and_energy_shield_+%") + shared);
+ // Native 3.29.3b ES getter 0x1424af430: either prohibition wins over base, flat mods, increases and quality.
+ int energyShield = Get("local_no_energy_shield") != 0
+ || Get("local_unique_tabula_rasa_no_requirement_or_energy_shield") != 0 ? 0
+ : Rating(basis.EnergyShield, Get("local_energy_shield") + Get("local_evasion_rating_and_energy_shield"),
+ Get("local_energy_shield_+%") + Get("local_armour_and_energy_shield_+%")
+ + Get("local_evasion_and_energy_shield_+%") + Get("local_armour_and_evasion_and_energy_shield_+%"));
+ return (armour, evasion, energyShield);
+ }
+}
diff --git a/mods/pob/Converter/Source/ItemSend.cs b/mods/pob/Converter/Source/ItemSend.cs
new file mode 100644
index 0000000..89890aa
--- /dev/null
+++ b/mods/pob/Converter/Source/ItemSend.cs
@@ -0,0 +1,56 @@
+using System.Text.Json;
+using GameServer.Core.Protocol.Instance;
+using Microsoft.Data.Sqlite;
+
+// Native unique catalogue resolution only; the Gateway owns character changes.
+static class ItemSend
+{
+ internal sealed record UniqueDefinition(string Name, string BaseTypeId, string[] Mods, byte ItemLevel = 86, bool Corrupted = false);
+
+ // The server's catalogue row: PoB's text cannot name most unique modifiers, this row does. Older databases have no such table.
+ internal static UniqueDefinition? Definition(SqliteConnection connection, string title, ItemCatalog.BaseType type, Item item)
+ {
+ if (item.Rarity != ItemRarity.Unique || item.FracturedCount > 0) return null;
+ using var c = connection.CreateCommand();
+ c.CommandText = "SELECT 1 FROM sqlite_master WHERE type='table' AND name='catalog_entries'";
+ if (c.ExecuteScalar() is null) return null;
+ c.CommandText = "SELECT payload FROM catalog_entries WHERE kind='unique_item' AND key=$key AND enabled=1";
+ // A Foulborn unique is its ordinary unique with mutated modifiers, which stay as parsed.
+ const string foulborn = "Foulborn ";
+ c.Parameters.AddWithValue("$key", $"{(title.StartsWith(foulborn, StringComparison.Ordinal) ? title[foulborn.Length..] : title)}|{type.Id}");
+ return c.ExecuteScalar() is string payload ? JsonSerializer.Deserialize(payload) : null;
+ }
+
+ /// Catalogue completion retains exported rolls; only missing fixed-value native stats can be inferred.
+ internal static Item Completed(Item item, ItemCatalog.BaseType type, UniqueDefinition unique, ModCatalog mods, List warnings)
+ {
+ HashSet Stats(ModCatalog.Mod mod) => [.. mod.Stats.Select(s => s.Id)];
+ var parsed = item.Mods.ToList();
+ ItemMod Resolve(ModCatalog.Mod mod, ModSection section)
+ {
+ var match = parsed.FirstOrDefault(m => mods.ByHash(m.Hash) is { } native && Stats(native).SetEquals(Stats(mod)));
+ if (match is null)
+ {
+ if (mod.Stats.Any(s => s.Min != s.Max))
+ throw new ArgumentException($"{type.Name}: the export omits the original roll of '{mod.Id}'.");
+ return new(section, mod.Hash, [.. mod.Stats.Select(s => s.Max)]);
+ }
+ parsed.Remove(match);
+ var values = mods.ByHash(match.Hash)!.Stats.Select((s, i) => (s.Id, Value: match.Values[i])).ToDictionary(s => s.Id, s => s.Value);
+ return new(section, mod.Hash, [.. mod.Stats.Select(s => values[s.Id])]);
+ }
+ var implicits = (type.Implicits ?? []).Select(m => Resolve(m, ModSection.Implicit)).ToList();
+ var explicits = unique.Mods.Select(id => mods.ById(id)
+ ?? throw new ArgumentException($"Native unique modifier '{id}' is unavailable.")).Select(m => Resolve(m, ModSection.Explicit)).ToList();
+ int? requiredLevel = item.RequiredLevel;
+ var completed = item with
+ {
+ Mods = [.. implicits, .. explicits, .. parsed], Corrupted = item.Corrupted || unique.Corrupted,
+ ItemLevel = item.ItemLevel > 1 ? item.ItemLevel : unique.ItemLevel,
+ };
+ return completed with { RequiredLevel = requiredLevel };
+ }
+
+ internal static string Title(string text) => text.Replace("\r", "").Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
+ .SkipWhile(l => !l.StartsWith("Rarity:", StringComparison.Ordinal)).Skip(1).FirstOrDefault() ?? "";
+}
diff --git a/mods/pob/Converter/Source/Main.cs b/mods/pob/Converter/Source/Main.cs
new file mode 100644
index 0000000..03967d3
--- /dev/null
+++ b/mods/pob/Converter/Source/Main.cs
@@ -0,0 +1,568 @@
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Text.RegularExpressions;
+using GameServer.Core.Imports;
+using GameServer.Core.Protocol.Instance;
+using Microsoft.Data.Sqlite;
+
+namespace PobImport;
+
+static class Entry
+{
+ sealed record Input(string Code, string Name, string Database, string Data, string? SourceFile = null, bool AllowPartial = false, bool PrepareOnly = false, string? RecordJson = null);
+ static bool protocolV1;
+ static TextWriter resultOutput = Console.Out;
+ static readonly Dictionary Catalogs = new(StringComparer.OrdinalIgnoreCase);
+
+ // Inventories.dat rows the build replaces: equipment, flasks, the weapon swap and the tree's jewel pane.
+ static readonly byte[] Replaced = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14, 15, 102, PassiveJewels];
+ const byte PassiveJewels = 23;
+
+ public static int Main()
+ {
+ try
+ {
+ Console.OutputEncoding = System.Text.Encoding.UTF8;
+ resultOutput = Console.Out;
+ string raw = Console.In.ReadToEnd().TrimStart((char)0xFEFF, (char)0xEF, (char)0xBB, (char)0xBF);
+ using var request = JsonDocument.Parse(raw);
+ protocolV1 = request.RootElement.TryGetProperty("Version", out var version);
+ Input input;
+ if (protocolV1)
+ {
+ if (version.GetInt32() != 1) throw new InvalidDataException("Unsupported converter protocol version.");
+ var value = request.RootElement;
+ string data = Path.GetFullPath(value.GetProperty("Data").GetString()!);
+ // Protocol v1 receives character identity in Record; this read-only connection is for unique catalogue rows.
+ string database = Path.Combine(data, "world.db");
+ input = new(value.GetProperty("Code").GetString()!, value.GetProperty("Name").GetString()!, database, data,
+ value.TryGetProperty("SourceFile", out var source) && source.ValueKind == JsonValueKind.String ? source.GetString() : null,
+ PrepareOnly: true, RecordJson: value.GetProperty("Record").GetRawText());
+ // A v1 response is a single JSON document; human diagnostics stay out of the transport.
+ Console.SetOut(TextWriter.Null);
+ }
+ else input = JsonSerializer.Deserialize(raw, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
+ ?? throw new ArgumentException("empty input");
+ if (!input.PrepareOnly) throw new ArgumentException("The converter only prepares builds; the Gateway applies them.");
+ Run(input);
+ return 0;
+ }
+ catch (Exception e)
+ {
+ Console.Error.WriteLine("Error: " + e.Message);
+ return 1;
+ }
+ }
+
+ static void Run(Input input)
+ {
+ NativeData.Validate();
+ string data = Path.GetFullPath(input.Data), database = Path.GetFullPath(input.Database);
+ var warnings = new List();
+ var build = NativeSource.Parse(input.Code.Trim(), input.SourceFile);
+ // Superior is a display prefix; item quality is carried by its separate numeric property.
+ build = build with { Items = [.. build.Items.Select(i => i with { Text = Regex.Replace(i.Text, @"(?m)^Superior (?=\S)", "") })] };
+
+ NativeSource.Begin(input.Code.Trim(), build, input.SourceFile);
+ using var connection = new SqliteConnection(new SqliteConnectionStringBuilder
+ { DataSource = database, Mode = SqliteOpenMode.ReadOnly, Pooling = false, DefaultTimeout = 10 }.ToString());
+ connection.Open();
+ string name = input.Name.Trim();
+ var record = JsonNode.Parse(input.RecordJson ?? throw new ArgumentException("Missing character record"))!.AsObject();
+ var save = new JsonObject();
+
+ // Passives, masteries, tattoos and level (evryBuild), with the unique catalogue completing uniques.
+ var progress = PathOfBuildingCharacters.Prepare(build, data);
+ warnings.AddRange(progress.Warnings);
+ if (!Catalogs.TryGetValue(data, out var catalog)) Catalogs[data] = catalog = new ItemCatalog(data);
+ Item Finish(PathOfBuildingItem definition, ItemCatalog.BaseType type, Item item, List own) =>
+ !item.NativeMods && ItemSend.Definition(connection, ItemSend.Title(definition.Text), type, item) is { } unique
+ ? ItemSend.Completed(item, type, unique, catalog.Mods, own) : item;
+ // Abyss jewels sit in their host item's Abyss sockets: PoB lists them as " Abyssal Socket N" slots, which
+ // the converter refuses. Take them out here and put them into the host's Nth Abyss socket after it is built.
+ var abyssal = build.Slots.Where(x => x.ItemId != 0 && x.Name.Contains(" Abyssal Socket ")).ToList();
+ build = build with { Slots = [.. build.Slots.Where(x => !x.Name.Contains(" Abyssal Socket "))] };
+ var equipment = PathOfBuildingItems.Materialize(build, catalog, data, Finish);
+ warnings.AddRange(equipment.Warnings);
+ {
+ var hostRows = new Dictionary { ["Body Armour"] = 1, ["Weapon 1"] = 2, ["Weapon 2"] = 3, ["Helmet"] = 4, ["Amulet"] = 5,
+ ["Ring 1"] = 6, ["Ring 2"] = 7, ["Ring 3"] = 102, ["Gloves"] = 8, ["Boots"] = 9, ["Belt"] = 10, ["Weapon 1 Swap"] = 14, ["Weapon 2 Swap"] = 15 };
+ var byId = build.Items.ToDictionary(i => i.Id);
+ foreach (var slot in abyssal)
+ {
+ var m = Regex.Match(slot.Name, @"^(.+) Abyssal Socket (\d+)$");
+ if (!m.Success || !hostRows.TryGetValue(m.Groups[1].Value, out byte row) || !byId.TryGetValue(slot.ItemId, out var definition)) continue;
+ if (build.UseSecondWeaponSet) row = row switch { 2 => 14, 3 => 15, 14 => 2, 15 => 3, _ => row };
+ if (!equipment.Inventories.TryGetValue(row, out var list) || list.Count == 0)
+ { warnings.Add($"Пропущено ({slot.Name}): нет предмета-хозяина."); continue; }
+ try
+ {
+ var own = new List();
+ var (type, item) = PathOfBuildingItems.ParseItem(definition, catalog, data, own);
+ item = Finish(definition, type, item, own);
+ warnings.AddRange(own);
+ var host = list[0];
+ var sockets = host.Item.Sockets ?? [];
+ int nth = int.Parse(m.Groups[2].Value), seen = 0, at = -1;
+ for (int k = 0; k < sockets.Count; k++)
+ if (sockets[k].Colour == SocketColour.Abyss && ++seen == nth) { at = k; break; }
+ if (at < 0) { warnings.Add($"Пропущено ({slot.Name}): у предмета нет {nth}-го абисс-сокета."); continue; }
+ var changed = sockets.ToList();
+ changed[at] = changed[at] with { Gem = CharacterSaves.ToSaved(item, catalog.Mods) };
+ list[0] = host with { Item = host.Item with { Sockets = changed } };
+ }
+ catch (Exception e) { warnings.Add($"Пропущено ({slot.Name}): {e.Message}"); }
+ }
+ }
+ // Equipment: the same passive-naming lines (an amulet's anointment), matched to each slot's PoB item.
+ {
+ var rows = new Dictionary { ["Body Armour"] = 1, ["Weapon 1"] = 2, ["Weapon 2"] = 3, ["Helmet"] = 4, ["Amulet"] = 5,
+ ["Ring 1"] = 6, ["Ring 2"] = 7, ["Ring 3"] = 102, ["Gloves"] = 8, ["Boots"] = 9, ["Belt"] = 10, ["Weapon 1 Swap"] = 14, ["Weapon 2 Swap"] = 15 };
+ var texts = build.Items.ToDictionary(i => i.Id, i => i.Text);
+ foreach (var slot in build.Slots.Where(x => x.ItemId != 0 && texts.ContainsKey(x.ItemId)))
+ {
+ byte row; byte x0 = 0;
+ if (rows.TryGetValue(slot.Name, out byte r0)) row = build.UseSecondWeaponSet ? (byte)(r0 switch { 2 => 14, 3 => 15, 14 => 2, 15 => 3, _ => r0 }) : r0;
+ else if (Regex.Match(slot.Name, @"^Flask ([1-5])$") is { Success: true } f) { row = 11; x0 = (byte)(f.Groups[1].Value[0] - '1'); }
+ else continue;
+ if (!equipment.Inventories.TryGetValue(row, out var list)) continue;
+ for (int k = 0; k < list.Count; k++)
+ if (list[k].X == x0) list[k] = list[k] with { Item = PassiveHashMods(list[k].Item, texts[slot.ItemId], data) };
+ }
+ }
+
+ var tree = NativeData.Shared("passive-tree", () => new PassiveTree(data));
+ var cells = JewelCells.Load(data);
+
+ // Ascendancy: the selection by its Ascendancy.dat Id and every allocated ascendancy node except the free start.
+ JsonObject? ascendancy = null;
+ // Only the chosen ascendancy's own nodes (PassiveSkills.AscendancyKey), never its free start node: bloodline
+ // and other trees' nodes make the Gateway refuse the whole save (AscendancyRuleException).
+ var ascendancyRows = NativeData.Shared("ascendancy-rows", () =>
+ {
+ var rows = new Dictionary();
+ using var ps = NativeData.Read(Path.Combine(data, "tables", "PassiveSkills.json"));
+ foreach (var r in ps.RootElement.EnumerateArray())
+ if (r.TryGetProperty("AscendancyKey", out var key) && key.ValueKind == JsonValueKind.Number
+ && r.GetProperty("PassiveSkillGraphId").GetInt32() is int g and > 0 and <= ushort.MaxValue)
+ rows.TryAdd((ushort)g, (key.GetInt32(), r.GetProperty("IsAscendancyStartingNode").GetBoolean()));
+ return rows;
+ });
+ int ascendancyRow = -1;
+ using (var asc = NativeData.Read(Path.Combine(data, "tables", "Ascendancy.json")))
+ ascendancyRow = asc.RootElement.EnumerateArray().Select((r, i) => (r, i)).FirstOrDefault(x =>
+ string.Equals(x.r.GetProperty("Name").GetString(), build.Ascendancy, StringComparison.OrdinalIgnoreCase)
+ || string.Equals(x.r.GetProperty("Id").GetString(), build.Ascendancy, StringComparison.OrdinalIgnoreCase), (default, -1)).Item2;
+ var ascendancyNodes = build.Tree.Nodes.Where(id => id <= ushort.MaxValue && ascendancyRows.TryGetValue((ushort)id, out var a)
+ && a.Key == ascendancyRow && !a.Start).Select(id => (ushort)id).ToList();
+ if (!string.IsNullOrWhiteSpace(build.Ascendancy) && !build.Ascendancy.Equals("None", StringComparison.OrdinalIgnoreCase))
+ {
+ using var asc = NativeData.Read(Path.Combine(data, "tables", "Ascendancy.json"));
+ var row = asc.RootElement.EnumerateArray().FirstOrDefault(r =>
+ string.Equals(r.GetProperty("Name").GetString(), build.Ascendancy, StringComparison.OrdinalIgnoreCase)
+ || string.Equals(r.GetProperty("Id").GetString(), build.Ascendancy, StringComparison.OrdinalIgnoreCase));
+ if (row.ValueKind != JsonValueKind.Object) throw new InvalidDataException($"Unknown native ascendancy '{build.Ascendancy}'.");
+ else
+ ascendancy = new JsonObject
+ {
+ ["Selection"] = new JsonObject { ["Family"] = 0, ["Id"] = row.GetProperty("Id").GetString(), ["Revision"] = "3.29.3c" },
+ ["Nodes"] = new JsonArray([.. ascendancyNodes.Select(n => (JsonNode)n)]),
+ ["Awards"] = new JsonArray("normal", "cruel", "merciless", "eternal"),
+ };
+ }
+
+ // Tree jewels: every PoB socket -> the PassiveJewels pane cell of that node (ordinary or cluster expansion).
+ var descendancyNodes = new List();
+ int descendancy = build.Tree.SecondaryAscendancyId;
+ var secondaryRows = NativeData.Shared("secondary-ascendancy-rows", () =>
+ {
+ using var rows = NativeData.Read(Path.Combine(data, "tables", "PassiveSkills.json"));
+ return rows.RootElement.EnumerateArray().Where(r => r.GetProperty("DescendancyKey").ValueKind == JsonValueKind.Number)
+ .GroupBy(r => r.GetProperty("PassiveSkillGraphId").GetUInt32()).ToDictionary(g => g.Key, g => g.First());
+ });
+ foreach (uint node in build.Tree.Nodes)
+ {
+ if (!secondaryRows.TryGetValue(node, out var row)) continue;
+ if (row.GetProperty("DescendancyKey").GetInt32() != descendancy) throw new InvalidDataException($"Passive {node} belongs to a different secondary ascendancy.");
+ if (!row.GetProperty("IsAscendancyStartingNode").GetBoolean()) descendancyNodes.Add(checked((ushort)node));
+ warnings.RemoveAll(w => w.StartsWith($"Skipped unsupported special passive {node} ", StringComparison.Ordinal));
+ }
+ if (descendancy is < 0 or > 255) throw new InvalidDataException("Invalid secondary ascendancy row.");
+ using (var rows = NativeData.Read(Path.Combine(data, "tables", "Descendancy.json")))
+ if (descendancy >= rows.RootElement.GetArrayLength()) throw new InvalidDataException("Secondary ascendancy is absent from this client.");
+ // A Bloodline can spend the earned Labyrinth pool while the main class remains unascended.
+ // Preserve those awards instead of encoding an impossible four-points-spent / zero-earned save.
+ if (descendancyNodes.Count > 0 && ascendancy is null)
+ ascendancy = new JsonObject { ["Selection"] = null, ["Nodes"] = new JsonArray(),
+ ["Awards"] = new JsonArray("normal", "cruel", "merciless", "eternal") };
+ var definitions = build.Items.ToDictionary(i => i.Id);
+ var jewels = new List<(int Cell, CharacterSaves.SavedItem Item, int? ClusterSize, string Text)>();
+ foreach (var socket in build.Tree.Jewels)
+ {
+ if (!definitions.TryGetValue(socket.ItemId, out var definition)) continue;
+ if (socket.NodeId > ushort.MaxValue || !cells.ByNode.TryGetValue((ushort)socket.NodeId, out int cell))
+ { warnings.Add($"Джевел в узле {socket.NodeId}: ячейка не найдена — пропущен."); continue; }
+ // A refunded socket still contains its jewel; activation is decided by the Game module.
+ try
+ {
+ var own = new List();
+ // PoB's own cluster properties: the layout comes from the enchantments, which stay.
+ var text = ClusterItemText(definition.Text);
+ var (type, item) = PathOfBuildingItems.ParseItem(definition with { Text = text }, catalog, data, own);
+ item = Finish(definition, type, item, own);
+ warnings.AddRange(own);
+ int? size = type.Name switch { "Small Cluster Jewel" => 0, "Medium Cluster Jewel" => 1, "Large Cluster Jewel" => 2, _ => null };
+ var saved = CharacterSaves.ToSaved(item, catalog.Mods);
+ saved = PassiveHashMods(saved, definition.Text, data);
+ if (Regex.Match(definition.Text, @"Adds (\d+) Small Passive Skills? which grants? nothing") is { Success: true } voices)
+ {
+ // Voices: the empty-passive variant is the count (1/3/5/7), not the roll evryBuild guessed.
+ string variant = voices.Groups[1].Value switch { "1" => "ExpansionJewelEmptyPassiveUnique__1", "3" => "ExpansionJewelEmptyPassiveUnique__2",
+ "5" => "ExpansionJewelEmptyPassiveUnique_3_", _ => "ExpansionJewelEmptyPassiveUnique__4" };
+ saved = saved with { Mods = [.. (saved.Mods ?? []).Select(m => m.Id.StartsWith("ExpansionJewelEmptyPassiveUnique")
+ ? m with { Id = variant, Values = [int.Parse(voices.Groups[1].Value)] } : m)] };
+ }
+ if (size is not null && item.Rarity != ItemRarity.Unique && Regex.IsMatch(definition.Text, @"Adds \d+ Passive Skills")) saved = FixCluster(saved, definition.Text, data, warnings);
+ jewels.Add((cell, saved, size, definition.Text));
+ }
+ catch (Exception e) when (e is ArgumentException or InvalidOperationException or FormatException)
+ { warnings.Add($"Джевел '{ItemSend.Title(definition.Text)}' (ячейка {cell}): {e.Message}"); }
+ }
+
+ // Cluster passives: PoB's subgraph ids -> the client's expansion ids (Agents/docs/game/cluster-jewels.md).
+ var templates = ClusterTemplates.Load(data);
+ var clusterIds = new SortedSet();
+ var jewelByCell = jewels.ToDictionary(j => j.Cell);
+ foreach (uint id in build.Tree.Nodes.Where(n => n >= 0x10000))
+ {
+ int index = (int)(id & 0xF), size = (int)(id >> 4 & 3), large = (int)(id >> 6 & 7), medium = (int)(id >> 9 & 3);
+ if (index >= 12) continue; // PoB's mastery decoration (index 12) is not a client node.
+ // A smaller jewel may sit in a larger socket, and medium index 0 adds nothing to PoB's id: walk the large
+ // socket -> its medium cell -> that one's small cell and take the first that holds a jewel of this size.
+ int? at = null;
+ int lc = cells.Large.FirstOrDefault(c => cells.Index[c] == large, -1);
+ var path = new List();
+ if (lc >= 0)
+ {
+ path.Add(lc);
+ int mc = cells.Children(lc).FirstOrDefault(c => cells.Index[c] == medium, -1);
+ if (mc >= 0) { path.Add(mc); int sc = cells.Children(mc).FirstOrDefault(-1); if (sc >= 0) path.Add(sc); }
+ }
+ foreach (int c in path)
+ if (jewelByCell.TryGetValue(c, out var j) && j.ClusterSize == size) { at = c; break; }
+ if (at is null) { warnings.Add($"Кластерный узел {id}: нет кластера в ячейке — пропущен."); continue; }
+ clusterIds.Add(ClientId(cells, templates, at.Value, size, index));
+ }
+ // Sockets inside cluster jewels are ordinary PassiveSkills ids in PoB; the client counts them as cluster nodes.
+ foreach (uint id in build.Tree.Nodes.Where(n => n <= ushort.MaxValue))
+ {
+ if (!cells.ByNode.TryGetValue((ushort)id, out int cell) || cells.Parent(cell) is not int parent) continue;
+ if (!jewelByCell.TryGetValue(parent, out var host) || host.ClusterSize is not int hostSize) continue;
+ var template = templates[hostSize];
+ int position = -1;
+ if (hostSize == 2 && SocketCount(host.Text) == 1) position = 6; // PoB/client: a single-socket large uses index 6.
+ else
+ {
+ int[] order = [0, 2, 1];
+ int k = Array.IndexOf(order, cells.Index[cell]);
+ if (hostSize < 2) k = 0;
+ if (k >= 0 && k < template.Socket.Length) position = template.Socket[k];
+ }
+ if (position < 0) { warnings.Add($"Сокет кластера {id}: позиция не найдена — пропущен."); continue; }
+ clusterIds.Add(ClientId(cells, templates, parent, hostSize, position));
+ }
+
+ // Points: ordinary passives and cluster nodes share the budget (level - 1 + quest/extra points).
+ int ordinary = progress.Passives.Count, granted = tree.PointsGranted(progress.Passives);
+ int extra = Math.Max(0, ordinary + clusterIds.Count - (build.Level - 1) - granted - NativeProgress.AscendancyPoints(build, data));
+
+ // Inventories: keep everything but the replaced rows; new item ids start above the kept ones.
+ var kept = new JsonObject();
+ uint maxId = 0;
+ if (save["Inventories"] is JsonObject old)
+ foreach (var (row, list) in old)
+ {
+ if (Replaced.Contains(byte.Parse(row))) continue;
+ kept[row] = list!.DeepClone();
+ foreach (var p in list!.AsArray()) maxId = Math.Max(maxId, p!["Id"]!.GetValue());
+ }
+ uint next = maxId + 1;
+ foreach (var (row, placements) in equipment.Inventories)
+ kept[row.ToString()] = new JsonArray([.. placements.Select(p => Placement(next++, p.X, p.Y, p.Item))]);
+ if (jewels.Count > 0)
+ kept[PassiveJewels.ToString()] = new JsonArray([.. jewels.OrderBy(j => j.Cell).Select(j => Placement(next++, (byte)j.Cell, 0, j.Item))]);
+
+ save["Inventories"] = kept;
+ save["SkillBar"] = JsonSerializer.SerializeToNode(equipment.SkillBar.ToDictionary(k => k.Key.ToString(), k => k.Value));
+ save["Experience"] = progress.Experience;
+ save["Passives"] = JsonSerializer.SerializeToNode(progress.Passives);
+ save["MasteryEffects"] = progress.MasteryEffects.Count > 0 ? JsonSerializer.SerializeToNode(progress.MasteryEffects.ToDictionary(k => k.Key.ToString(), k => k.Value)) : null;
+ save["Tattoos"] = progress.Tattoos is { Count: > 0 } t ? JsonSerializer.SerializeToNode(t.ToDictionary(k => k.Key.ToString(), k => k.Value)) : null;
+ save["TattooKeystones"] = progress.TattooKeystones is { Count: > 0 } tk ? JsonSerializer.SerializeToNode(tk.ToDictionary(k => k.Key.ToString(), k => k.Value)) : null;
+ save["ExtraPassivePoints"] = extra;
+ save["ClusterPassives"] = clusterIds.Count > 0 ? new JsonArray([.. clusterIds.Select(i => (JsonNode)i)]) : null;
+ save["MainAscendancy"] = ascendancy;
+ save["Descendancy"] = descendancy == 0 ? null : JsonValue.Create(descendancy);
+ save["DescendancyNodes"] = descendancyNodes.Count == 0 ? null : JsonSerializer.SerializeToNode(descendancyNodes);
+ save["PantheonMajor"] = Pantheon(data, build.PantheonMajor, warnings);
+ save["PantheonMinor"] = Pantheon(data, build.PantheonMinor, warnings);
+ // Session state that belongs to the old build.
+ foreach (string field in new[] { "ActiveAuras", "Life", "Mana", "VitalsOwner", "Tutorial", "StartWeapon", "AttackInPlaceSlots", "SkillBarMask52" })
+ save[field] = null;
+ var moduleData = new JsonObject
+ {
+ ["Game.ImportedPassiveExtra"] = extra.ToString(System.Globalization.CultureInfo.InvariantCulture),
+ ["pob.source"] = input.Code.Trim(),
+ };
+ if (!string.IsNullOrWhiteSpace(build.Bandit) && !build.Bandit.Equals("None", StringComparison.OrdinalIgnoreCase))
+ {
+ if (build.Bandit is not ("Eramir" or "Alira" or "Kraityn" or "Oak")) throw new InvalidDataException($"Unknown bandit choice '{build.Bandit}'.");
+ moduleData["Game.ImportedBanditChoice"] = build.Bandit;
+ }
+ save["ModuleData"] = moduleData;
+
+ record["Class"] = (int)build.Class;
+ record["Level"] = build.Level;
+
+ // Lines handled here (PassiveHashMods) or that are PoB labels, not modifiers.
+ warnings.RemoveAll(w => Regex.IsMatch(w, @"modifier '(Passive Skills in Radius of .* can be Allocated|without being connected to your tree|Passage|Allocates .*)'"));
+ // A skill an item modifier or a passive grants comes with that item or passive: there are no gems to socket.
+ warnings.RemoveAll(w => w.Contains("item-granted skill source"));
+ int items = equipment.Inventories.Sum(i => i.Value.Count);
+ int gems = equipment.Inventories.SelectMany(i => i.Value).Sum(i => i.Item.Sockets?.Count(s => s.Gem is not null) ?? 0);
+ Console.WriteLine($"Персонаж: {name} -> {build.Class} {build.Ascendancy}, уровень {build.Level}");
+ if (NativeSource.SourcePath is { } sourcePath) Console.WriteLine($"Нативный снимок: {sourcePath}; обработано предметов: {NativeSource.ResolvedItems}.");
+ Console.WriteLine($"Предметов: {items}, камней: {gems}, пассивок: {ordinary}, мастерий: {progress.MasteryEffects.Count}, " +
+ $"асценд. узлов: {ascendancyNodes.Count}, джевелов на дереве: {jewels.Count}, узлов кластеров: {clusterIds.Count}, доп. очков: {extra}");
+ if (warnings.Count > 0)
+ {
+ Console.WriteLine($"Предупреждения ({warnings.Distinct().Count()}):");
+ foreach (string w in warnings.Distinct()) Console.WriteLine(" - " + w);
+ }
+ var losses = warnings.Where(w => w.StartsWith("Пропущено") || w.StartsWith("Skipped item") || w.StartsWith("Skipped gem")
+ || w.StartsWith("Skipped") || w.StartsWith("Skipped modifier") || w.StartsWith("Джевел") || w.StartsWith("Кластер") || w.StartsWith("Дерево")).Distinct().ToArray();
+ if (losses.Length > 0)
+ throw new InvalidDataException($"Импорт с потерями запрещён; база не изменена: {string.Join("; ", losses)}");
+ var result = new JsonObject { ["Record"] = record, ["Save"] = save,
+ ["Summary"] = $"{build.Class}, уровень {build.Level}; предметов {items}, камней {gems}, пассивок {ordinary}",
+ ["Warnings"] = JsonSerializer.SerializeToNode(WarningPages(warnings)) };
+ if (protocolV1) result["Version"] = 1;
+ NativeData.Validate();
+ resultOutput.WriteLine((protocolV1 ? "" : "POB_RESULT|") + result.ToJsonString());
+ }
+
+ // Keep every diagnostic while respecting the SDK's 100 x 800-character transport budget.
+ // Loss detection above still runs on the original individual warnings before packaging.
+ static string[] WarningPages(IEnumerable warnings)
+ {
+ string text = string.Join('\n', warnings.Distinct());
+ var pages = new List();
+ for (int start = 0; start < text.Length;)
+ {
+ int length = Math.Min(800, text.Length - start);
+ if (start + length < text.Length)
+ {
+ int line = text.LastIndexOf('\n', start + length - 1, length);
+ if (line > start) length = line - start + 1;
+ else if (char.IsHighSurrogate(text[start + length - 1])) length--;
+ }
+ pages.Add(text.Substring(start, length)); start += length;
+ }
+ if (pages.Count > 100) throw new InvalidDataException("The complete import diagnostics exceed the SDK budget; no warnings were discarded.");
+ return pages.ToArray();
+ }
+
+ // PoB labels cluster structure as crafted implicits. FixCluster reconstructs those native values;
+ // keep the Implicits count aligned when removing their textual restatement and PoB metadata.
+ static string ClusterItemText(string text)
+ {
+ var lines = text.Replace("\r", "").Split('\n');
+ bool structure = Regex.IsMatch(text, @"^Cluster Jewel Skill:\s*\S+", RegexOptions.Multiline)
+ && Regex.IsMatch(text, @"Adds \d+ Passive Skills");
+ var output = new List();
+ int remaining = 0, marker = -1, kept = 0;
+ foreach (string raw in lines)
+ {
+ string line = raw.Trim();
+ if (line.StartsWith("Implicits:") && int.TryParse(line[10..], out int count))
+ { remaining = count; marker = output.Count; output.Add(raw); continue; }
+ bool metadata = line.StartsWith("Cluster Jewel Skill:") || line.StartsWith("Cluster Jewel Node Count:");
+ string plain = Regex.Replace(line, @"^(?:\{[^}]+\})+", "");
+ bool remove = metadata || plain.StartsWith("Added Small Passive Skills grant:")
+ || structure && Regex.IsMatch(plain, @"^Adds \d+ Passive Skills$");
+ bool implicitLine = !metadata && remaining > 0 && line.Length > 0;
+ if (implicitLine) remaining--;
+ if (remove) continue;
+ if (implicitLine) kept++;
+ output.Add(raw);
+ }
+ if (marker >= 0) output[marker] = "Implicits: " + kept;
+ return string.Join('\n', output);
+ }
+
+ /// A cluster jewel's structure enchantment: JewelExpansionPassiveNodes holds the theme (the
+ /// PassiveTreeExpansionSkills row of PoB's "Cluster Jewel Skill") and the passive count. evryBuild leaves both 0,
+ /// which the Gateway reads as a cluster with no passives.
+ static CharacterSaves.SavedItem FixCluster(CharacterSaves.SavedItem item, string text, string data, List warnings)
+ {
+ string title = ItemSend.Title(text);
+ string? skill = Regex.Match(text, @"^Cluster Jewel Skill:\s*(\S+)", RegexOptions.Multiline) is { Success: true } s ? s.Groups[1].Value : null;
+ int count = Regex.Match(text, @"Adds (\d+) Passive Skills") is { Success: true } a ? int.Parse(a.Groups[1].Value)
+ : Regex.Match(text, @"^Cluster Jewel Node Count:\s*(\d+)", RegexOptions.Multiline) is { Success: true } n ? int.Parse(n.Groups[1].Value) : 0;
+ int theme = -1;
+ if (skill is not null)
+ {
+ var themes = NativeData.Shared("cluster-themes", () =>
+ {
+ using var ps = NativeData.Read(Path.Combine(data, "tables", "PassiveSkills.json"));
+ var names = ps.RootElement.EnumerateArray().Select(r => r.GetProperty("Id").GetString()!).ToArray();
+ using var ex = NativeData.Read(Path.Combine(data, "tables", "PassiveTreeExpansionSkills.json"));
+ return ex.RootElement.EnumerateArray().Select((r, i) => (Name: names[r.GetProperty("PassiveSkillsKey").GetInt32()], Index: i))
+ .GroupBy(p => p.Name).ToDictionary(g => g.Key, g => g.First().Index);
+ });
+ theme = themes.GetValueOrDefault(skill, -1);
+ }
+ if (theme < 0) { warnings.Add($"Кластер '{title}': тема '{skill}' не найдена."); theme = 0; }
+ if (count <= 0) warnings.Add($"Кластер '{title}': не найдено число пассивок.");
+ var mods = (item.Mods ?? []).Where(m => m.Id != "JewelExpansionPassiveNodes").ToList();
+ mods.Insert(0, new CharacterSaves.SavedMod("JewelExpansionPassiveNodes", GameServer.Core.Protocol.Instance.ModSection.Enchant, [theme, count]));
+ return item with { Mods = mods };
+ }
+
+ /// Jewel lines that name a passive instead of a number: Impossible Escape's keystone and Forbidden
+ /// Flame/Flesh's ascendancy notable. The client's stat value is the passive's PassiveSkillGraphId (as the
+ /// Gateway's ImpossibleEscapeCatalogue writes it); evryBuild cannot read a name as a value and drops them.
+ static CharacterSaves.SavedItem PassiveHashMods(CharacterSaves.SavedItem item, string text, string data)
+ {
+ var added = new List();
+ if (Regex.Match(text, @"Passive Skills in Radius of (.+?) can be Allocated") is { Success: true } escape
+ && GraphIdByName(data, escape.Groups[1].Value.Trim(), ascendancy: false) is int keystone)
+ added.Add(new("JewelUniqueAllocateDisconnectedPassivesAroundKeystone", ModSection.Explicit, [keystone, 800]));
+ foreach (Match forbidden in Regex.Matches(text, @"Allocates (.+?) if you have the matching modifier on Forbidden (Flame|Flesh)"))
+ if (GraphIdByName(data, forbidden.Groups[1].Value.Trim(), ascendancy: true) is int notable)
+ added.Add(new(forbidden.Groups[2].Value == "Flesh" ? "PuzzlePieceCleansingFireUnique__1" : "PuzzlePieceGreatTangleUnique__1",
+ ModSection.Explicit, [notable]));
+ // Anointment: "Allocates " alone on its line is GrantedPassive, an enchantment.
+ foreach (Match anoint in Regex.Matches(text.Replace("\r", ""), @"^(?:\{[^}]*\})*Allocates ([^\n]+?)\s*$", RegexOptions.Multiline))
+ if (!anoint.Groups[1].Value.Contains(" if you have ") && GraphIdByName(data, anoint.Groups[1].Value.Trim(), ascendancy: false, notable: true) is int granted)
+ added.Add(new("GrantedPassive", ModSection.Enchant, [granted]));
+ if (added.Count == 0) return item;
+ var ids = added.Select(a => a.Id).ToHashSet();
+ return item with { Mods = [.. (item.Mods ?? []).Where(m => !ids.Contains(m.Id)), .. added] };
+ }
+
+ static Dictionary? passiveNames;
+ static int? GraphIdByName(string data, string name, bool ascendancy, bool notable = false)
+ {
+ if (passiveNames is null)
+ {
+ passiveNames = new(StringComparer.OrdinalIgnoreCase);
+ using var ps = NativeData.Read(Path.Combine(data, "tables", "PassiveSkills.json"));
+ foreach (var r in ps.RootElement.EnumerateArray())
+ {
+ string n = r.GetProperty("Name").GetString() ?? "";
+ bool asc = r.TryGetProperty("AscendancyKey", out var a) && a.ValueKind == JsonValueKind.Number;
+ bool keystone = r.TryGetProperty("IsKeystone", out var k) && k.ValueKind == JsonValueKind.True;
+ bool isNotable = r.TryGetProperty("IsNotable", out var nb) && nb.ValueKind == JsonValueKind.True;
+ int graph = r.GetProperty("PassiveSkillGraphId").GetInt32();
+ if (n.Length == 0) continue;
+ if (asc || keystone) passiveNames.TryAdd(n + (asc ? "|a" : "|k"), (graph, asc));
+ if (isNotable && !asc) passiveNames.TryAdd(n + "|n", (graph, false));
+ }
+ }
+ return passiveNames.TryGetValue(name + (notable ? "|n" : ascendancy ? "|a" : "|k"), out var found) ? found.Graph : null;
+ }
+
+ static JsonObject Placement(uint id, byte x, byte y, CharacterSaves.SavedItem item) => new()
+ {
+ ["Id"] = id, ["X"] = x, ["Y"] = y, ["Item"] = JsonSerializer.SerializeToNode(item),
+ };
+
+ /// The client's id of a cluster node: the cell's block base plus the ring position of the jewel's template
+ /// index, halved in an expansion cell (Agents/docs/game/cluster-jewels.md, ClusterJewelLayout).
+ static ushort ClientId(JewelCells cells, Dictionary templates, int cell, int size, int index)
+ {
+ var template = templates[size];
+ int start = size < cells.Starts[cell].Length ? cells.Starts[cell][size] : 0;
+ int position = (index + start) % template.Total;
+ return (ushort)(cells.Base(cell) + (cells.Size[cell] == 2 ? position : position / 2));
+ }
+
+ static int SocketCount(string text) =>
+ Regex.Match(text, @"Adds (\d+) Jewel Socket", RegexOptions.IgnoreCase) is { Success: true } m ? int.Parse(m.Groups[1].Value) : 2;
+
+ static string? Pantheon(string data, string? god, List warnings)
+ {
+ if (string.IsNullOrWhiteSpace(god) || god.Equals("None", StringComparison.OrdinalIgnoreCase)) return null;
+ using var doc = NativeData.Read(Path.Combine(data, "tables", "PantheonPanelLayout.json"));
+ foreach (var row in doc.RootElement.EnumerateArray())
+ if (string.Equals(row.GetProperty("Id").GetString(), god, StringComparison.OrdinalIgnoreCase)
+ || (row.GetProperty("GodName1").GetString() ?? "").EndsWith(" " + god, StringComparison.OrdinalIgnoreCase))
+ return row.GetProperty("Id").GetString();
+ throw new InvalidDataException($"Unknown native Pantheon selection '{god}'.");
+ }
+
+
+}
+
+/// The PassiveJewels pane cells (PassiveJewelSlots.json): node -> cell, sizes, parents, ClusterIndex, starts.
+sealed class JewelCells
+{
+ public Dictionary ByNode { get; } = [];
+ public Dictionary Size { get; } = [];
+ public Dictionary Index { get; } = [];
+ public Dictionary Starts { get; } = [];
+ public Dictionary ParentOf { get; } = [];
+ public List Large { get; } = [];
+
+ public int? Parent(int cell) => ParentOf.TryGetValue(cell, out int p) ? p : null;
+ public IEnumerable Children(int cell) => ParentOf.Where(kv => kv.Value == cell).Select(kv => kv.Key).OrderBy(c => Index[c]);
+
+ public int Base(int cell)
+ {
+ if (Parent(cell) is not int parent) return 39 * Index[cell];
+ if (Parent(parent) is null) return 39 * Index[parent] + 9 * Index[cell] + 12;
+ return Base(parent) + 6;
+ }
+
+ public static JewelCells Load(string data) => NativeData.Shared("jewel-cells", () => Read(data));
+ static JewelCells Read(string data)
+ {
+ var cells = new JewelCells();
+ using var slots = NativeData.Read(Path.Combine(data, "tables", "PassiveJewelSlots.json"));
+ using var passives = NativeData.Read(Path.Combine(data, "tables", "PassiveSkills.json"));
+ var rows = passives.RootElement.EnumerateArray().ToArray();
+ int cell = -1;
+ foreach (var row in slots.RootElement.EnumerateArray())
+ {
+ cell++;
+ int passiveRow = row.GetProperty("Slot").GetInt32();
+ if (passiveRow < 0 || passiveRow >= rows.Length || !rows[passiveRow].GetProperty("IsJewelSocket").GetBoolean()) continue;
+ if (row.GetProperty("__col6").GetBoolean() && row.GetProperty("ReplacesSlot").ValueKind == JsonValueKind.Null) continue;
+ int graphId = rows[passiveRow].GetProperty("PassiveSkillGraphId").GetInt32();
+ cells.ByNode.TryAdd((ushort)graphId, cell);
+ var size = row.GetProperty("ClusterJewelSize");
+ cells.Size[cell] = size.ValueKind == JsonValueKind.Number ? size.GetInt32() : -1;
+ cells.Index[cell] = row.TryGetProperty("ClusterIndex", out var ci) && ci.ValueKind == JsonValueKind.Number ? ci.GetInt32() : 0;
+ cells.Starts[cell] = row.TryGetProperty("StartIndices", out var st) && st.ValueKind == JsonValueKind.Array
+ ? [.. st.EnumerateArray().Select(v => v.GetInt32())] : [];
+ var replaces = row.GetProperty("ReplacesSlot");
+ if (replaces.ValueKind == JsonValueKind.Number) cells.ParentOf[cell] = replaces.GetInt32();
+ else if (cells.Size[cell] == 2) cells.Large.Add(cell);
+ }
+ return cells;
+ }
+}
+
+static class ClusterTemplates
+{
+ public sealed record Template(int[] Socket, int Total);
+
+ public static Dictionary Load(string data) => NativeData.Shared("cluster-templates", () => Read(data));
+ static Dictionary Read(string data)
+ {
+ using var doc = NativeData.Read(Path.Combine(data, "tables", "PassiveTreeExpansionJewels.json"));
+ return doc.RootElement.EnumerateArray().ToDictionary(r => r.GetProperty("PassiveTreeExpansionJewelSizesKey").GetInt32(),
+ r => new Template([.. r.GetProperty("SocketIndices").EnumerateArray().Select(v => v.GetInt32())], r.GetProperty("TotalIndices").GetInt32()));
+ }
+}
diff --git a/mods/pob/Converter/Source/ModCatalog.cs b/mods/pob/Converter/Source/ModCatalog.cs
new file mode 100644
index 0000000..b52c637
--- /dev/null
+++ b/mods/pob/Converter/Source/ModCatalog.cs
@@ -0,0 +1,150 @@
+// Adapted from LocalExile feature/pob-import, 5394de0a. See NOTICE.md.
+using System.Text.Json;
+using GameServer.Core.Protocol.Instance;
+
+///
+/// Mods.dat (data/tables/Mods.json, loaded on first use): what the server needs to put mods on items
+/// (Agents/docs/protocol/13-items.md §2a). The client identifies a mod by its HASH16 and counts its stats itself
+/// (StatsKey1..8 up to the first empty one), so every is built here with exactly that many values.
+///
+sealed class ModCatalog(string folder = "data", bool ruthless = false)
+{
+ /// A stat of a mod: its Stats.dat Id, the Stat{n}Min / Stat{n}Max roll range, and Stats.dat IsLocal (the
+ /// stat changes the item it is on, not the character).
+ public sealed record ModStat(string Id, int Min, int Max, bool Local = false, bool Scalable = true);
+
+ /// A Mods.dat row. GenerationType 1 prefix, 2 suffix, 3 unique / base implicit, 10 enchantment …;
+ /// Domain 1 items.
+ /// A Mods.dat row. Rolling (ItemRolls): SpawnWeights is the (Tags.dat Id, weight) list where the first tag the
+ /// item has decides, GenerationWeights multiply that by weight / 100, Families exclude each other on one item.
+ public sealed record Mod(int Row, string Id, ushort Hash, string Name, int Domain, int GenerationType, int Level,
+ IReadOnlyList Stats)
+ {
+ public IReadOnlyList Families { get; init; } = [];
+ public IReadOnlyList<(string Tag, int Weight)> SpawnWeights { get; init; } = [];
+ public IReadOnlyList<(string Tag, int Weight)> GenerationWeights { get; init; } = [];
+ public bool EssenceOnly { get; init; }
+ /// ModType.dat's Name for ModTypeKey: the Harvest conversion groups (ColdResistance, FireDamage …).
+ public string ModType { get; init; } = "";
+ public IReadOnlySet Tags { get; init; } = new HashSet();
+ /// What a mod does beyond its stats (monster mods: MonsterModCatalog): its BuffTemplates row (an aura or
+ /// buff, BuffTemplate1), the monster it leaves on death (MonsterOnDeath) and its granted skills
+ /// (GrantedEffectsPerLevelKeys).
+ public int? BuffTemplate { get; init; }
+ public string MonsterOnDeath { get; init; } = "";
+ public int GrantedEffects { get; init; }
+ public bool Unscalable { get; init; }
+
+ /// The weight for an item with these tags: the first spawn tag it has, times the first generation tag
+ /// it has / 100; 0 when no spawn tag matches.
+ public int WeightFor(IReadOnlySet tags)
+ {
+ int weight = SpawnWeights.FirstOrDefault(w => tags.Contains(w.Tag)).Weight;
+ if (weight > 0 && GenerationWeights.FirstOrDefault(w => tags.Contains(w.Tag)) is { Tag: not null } g) weight = weight * g.Weight / 100;
+ return weight;
+ }
+
+ /// The list a mod goes into when nothing else says so: prefixes and suffixes are explicit,
+ /// enchantments enchants, everything else (base implicits, corruptions …) implicit.
+ public ModSection DefaultSection => GenerationType switch { 1 or 2 => ModSection.Explicit, 10 => ModSection.Enchant, _ => ModSection.Implicit };
+
+ /// The mod with a value per stat rolled in its range.
+ public ItemMod Roll(ModSection section, Random random) =>
+ new(section, Hash, [.. Stats.Select(s => random.Next(Math.Min(s.Min, s.Max), Math.Max(s.Min, s.Max) + 1))]);
+
+ /// The mod with these values: missing ones are rolled, extra ones dropped (the client reads exactly one
+ /// per stat).
+ public ItemMod With(ModSection section, IReadOnlyList values, Random random)
+ {
+ var rolled = Roll(section, random).Values;
+ return new(section, Hash, [.. rolled.Select((v, i) => i < values.Count ? values[i] : v)]);
+ }
+
+ public override string ToString() => $"{Id} (row {Row})";
+ }
+
+ private readonly Lazy<(List Rows, Dictionary ByHash, Dictionary ById)> _mods = new(() => Load(folder, ruthless));
+
+ public bool Loaded => _mods.Value.Rows.Count > 0;
+
+ public Mod? Row(int row) => row >= 0 && row < _mods.Value.Rows.Count ? _mods.Value.Rows[row] : null;
+
+ public Mod? ByHash(ushort hash) => _mods.Value.ByHash.GetValueOrDefault(hash);
+
+ public Mod? ById(string id) => _mods.Value.ById.GetValueOrDefault(id);
+
+ public IReadOnlyList All => _mods.Value.Rows;
+
+ /// A mod by row number, exact Id (any case), then the first Id that contains the text.
+ public Mod? Find(string query)
+ {
+ if (int.TryParse(query, out int row)) return Row(row);
+ return ById(query) ?? _mods.Value.Rows.FirstOrDefault(m => m.Id.Contains(query, StringComparison.OrdinalIgnoreCase));
+ }
+
+ /// "SpellDamageOnWeaponImplicitWand1 implicit: spell_damage_+% 10" for logs and /mods.
+ public string Describe(ItemMod m) => ByHash(m.Hash) is { } mod
+ ? $"{mod.Id} {m.Section.ToString().ToLowerInvariant()}: " + string.Join(", ", mod.Stats.Select((s, i) => $"{s.Id} {(i < m.Values.Count ? m.Values[i] : 0)}"))
+ : $"0x{m.Hash:x4} {m.Section.ToString().ToLowerInvariant()}: {string.Join(", ", m.Values)}";
+
+ private static (List, Dictionary, Dictionary) Load(string folder, bool ruthless)
+ {
+ string path = Path.Combine(folder, "tables", "Mods.json"), statsPath = Path.Combine(folder, "tables", "Stats.json"),
+ tagsPath = Path.Combine(folder, "tables", "Tags.json"), modTypePath = Path.Combine(folder, "tables", "ModType.json");
+ var rows = new List();
+ if (!NativeData.Exists(path) || !NativeData.Exists(statsPath)) return (rows, [], []);
+ List<(string Id, bool Local, bool Scalable)> stats;
+ using (var s = NativeData.Read(statsPath))
+ stats = [.. s.RootElement.EnumerateArray().Select(r => (r.GetProperty("Id").GetString() ?? "", r.GetProperty("IsLocal").GetBoolean(), r.GetProperty("IsScalable").GetBoolean()))];
+ List modTypes = [];
+ if (NativeData.Exists(modTypePath))
+ using (var t = NativeData.Read(modTypePath))
+ modTypes = [.. t.RootElement.EnumerateArray().Select(r => r.GetProperty("Name").GetString() ?? "")];
+ List tags = [];
+ if (NativeData.Exists(tagsPath))
+ using (var t = NativeData.Read(tagsPath))
+ tags = [.. t.RootElement.EnumerateArray().Select(r => r.GetProperty("Id").GetString() ?? "")];
+ List<(string, int)> Weights(JsonElement r, string keys, string values) =>
+ [.. r.GetProperty(keys).EnumerateArray().Zip(r.GetProperty(values).EnumerateArray(),
+ (k, v) => (k.GetInt32() < tags.Count ? tags[k.GetInt32()] : $"#{k.GetInt32()}", v.GetInt32()))];
+ using var d = NativeData.Read(path);
+ foreach (var r in d.RootElement.EnumerateArray())
+ {
+ bool alternate = ruthless && r.TryGetProperty("HasHardmodeStatValues", out var hardmode) && hardmode.GetBoolean();
+ string suffix = alternate ? "Hardmode" : "";
+ // The client's stat iterator (0x142430710) stops at the first empty key, so the count does too.
+ var modStats = new List();
+ for (int i = 1; i <= 8; i++)
+ {
+ if (r.GetProperty($"StatsKey{i}") is not { ValueKind: JsonValueKind.Number } k) break;
+ int key = k.GetInt32();
+ var (statId, local, scalable) = key < stats.Count ? stats[key] : ($"#{key}", false, false);
+ // Explicit zero is meaningful (for example disabled boss rarity bonuses); it must not fall back.
+ modStats.Add(new(statId, r.GetProperty($"Stat{i}Min{suffix}").GetInt32(), r.GetProperty($"Stat{i}Max{suffix}").GetInt32(), local, scalable));
+ }
+ rows.Add(new Mod(rows.Count, r.GetProperty("Id").GetString() ?? "", (ushort)r.GetProperty("HASH16").GetInt32(),
+ r.GetProperty("Name").GetString() ?? "", r.GetProperty("Domain").GetInt32(), r.GetProperty("GenerationType").GetInt32(),
+ r.GetProperty("Level").GetInt32(), modStats)
+ {
+ Families = [.. r.GetProperty("Families").EnumerateArray().Select(f => f.GetInt32())],
+ SpawnWeights = Weights(r, "SpawnWeight_TagsKeys", "SpawnWeight_Values"),
+ GenerationWeights = Weights(r, "GenerationWeight_TagsKeys", "GenerationWeight_Values"),
+ EssenceOnly = r.GetProperty("IsEssenceOnlyModifier").GetBoolean(),
+ ModType = r.TryGetProperty("ModTypeKey", out var modType) && modType.ValueKind == JsonValueKind.Number &&
+ modType.GetInt32() is int mt && mt >= 0 && mt < modTypes.Count ? modTypes[mt] : "",
+ BuffTemplate = r.TryGetProperty("BuffTemplate1", out var buff) && buff.ValueKind == JsonValueKind.Number ? buff.GetInt32() : null,
+ MonsterOnDeath = r.TryGetProperty("MonsterOnDeath", out var death) ? death.GetString() ?? "" : "",
+ GrantedEffects = r.TryGetProperty("GrantedEffectsPerLevelKeys", out var granted) ? granted.GetArrayLength() : 0,
+ Unscalable = r.TryGetProperty("IsUnscalable", out var unscalable) && unscalable.GetBoolean(),
+ Tags = new[] { "TagsKeys", "ImplicitTagsKeys" }
+ .Where(key => r.TryGetProperty(key, out _))
+ .SelectMany(key => r.GetProperty(key).EnumerateArray().Select(k => k.GetInt32()))
+ .Where(k => k >= 0 && k < tags.Count).Select(k => tags[k]).ToHashSet(),
+ });
+ }
+ var byHash = new Dictionary();
+ var byId = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (var m in rows) { byHash.TryAdd(m.Hash, m); byId.TryAdd(m.Id, m); }
+ return (rows, byHash, byId);
+ }
+}
diff --git a/mods/pob/Converter/Source/ModText.cs b/mods/pob/Converter/Source/ModText.cs
new file mode 100644
index 0000000..56c51f9
--- /dev/null
+++ b/mods/pob/Converter/Source/ModText.cs
@@ -0,0 +1,188 @@
+using System.Globalization;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using GameServer.Core.Protocol.Instance;
+
+///
+/// Names modifiers from the text PoB shows for them. The native description renderer supplies lines by
+/// Mods.dat Id, so a line is matched by its wording with the numbers ignored, and several lines can be one hybrid
+/// modifier. Each number is inverted through its exact native stat binding and unit conversion;
+/// literal numbers and repeated bindings must agree, and conditional wording selects hidden enum values.
+///
+sealed class ModText(IReadOnlyList patterns)
+{
+ internal sealed record Line(ModSection Section, string Text);
+
+ /// A modifier for these indices of the given lines. OutsideRoll: a value beyond the native roll, which
+ /// catalysts and magnitude modifiers can cause; the value is kept.
+ internal sealed record Found(ItemMod Mod, IReadOnlyList Lines, bool OutsideRoll);
+
+ sealed record Entry(NativeModText.Pattern Pattern)
+ {
+ public string Id => Pattern.Id;
+ public string[] Lines => Pattern.Lines;
+ }
+ sealed record Token(double Low, double High)
+ {
+ public bool Holds(double value) => value >= Math.Min(Low, High) - 1e-6 && value <= Math.Max(Low, High) + 1e-6;
+ public double Distance(double value) => Math.Max(0, Math.Max(Math.Min(Low, High) - value, value - Math.Max(Low, High)));
+ }
+ sealed record Candidate(Entry Entry, ModCatalog.Mod Mod, ModSection Section, int[] Lines, int[] Values, bool Outside, double Distance);
+
+ static readonly Regex Number = new(@"([+-]?)\((-?\d+(?:\.\d+)?)-(-?\d+(?:\.\d+)?)\)|[+-]?\d+(?:\.\d+)?", RegexOptions.CultureInvariant);
+ static readonly Lazy Bundled = new(() =>
+ {
+ return new(NativeModText.Build());
+ });
+
+ public static ModText Embedded => Bundled.Value;
+
+ readonly IReadOnlyDictionary entries = patterns.Select((p, i) => (p, i)).ToDictionary(x => x.p.Id + "#" + x.i, x => x.p.Lines);
+ readonly Lazy> byWording = new(() => patterns
+ .Select(e => new Entry(e))
+ .SelectMany(e => e.Lines.Select(l => (Wording: Wording(l), Entry: e))).ToLookup(p => p.Wording, p => p.Entry));
+
+ // Capitals differ between PoB's trade-derived text and its mod data ("All Lightning" and "all Lightning").
+ static string Canonical(string line)
+ {
+ const string mana = " Mana per Enemy Killed", curse = "% reduced Curse Duration";
+ if (line.StartsWith("Lose ", StringComparison.OrdinalIgnoreCase) && line.EndsWith(mana, StringComparison.OrdinalIgnoreCase)
+ && Number.Match(line[5..^mana.Length]) is { Success: true } amount && amount.Value == line[5..^mana.Length])
+ return "Gain -" + amount.Value + mana;
+ if (line.EndsWith(curse, StringComparison.OrdinalIgnoreCase)
+ && Number.Match(line[..^curse.Length]) is { Success: true } duration && duration.Value == line[..^curse.Length])
+ return "-" + duration.Value + "% increased Curse Duration";
+ return line;
+ }
+
+ internal static string Wording(string line) => Number.Replace(Canonical(line), "#").ToLowerInvariant();
+
+ static double Parse(string value) => double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture);
+
+ static IEnumerable Tokens(string line) => Number.Matches(Canonical(line)).Select(m =>
+ {
+ if (!m.Groups[2].Success) { double value = Parse(m.Value); return new Token(value, value); }
+ int sign = m.Groups[1].Value == "-" ? -1 : 1;
+ return new Token(sign * Parse(m.Groups[2].Value), sign * Parse(m.Groups[3].Value));
+ });
+
+ static IEnumerable Values(string line) => Number.Matches(Canonical(line)).Select(m => Parse(m.Value));
+
+ /// The best modifiers for these lines. Each line is used at most once; a line no modifier fits is left out.
+ public IReadOnlyList Resolve(IReadOnlyList lines, ItemCatalog.BaseType type, Item item, ModCatalog mods)
+ {
+ var classLines = new List();
+ var classSources = new List();
+ int header = -1;
+ for (int i = 0; i < lines.Count; i++)
+ {
+ var line = lines[i];
+ if (line.Text == "While your Passive Skill Tree connects to a class' starting location, you gain:")
+ { header = i; continue; }
+ int colon = line.Text.IndexOf(": ", StringComparison.Ordinal);
+ string cls = colon > 0 ? line.Text[..colon] : "";
+ if (header >= 0 && cls is "Marauder" or "Duelist" or "Ranger" or "Shadow" or "Witch" or "Templar" or "Scion")
+ {
+ classLines.Add(new(line.Section, $"While your Passive Skill Tree connects to the {cls}'s starting location, you gain:"));
+ classSources.Add(header);
+ classLines.Add(new(line.Section, line.Text[(colon + 2)..])); classSources.Add(i);
+ continue;
+ }
+ if (header >= 0 && !classSources.Contains(header))
+ { classLines.Add(lines[header]); classSources.Add(header); }
+ header = -1;
+ classLines.Add(line); classSources.Add(i);
+ }
+ if (header >= 0 && !classSources.Contains(header)) { classLines.Add(lines[header]); classSources.Add(header); }
+ var (expanded, socketSources) = IndexedMods.ExpandSockets(classLines, entries);
+ int[] source = [.. socketSources.Select(i => classSources[i])];
+ return ResolveCore(expanded, type, item, mods).Select(f => f with { Lines = f.Lines.Select(i => source[i]).Distinct().ToArray() }).ToArray();
+ }
+
+ IReadOnlyList ResolveCore(IReadOnlyList lines, ItemCatalog.BaseType type, Item item, ModCatalog mods)
+ {
+ var candidates = new List();
+ var seen = new HashSet<(Entry, ModSection)>();
+ foreach (var line in lines)
+ foreach (var entry in byWording.Value[Wording(line.Text)])
+ if (seen.Add((entry, line.Section)) && mods.ById(entry.Id) is { } mod)
+ {
+ var excluded = new HashSet();
+ while (Match(entry, mod, line.Section, lines, excluded) is { } candidate)
+ {
+ candidates.Add(candidate);
+ excluded.UnionWith(candidate.Lines);
+ }
+ }
+ var result = type.Name == "Great Crown" ? IndexedMods.Resolve(lines, item, mods).ToList() : new List();
+ var used = result.SelectMany(f => f.Lines).ToHashSet();
+ // What a modifier does outranks how well its roll fits: "+397 to Armour" on a body armour is the item's own armour
+ // even when a catalyst lifts it past every local roll, and an in-range global armour stat would be a different item.
+ foreach (var candidate in candidates.OrderByDescending(c => DomainFit(c.Mod, type) > 0 ? c.Lines.Length : 0).ThenByDescending(c => DomainFit(c.Mod, type)).ThenByDescending(c => c.Lines.Length).ThenByDescending(c => LocalFit(c.Mod, type))
+ .ThenByDescending(c => SectionFits(c.Mod, c.Section, item))
+ .ThenBy(c => c.Outside).ThenByDescending(c => c.Lines.Length).ThenBy(c => c.Distance)
+ .ThenBy(c => c.Mod.Stats.Sum(s => (long)Math.Abs(s.Max - s.Min)))
+ .ThenByDescending(c => c.Mod.WeightFor(type.Tags) > 0).ThenByDescending(c => c.Mod.Level).ThenBy(c => c.Mod.Id, StringComparer.Ordinal))
+ {
+ var available = candidate;
+ if (candidate.Lines.Any(used.Contains))
+ {
+ if (candidate.Mod.Domain != 42 || Match(candidate.Entry, candidate.Mod, candidate.Section, lines, used) is not { } retry) continue;
+ available = retry;
+ }
+ used.UnionWith(available.Lines);
+ result.Add(new(new(available.Section, available.Mod.Hash, available.Values), available.Lines, available.Outside));
+ }
+ result.AddRange(IndexedMods.Resolve(lines, item, mods).Where(f => !f.Lines.Any(used.Contains)));
+ return result;
+ }
+
+ // A modifier's Domain says which items it belongs to; 9 is the crafting bench's. Wording alone can repeat across them.
+ static int DomainFit(ModCatalog.Mod mod, ItemCatalog.BaseType type) => mod.Domain == 42 && mod.Stats.Any(s => s.Id == "local_maximum_sockets_+") ? 3 : mod.Domain == type.ModDomain ? 2 : mod.Domain is 9 or 41 ? 1 : 0;
+
+ // Weapons, armour and flasks carry their own local stats. Elsewhere the same wording is the global stat.
+ static int LocalFit(ModCatalog.Mod mod, ItemCatalog.BaseType type)
+ {
+ int local = mod.Stats.Count(s => s.Local);
+ return type.Components.Contains("Armour") || type.Components.Contains("Weapon") || type.Components.Contains("Flask") ? local : -local;
+ }
+
+ // Rare and magic explicit lines are prefixes and suffixes. A unique's own modifiers can share their wording.
+ static bool SectionFits(ModCatalog.Mod mod, ModSection section, Item item) => section switch
+ {
+ ModSection.Enchant => mod.GenerationType == 10,
+ ModSection.Implicit => mod.GenerationType is not (1 or 2),
+ ModSection.Explicit => item.Rarity == ItemRarity.Unique || mod.GenerationType is 1 or 2,
+ _ => true,
+ };
+
+ static Candidate? Match(Entry entry, ModCatalog.Mod mod, ModSection section, IReadOnlyList lines, IReadOnlySet excluded)
+ {
+ var chosen = new List();
+ foreach (string text in entry.Lines)
+ {
+ string wording = Wording(text);
+ int index = Enumerable.Range(0, lines.Count).FirstOrDefault(i => !chosen.Contains(i) && !excluded.Contains(i) && lines[i].Section == section && Wording(lines[i].Text) == wording, -1);
+ if (index < 0) return null;
+ if (text == "-1 to maximum Sockets" && lines[index].Text != text) return null;
+ chosen.Add(index);
+ }
+ var tokens = entry.Lines.SelectMany(Tokens).ToArray();
+ var numbers = chosen.SelectMany(i => Values(lines[i].Text)).ToArray();
+ if (tokens.Length != numbers.Length) return null;
+ // Values() reads canonical wording. Undo a canonical sign change in the native
+ // template before applying its own handler (e.g. negate for reduced curse duration).
+ int offset = 0;
+ foreach (string text in entry.Lines)
+ {
+ int count = Number.Matches(text).Count;
+ if (Canonical(text) != text)
+ for (int n = 0; n < count; n++) numbers[offset + n] = -numbers[offset + n];
+ offset += count;
+ }
+ return entry.Pattern.Values(numbers) is { } values ? new(entry, mod, section, [.. chosen], values,
+ Enumerable.Range(0, tokens.Length).Any(i => !tokens[i].Holds(numbers[i])),
+ Enumerable.Range(0, tokens.Length).Sum(i => tokens[i].Distance(numbers[i]))) : null;
+ }
+
+}
diff --git a/mods/pob/Converter/Source/NativeActiveEffects.cs b/mods/pob/Converter/Source/NativeActiveEffects.cs
new file mode 100644
index 0000000..b756372
--- /dev/null
+++ b/mods/pob/Converter/Source/NativeActiveEffects.cs
@@ -0,0 +1,13 @@
+using System.Text.Json;
+
+static class NativeActiveEffects
+{
+ static readonly Lazy> Active = new(() =>
+ {
+ using var doc = NativeData.Read("data/tables/GrantedEffects.json");
+ return doc.RootElement.EnumerateArray().Select((r, i) => (Row: r, Index: i))
+ .Where(r => !r.Row.GetProperty("IsSupport").GetBoolean() && r.Row.GetProperty("ActiveSkill").ValueKind == JsonValueKind.Number)
+ .Select(r => r.Index).ToHashSet();
+ });
+ public static bool Contains(int row) => Active.Value.Contains(row);
+}
diff --git a/mods/pob/Converter/Source/NativeBaseIndex.cs b/mods/pob/Converter/Source/NativeBaseIndex.cs
new file mode 100644
index 0000000..3729da7
--- /dev/null
+++ b/mods/pob/Converter/Source/NativeBaseIndex.cs
@@ -0,0 +1,14 @@
+static class NativeBaseIndex
+{
+ sealed record Data(ItemCatalog.BaseType[] All, Dictionary Names);
+ static readonly Dictionary Cache = new();
+ static Data Get(ItemCatalog catalog)
+ {
+ if (Cache.TryGetValue(catalog, out var data)) return data;
+ var all = catalog.All.Where(t => t.Supported && !t.Id.Contains("Royale", StringComparison.OrdinalIgnoreCase)).ToArray();
+ return Cache[catalog] = new(all, all.GroupBy(t => t.Name, StringComparer.OrdinalIgnoreCase)
+ .ToDictionary(g => g.Key, g => g.ToArray(), StringComparer.OrdinalIgnoreCase));
+ }
+ public static ItemCatalog.BaseType[] All(ItemCatalog catalog) => Get(catalog).All;
+ public static ItemCatalog.BaseType[] Named(ItemCatalog catalog, string name) => Get(catalog).Names.GetValueOrDefault(name) ?? [];
+}
diff --git a/mods/pob/Converter/Source/NativeData.cs b/mods/pob/Converter/Source/NativeData.cs
new file mode 100644
index 0000000..71f5416
--- /dev/null
+++ b/mods/pob/Converter/Source/NativeData.cs
@@ -0,0 +1,88 @@
+using System.Text.Json;
+using GameServer.Core;
+
+// One converter request (or a read-only corpus run) uses one immutable data revision.
+// Client tables come from the same client.db as the server, never historical data/tables/*.json copies.
+static class NativeData
+{
+ static object? revision;
+ static readonly Dictionary documents = new(StringComparer.OrdinalIgnoreCase);
+ static readonly Dictionary derived = new(StringComparer.Ordinal);
+ static readonly Dictionary files = new(StringComparer.OrdinalIgnoreCase);
+
+ public sealed class Lease(JsonDocument document) : IDisposable
+ {
+ public JsonElement RootElement => document.RootElement;
+ public void Dispose() { } // The immutable document belongs to this bounded converter process.
+ }
+
+ public static void Validate()
+ {
+ revision ??= ClientTables.CacheKey;
+ if (!Equals(revision, ClientTables.CacheKey) || files.Any(f => File.GetLastWriteTimeUtc(f.Key) != f.Value))
+ throw new InvalidDataException("Game data changed during conversion; retry with one current data revision.");
+ }
+
+ static string? TableName(string path) => string.Equals(Path.GetFileName(Path.GetDirectoryName(Path.GetFullPath(path))),
+ "tables", StringComparison.OrdinalIgnoreCase) && Path.GetExtension(path).Equals(".json", StringComparison.OrdinalIgnoreCase)
+ ? Path.GetFileNameWithoutExtension(path) : null;
+
+ static readonly Dictionary tables = new(StringComparer.OrdinalIgnoreCase);
+ public static bool Exists(string path)
+ {
+ string? name = TableName(path) ?? (Path.GetFileName(path).Equals("item-types.json", StringComparison.OrdinalIgnoreCase) ? "item_types" : null);
+ if (name is null) return File.Exists(path);
+ if (!tables.TryGetValue(name, out bool exists)) { Validate(); tables[name] = exists = ClientTables.Has(name); }
+ return exists;
+ }
+
+ public static T Shared(string key, Func create) where T : class
+ {
+ if (!derived.TryGetValue(key, out var value)) { Validate(); derived.Add(key, value = create()); }
+ return (T)value;
+ }
+
+ public static Lease Read(string path)
+ {
+ string key = Path.GetFullPath(path);
+ if (!documents.TryGetValue(key, out var document))
+ {
+ Validate();
+ if (TableName(path) is { } table) document = Table(table);
+ else if (Path.GetFileName(path).Equals("item-types.json", StringComparison.OrdinalIgnoreCase))
+ {
+ using var rows = Table("item_types");
+ document = JsonSerializer.SerializeToDocument(new Dictionary { ["types"] = rows.RootElement });
+ }
+ else
+ {
+ DateTime written = File.GetLastWriteTimeUtc(key);
+ document = JsonDocument.Parse(File.ReadAllBytes(key));
+ if (File.GetLastWriteTimeUtc(key) != written) { document.Dispose(); throw new InvalidDataException("Game-data file changed during conversion."); }
+ files.Add(key, written);
+ }
+ Validate();
+ documents.Add(key, document);
+ }
+ return new(document);
+ }
+
+ static JsonDocument Table(string name)
+ {
+ var table = ClientTables.Table(name);
+ string[] columns = table.Columns.ToArray();
+ using var bytes = new MemoryStream();
+ using (var writer = new Utf8JsonWriter(bytes))
+ {
+ writer.WriteStartArray();
+ foreach (var row in table)
+ {
+ writer.WriteStartObject();
+ foreach (string column in columns) { writer.WritePropertyName(column); JsonSerializer.Serialize(writer, row.Get(column)); }
+ writer.WriteEndObject();
+ }
+ writer.WriteEndArray();
+ }
+ return JsonDocument.Parse(bytes.ToArray());
+ }
+}
diff --git a/mods/pob/Converter/Source/NativeGemCache.cs b/mods/pob/Converter/Source/NativeGemCache.cs
new file mode 100644
index 0000000..810fb4d
--- /dev/null
+++ b/mods/pob/Converter/Source/NativeGemCache.cs
@@ -0,0 +1,20 @@
+using GameServer.Core.Imports;
+using GameServer.Core.Protocol.Instance;
+
+static class NativeGemCache
+{
+ static readonly Dictionary Variants = [];
+ public static (ItemCatalog.BaseType Type, ItemCatalog.GemVariant Variant)[] Obtainable(ItemCatalog catalog)
+ {
+ if (Variants.TryGetValue(catalog, out var rows)) return rows;
+ return Variants[catalog] = catalog.All.Where(t => t.Supported && !t.Id.Contains("Royale", StringComparison.OrdinalIgnoreCase) && catalog.Gem(t) is not null)
+ .SelectMany(t => catalog.Gem(t)!.Variants.Where(v => v.Creatable).Select(v => (t, v))).ToArray();
+ }
+ static readonly Dictionary<(ItemCatalog, string, PathOfBuildingGem), Item> Cache = new();
+ public static Item Create(PathOfBuildingGem gem, ItemCatalog catalog, string folder, Func create)
+ {
+ var key = (catalog, folder, gem);
+ if (Cache.TryGetValue(key, out var item)) return item;
+ return Cache[key] = create();
+ }
+}
diff --git a/mods/pob/Converter/Source/NativeItemSources.cs b/mods/pob/Converter/Source/NativeItemSources.cs
new file mode 100644
index 0000000..07a3ee1
--- /dev/null
+++ b/mods/pob/Converter/Source/NativeItemSources.cs
@@ -0,0 +1,30 @@
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using GameServer.Core.Imports;
+using Microsoft.Data.Sqlite;
+
+// Optional operator-built registry of exact item exports in downloaded snapshots.
+// A changed build may reuse an item, but never the snapshot's tree, skills or socket contents.
+static class NativeItemSources
+{
+ public const string DefaultPath = "data/pob-import/native-items.db";
+ public static string Key(PathOfBuildingItem item) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(
+ JsonSerializer.Serialize(new { Text = Normalize(item.Text), item.Variant, item.HasAlternateVariants, item.HasLegacyModRanges,
+ Ranges = item.ModRanges.OrderBy(p => p.Key).ToArray() }))));
+
+ public static string Normalize(string text) => string.Join('\n', text.Replace("Rarity: RELIC", "Rarity: UNIQUE").Replace("\r", "").Split('\n')
+ .Select(l => Regex.Replace(l.Trim(), @"^Superior (?=\S)", ""))
+ .Where(l => l.Length > 0 && !l.StartsWith("{vestigial}") && !Regex.IsMatch(l, @"^(Requires Class \w+|Foil Unique \(.*\)|Ward: \d+|WardBasePercentile: [\d.]+|Memory Strands: \d+)$")));
+ public static string? Find(PathOfBuildingItem item)
+ {
+ if (!File.Exists(DefaultPath)) return null;
+ using var db = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = DefaultPath, Mode = SqliteOpenMode.ReadOnly, Pooling = false }.ToString());
+ db.Open();
+ using var query = db.CreateCommand();
+ query.CommandText = "SELECT source FROM item_sources WHERE fingerprint=$key";
+ query.Parameters.AddWithValue("$key", Key(item));
+ return query.ExecuteScalar() as string;
+ }
+}
diff --git a/mods/pob/Converter/Source/NativeModText.cs b/mods/pob/Converter/Source/NativeModText.cs
new file mode 100644
index 0000000..ccc2d99
--- /dev/null
+++ b/mods/pob/Converter/Source/NativeModText.cs
@@ -0,0 +1,188 @@
+using System.Globalization;
+using System.Text;
+using System.Text.RegularExpressions;
+
+// Current client descriptions bind every displayed number to its native stat, including conditional wording.
+static class NativeModText
+{
+ static readonly CultureInfo Invariant = CultureInfo.InvariantCulture;
+ internal static readonly Regex Number = new(@"([+-]?)\((-?\d+(?:\.\d+)?)-(-?\d+(?:\.\d+)?)\)|[+-]?\d+(?:\.\d+)?", RegexOptions.CultureInvariant);
+ static readonly Regex Placeholder = new(@"\{(\d*)(?::([^}]+))?\}", RegexOptions.CultureInvariant);
+ public sealed record Binding(int Stat, double Scale, double Literal = 0, int? Precision = null);
+ public sealed record Condition(int Stat, string Text);
+ public sealed record Pattern(string Id, string[] Lines, int[] Defaults, Binding[] Bindings, Condition[] Conditions)
+ {
+ public int[]? Values(double[] numbers)
+ {
+ if (numbers.Length != Bindings.Length) return null;
+ var values = Defaults.ToArray();
+ var assigned = new Dictionary();
+ for (int n = 0; n < numbers.Length; n++)
+ {
+ var b = Bindings[n];
+ if (b.Stat < 0) { if (Math.Abs(numbers[n] - b.Literal) > 1e-6) return null; continue; }
+ double native = numbers[n] / b.Scale;
+ if (!double.IsFinite(native) || native < int.MinValue || native > int.MaxValue) return null;
+ if (Math.Abs(native - Math.Round(native)) > 1e-5)
+ {
+ if (b.Precision is not int precision) return null;
+ double chosen = Math.Round(native), tolerance = Math.Pow(10, -precision) / 2 + 1e-9;
+ bool Displays(double value) => Math.Abs(value * b.Scale - numbers[n]) < tolerance;
+ // Accept only a unique native integer preimage of the rounded display, never an approximation.
+ if (!Displays(chosen) || Displays(chosen - 1) || Displays(chosen + 1)) return null;
+ native = chosen;
+ }
+ int value = checked((int)Math.Round(native));
+ if (assigned.TryGetValue(b.Stat, out int previous) && previous != value) return null;
+ assigned[b.Stat] = values[b.Stat] = value;
+ }
+ return Conditions.All(c => Holds(c.Text, c.Stat < 0 ? 0 : values[c.Stat])) ? values : null;
+ }
+ }
+ sealed record Fragment(string Text, Binding[] Bindings);
+ sealed record State(int[] Low, int[] High, HashSet Done, List Fragments, List Conditions);
+
+ public static IReadOnlyList Build()
+ {
+ var descriptions = StatDescriptions.Load();
+ if (descriptions.All.Count == 0) throw new InvalidDataException("Missing stat_descriptions in client.db; extract current client data.");
+ var byStat = descriptions.All.SelectMany(d => d.Stats.Select(s => (Stat: s, Description: d))).ToLookup(p => p.Stat, p => p.Description);
+ var result = new List();
+ foreach (var mod in new ModCatalog("data").All)
+ {
+ var positions = mod.Stats.Select((s, i) => (s.Id, i)).GroupBy(x => x.Id).ToDictionary(g => g.Key, g => g.Last().i);
+ var states = new List { new(mod.Stats.Select(s => Math.Min(s.Min, s.Max)).ToArray(), mod.Stats.Select(s => Math.Max(s.Min, s.Max)).ToArray(), [], [], []) };
+ foreach (var stat in mod.Stats)
+ {
+ var next = new List();
+ foreach (var state in states)
+ {
+ if (state.Done.Contains(stat.Id)) { next.Add(state); continue; }
+ int at = positions[stat.Id];
+ if (stat.Id is "local_jewel_effect_base_radius" or "dummy_stat_display_nothing" or "number_of_stackable_unique_jewels"
+ && state.Low[at] == state.High[at])
+ {
+ next.Add(state with { Done = new HashSet(state.Done) { stat.Id } });
+ continue;
+ }
+ // Radius is an item property, not a modifier line. Zero stats remain in the mod,
+ // but are hidden only if the client has no matching display variant for them.
+ bool hidden = state.Low[at] == state.High[at] && (stat.Id == "local_jewel_effect_base_radius" || state.Low[at] == 0);
+ bool rendered = false;
+ foreach (var description in byStat[stat.Id])
+ {
+ foreach (var variant in description.Variants)
+ {
+ int[] low = state.Low.ToArray(), high = state.High.ToArray();
+ var conditions = state.Conditions.ToList();
+ bool valid = true;
+ for (int i = 0; i < description.Stats.Count; i++)
+ {
+ int position = positions.GetValueOrDefault(description.Stats[i], -1);
+ string condition = variant.Conditions[i];
+ if (position < 0) valid &= Holds(condition, 0);
+ else valid &= Restrict(condition, ref low[position], ref high[position]);
+ conditions.Add(new(position, condition));
+ }
+ if (!valid || Render(variant, description.Stats, positions, low, high) is not { } fragment) continue;
+ var done = new HashSet(state.Done);
+ done.UnionWith(description.Stats);
+ next.Add(new(low, high, done, [.. state.Fragments, fragment], conditions));
+ rendered = true;
+ }
+ if (rendered) break;
+ }
+ if (!rendered && hidden) next.Add(state with { Done = new HashSet(state.Done) { stat.Id } });
+ }
+ states = next;
+ if (states.Count == 0) break;
+ }
+ foreach (var state in states)
+ {
+ if (state.Fragments.Count == 0) continue;
+ var bindings = state.Fragments.SelectMany(f => f.Bindings).ToArray();
+ // Never guess an unprinted variable. Conditional wording can select an exact value
+ // (e.g. Rakiata selects the Timeless Jewel's keystone index 2).
+ if (Enumerable.Range(0, mod.Stats.Count).Any(i => state.Low[i] != state.High[i] && !bindings.Any(b => b.Stat == i))) continue;
+ result.Add(new(mod.Id, state.Fragments.SelectMany(f => f.Text.Replace("\\n", "\n").Split('\n')).ToArray(), state.Low, bindings, state.Conditions.ToArray()));
+ }
+ }
+ return result;
+ }
+
+ static Fragment? Render(StatDescriptions.Variant variant, IReadOnlyList stats, Dictionary positions, int[] low, int[] high)
+ {
+ var scales = Enumerable.Repeat(1d, stats.Count).ToArray();
+ var precision = new int?[stats.Count];
+ foreach (var (name, index) in variant.Handlers)
+ {
+ if (name == "canonical_stat") continue; // Description metadata, not an arithmetic transform.
+ if (index < 1 || index > scales.Length) return null;
+ double? factor = name switch
+ {
+ "negate" => -1, "divide_by_one_hundred" or "divide_by_one_hundred_2dp_if_required" => .01,
+ "per_minute_to_per_second" or "per_minute_to_per_second_2dp" or "per_minute_to_per_second_0dp" or "per_minute_to_per_second_1dp" or "per_minute_to_per_second_2dp_if_required" => 1d / 60,
+ "milliseconds_to_seconds" or "milliseconds_to_seconds_2dp" or "milliseconds_to_seconds_2dp_if_required" => .001,
+ "divide_by_ten" or "divide_by_ten_0dp" or "deciseconds_to_seconds" or "locations_to_metres" => .1,
+ "divide_by_two_0dp" => .5, "divide_by_five" => .2, "divide_by_one_thousand" => .001,
+ "double" => 2, "times_twenty" => 20, _ => null,
+ };
+ if (factor is null) return null;
+ scales[index - 1] *= factor.Value;
+ if (name.Contains("2dp", StringComparison.Ordinal)) precision[index - 1] = 2;
+ else if (name.Contains("1dp", StringComparison.Ordinal)) precision[index - 1] = 1;
+ else if (name.Contains("0dp", StringComparison.Ordinal)) precision[index - 1] = 0;
+ else if (name == "per_minute_to_per_second") precision[index - 1] = 2;
+ }
+ var output = new StringBuilder();
+ var bindings = new List();
+ void Literal(string text)
+ {
+ output.Append(text);
+ foreach (Match number in Number.Matches(text)) bindings.Add(new(-1, 1, double.Parse(number.Value, NumberStyles.Float, Invariant)));
+ }
+ int end = 0, automatic = 0;
+ foreach (Match placeholder in Placeholder.Matches(variant.Text))
+ {
+ Literal(variant.Text[end..placeholder.Index]);
+ int index = placeholder.Groups[1].Length == 0 ? automatic++ : int.Parse(placeholder.Groups[1].Value, Invariant);
+ if (index >= stats.Count) return null;
+ int position = positions.GetValueOrDefault(stats[index], -1);
+ double lo = position < 0 ? 0 : low[position] * scales[index], hi = position < 0 ? 0 : high[position] * scales[index];
+ string Num(double n) => n.ToString("0.########", Invariant);
+ string sign = placeholder.Groups[2].Value.Contains('+') && lo >= 0 ? "+" : "";
+ output.Append(sign).Append(lo == hi ? Num(lo) : "(" + Num(lo) + "-" + Num(hi) + ")");
+ bindings.Add(new(position, scales[index], Precision: precision[index]));
+ end = placeholder.Index + placeholder.Length;
+ }
+ Literal(variant.Text[end..]);
+ return output.ToString().Contains('{') ? null : new(output.ToString(), bindings.ToArray());
+ }
+
+ static bool Restrict(string condition, ref int low, ref int high)
+ {
+ if (condition == "#") return true;
+ if (condition.StartsWith('!'))
+ {
+ int excluded = int.Parse(condition[1..], Invariant);
+ if (low == excluded) low++;
+ if (high == excluded) high--;
+ }
+ else if (condition.Split('|') is { Length: 2 } range)
+ {
+ if (range[0] != "#") low = Math.Max(low, int.Parse(range[0], Invariant));
+ if (range[1] != "#") high = Math.Min(high, int.Parse(range[1], Invariant));
+ }
+ else { int exact = int.Parse(condition, Invariant); low = Math.Max(low, exact); high = Math.Min(high, exact); }
+ return low <= high;
+ }
+
+ static bool Holds(string condition, double value)
+ {
+ bool Bound(string s, bool lower) => s == "#" || double.TryParse(s, NumberStyles.Float, Invariant, out var n) && (lower ? value >= n : value <= n);
+ if (condition == "#") return true;
+ if (condition.StartsWith('!')) return double.TryParse(condition[1..], NumberStyles.Float, Invariant, out var n) && value != n;
+ var range = condition.Split('|');
+ return range.Length == 2 ? Bound(range[0], true) && Bound(range[1], false) : double.TryParse(condition, NumberStyles.Float, Invariant, out var exact) && value == exact;
+ }
+}
diff --git a/mods/pob/Converter/Source/NativeModels.cs b/mods/pob/Converter/Source/NativeModels.cs
new file mode 100644
index 0000000..766e328
--- /dev/null
+++ b/mods/pob/Converter/Source/NativeModels.cs
@@ -0,0 +1,188 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using GameServer.Core.Protocol.Instance;
+
+namespace GameServer.Core.Accounts
+{
+ public enum CharacterClass { Scion, Marauder, Ranger, Witch, Duelist, Templar, Shadow }
+}
+
+namespace GameServer.Core.Protocol.Instance
+{
+ public enum SocketColour : byte { Red = 1, Green = 2, Blue = 3, White = 4, Abyss = 5, Delve = 6 }
+ [Flags] public enum ItemInfluence : byte { None = 0, Shaper = 1, Elder = 2, Crusader = 4, Redeemer = 8, Hunter = 16, Warlord = 32 }
+ public enum ItemRarity : byte { Normal, Magic, Rare, Unique }
+ public enum ModSection : byte { Implicit = 4, Explicit = 5, Enchant = 6, Scourge = 10, Hidden = 11 }
+ public sealed record ItemSocket(SocketColour Colour, Item? Gem = null);
+ public sealed record ItemMod(ModSection Section, ushort Hash, IReadOnlyList Values);
+ // Export-time representation only. It neither runs gameplay nor serializes network messages.
+ public sealed record Item(uint TypeHash, IReadOnlyList Components, ushort VisualIdentity)
+ {
+ public const byte MaximumDefenceBaseRoll = 31, SpecialDefenceBaseRoll = 32;
+ public byte DefenceBaseRoll { get; init; }
+ public byte ItemLevel { get; init; } = 1;
+ public byte Quality { get; init; }
+ public byte MemoryStrands { get; init; }
+ public byte Intangibility { get; init; }
+ public byte? RelicStyle { get; init; }
+ public bool Vestigial { get; init; }
+ int? requiredLevel;
+ IReadOnlyList? requiredLevelMods;
+ IReadOnlyList? requiredLevelSockets;
+ public int? RequiredLevel
+ {
+ get => ReferenceEquals(Mods, requiredLevelMods) && ReferenceEquals(Sockets, requiredLevelSockets) ? requiredLevel : null;
+ init { requiredLevel = value; requiredLevelMods = Mods; requiredLevelSockets = Sockets; }
+ }
+ public byte? AlternateQualityType { get; init; }
+ public int Charges { get; init; }
+ public ushort StackSize { get; init; } = 1;
+ public IReadOnlyList Sockets { get; init; } = [];
+ public Item? OriginalItem { get; init; }
+ public bool NativeMods { get; init; }
+ public bool NativeSockets { get; init; }
+ public IReadOnlyList? Links { get; init; }
+ public int GemExperience { get; init; }
+ public int GemVariant { get; init; }
+ public byte GemFlags { get; init; }
+ public ItemRarity Rarity { get; init; }
+ public bool Identified { get; init; } = true;
+ public bool Corrupted { get; init; }
+ public byte FracturedCount { get; init; }
+ public bool Mirrored { get; init; }
+ public ItemInfluence Influences { get; init; }
+ public bool Split { get; init; }
+ public bool Synthesised { get; init; }
+ public IReadOnlyList Mods { get; init; } = [];
+ public IReadOnlyList NameWords { get; init; } = [];
+ static readonly HashSet Supported = ["Transformed", "Tincture", "LocalStats", "AttributeRequirements", "Weapon", "Usable", "Flask", "Quest", "Shield", "RenderItem", "Base", "Mods", "Armour", "Quality", "Sockets", "Charges", "Stack", "SkillGem", "Map", "MapKey"];
+ public static bool CanSerialize(IEnumerable components) => components.All(Supported.Contains);
+ }
+}
+
+static class CharacterSaves
+{
+ public sealed record SavedSocket(SocketColour Colour, SavedItem? Gem = null);
+ public sealed record SavedMod(string Id, ModSection Section, List Values);
+ // Exact upstream save fields. A server older than DefenceBaseRoll ignores it; a newer one reads a missing value as the minimum.
+ public sealed record SavedItem(uint Type, byte ItemLevel = 1, byte Quality = 0, int Charges = 0, ushort StackSize = 1,
+ List? Sockets = null, List? Links = null, int GemExperience = 0,
+ ItemRarity Rarity = ItemRarity.Normal, bool Identified = true, List? Mods = null, List? Name = null,
+ int GemVariant = 0, bool Corrupted = false, byte Fractured = 0, bool Mirrored = false, byte GemFlags = 0, ushort? Visual = null,
+ byte DefenceBaseRoll = 0, ItemInfluence Influences = ItemInfluence.None, bool Split = false, bool Synthesised = false, [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] SavedItem? OriginalItem = null)
+ {
+ public byte? AlternateQualityType { get; init; }
+ public byte MemoryStrands { get; init; }
+ public byte Intangibility { get; init; }
+ public byte? RelicStyle { get; init; }
+ public bool Vestigial { get; init; }
+ public int? RequiredLevel { get; init; }
+ }
+ public sealed record SavedPlacement(uint Id, byte X, byte Y, SavedItem Item);
+ // Tattoos: passive node -> tattoo item name; TattooKeystones: the keystone Journey Tattoo of Makanui granted, by node.
+ // Both are upstream save fields, omitted when empty so a save without tattoos is byte-for-byte what it was.
+ public sealed record Save(Dictionary> Inventories, Dictionary? SkillBar = null,
+ uint? Experience = null, List? Passives = null, List? Waypoints = null, List? Visited = null,
+ ushort? ExtraPassivePoints = null, Dictionary? MasteryEffects = null,
+ [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] Dictionary? Tattoos = null,
+ [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] Dictionary? TattooKeystones = null);
+ public static SavedItem ToSaved(Item item, ModCatalog mods) => new(item.TypeHash, item.ItemLevel, item.Quality,
+ item.Charges, item.StackSize, [.. item.Sockets.Select(s => new SavedSocket(s.Colour, s.Gem is null ? null : ToSaved(s.Gem, mods)))],
+ item.Links is null ? null : [.. item.Links], item.GemExperience, item.Rarity, item.Identified,
+ [.. item.Mods.Select(m => new SavedMod(mods.ByHash(m.Hash)?.Id ?? throw new ArgumentException("Unknown native modifier"), m.Section, [.. m.Values]))],
+ [.. item.NameWords], item.GemVariant, item.Corrupted, item.FracturedCount, item.Mirrored, item.GemFlags,
+ item.Rarity == ItemRarity.Unique ? item.VisualIdentity : null, item.DefenceBaseRoll, item.Influences, item.Split, item.Synthesised, item.OriginalItem is null ? null : ToSaved(item.OriginalItem, mods))
+ { AlternateQualityType = item.AlternateQualityType, MemoryStrands = item.MemoryStrands, Intangibility = item.Intangibility,
+ RequiredLevel = item.RequiredLevel, RelicStyle = item.RelicStyle, Vestigial = item.Vestigial };
+}
+
+static class ItemModStats
+{
+ public delegate int? ModifierValueRule(ItemMod mod, ModCatalog.Mod row, int statIndex, long ordinaryEffect);
+ public static Dictionary Local(Item item, ModCatalog mods)
+ {
+ var result = new Dictionary();
+ long All(string id) => item.Mods.Sum(m => mods.ByHash(m.Hash) is { } row
+ ? row.Stats.Select((s, i) => s.Id == id ? (long)m.Values[i] : 0).Sum() : 0);
+ long explicitEffect = All("local_explicit_mod_effect_+%"), prefix = All("local_prefix_mod_effect_+%"), suffix = All("local_suffix_mod_effect_+%");
+ var rule = GameServer.Modules.Game.HeistModifierMagnitudes.For(item, mods);
+ foreach (var mod in item.Mods)
+ if (mods.ByHash(mod.Hash) is { } row)
+ for (int i = 0; i < row.Stats.Count; i++)
+ if (row.Stats[i].Local)
+ {
+ long pct = mod.Section != ModSection.Explicit ? 0 : explicitEffect
+ + (row.GenerationType == 1 ? prefix : row.GenerationType == 2 ? suffix : 0);
+ string id = row.Stats[i].Id;
+ int value = id is "local_explicit_mod_effect_+%" or "local_prefix_mod_effect_+%" or "local_suffix_mod_effect_+%"
+ ? mod.Values[i] : rule?.Invoke(mod, row, i, pct)
+ ?? (int)Math.Clamp(Math.Floor((decimal)mod.Values[i] * (100 + pct) / 100), int.MinValue, int.MaxValue);
+ result[id] = ActorScale.Add(0, result.GetValueOrDefault(id), value);
+ }
+ return result;
+ }
+ public static int LevelRequirement(Item item, int dropLevel, ModCatalog mods)
+ {
+ var local = Local(item, mods);
+ if (local.GetValueOrDefault("local_level_requirement_override") is int over and not 0) return Math.Max(0, over);
+ int required = Math.Max(dropLevel, item.Mods.Select(m => (mods.ByHash(m.Hash)?.Level ?? 0) * 4 / 5).DefaultIfEmpty(0).Max());
+ return Math.Max(0, required + local.GetValueOrDefault("local_level_requirement_+"));
+ }
+}
+static class ActorScale
+{
+ public static int Add(uint key, int a, int b) => (int)Math.Clamp((long)a + b, int.MinValue, int.MaxValue);
+}
+static class PlayerInventories
+{
+ public const byte Flask = 11;
+ public static bool Accepts(byte row, string type) => row switch
+ {
+ 1 => type == "Body Armour", 4 => type == "Helmet", 5 => type == "Amulet", 6 or 7 or 102 => type == "Ring",
+ 8 => type == "Gloves", 9 => type == "Boots", 10 => type == "Belt",
+ 11 => type is "LifeFlask" or "ManaFlask" or "HybridFlask" or "UtilityFlask" or "UtilityFlaskCritical" or "Tincture",
+ 2 or 14 => Weapons.Contains(type), 3 or 15 => Weapons.Contains(type) || type is "Shield" or "Quiver", _ => false
+ };
+ static readonly HashSet Weapons = ["Wand", "Dagger", "Rune Dagger", "Claw", "One Hand Sword", "Thrusting One Hand Sword", "One Hand Axe", "One Hand Mace", "Sceptre", "Two Hand Sword", "Two Hand Axe", "Two Hand Mace", "Bow", "Staff", "Warstaff", "FishingRod"];
+}
+static class CurrencyEffects
+{
+ public static int SocketCapacity(Item item, ItemCatalog.BaseType type)
+ {
+ if (!item.Components.Contains("Sockets") || !type.Components.Contains("Sockets")) return 0;
+ int maximum = type.Class switch
+ {
+ "Body Armour" or "Bow" or "Staff" or "Warstaff" or "Two Hand Sword" or "Two Hand Axe" or "Two Hand Mace" or "FishingRod" => 6,
+ "Helmet" or "Gloves" or "Boots" => 4,
+ "Shield" or "Claw" or "Dagger" or "Rune Dagger" or "Wand" or "One Hand Sword" or "Thrusting One Hand Sword" or "One Hand Axe" or "One Hand Mace" or "Sceptre" => 3,
+ _ => 0
+ };
+ return Math.Min(maximum, type.Width * type.Height);
+ }
+}
+
+static class NativeGraph
+{
+ public static IReadOnlyDictionary Load(string folder) => NativeData.Shared("passive-graph", () => Read(folder));
+ static Dictionary Read(string folder)
+ {
+ using var doc = NativeData.Read(Path.Combine(folder, "passive-skill-graphs.json"));
+ if (doc.RootElement.GetProperty("revision").GetString() != "3.29.3c") throw new ArgumentException("Passive graph data must be 3.29.3c.");
+ return doc.RootElement.GetProperty("normal").GetProperty("nodes").EnumerateArray()
+ .ToDictionary(n => n.GetProperty("id").GetUInt32(), n => n.GetProperty("adjacent").EnumerateArray().Select(v => v.GetUInt32()).ToArray());
+ }
+}
+static class PathOfBuildingPassiveGraph
+{
+ public static HashSet Connected(uint start, IReadOnlyCollection allocated,
+ Func mastery, IReadOnlyDictionary graph)
+ {
+ var requested = allocated.Select(n => (uint)n).ToHashSet();
+ var reached = new HashSet { start }; var queue = new Queue(); queue.Enqueue(start);
+ while (queue.TryDequeue(out uint current))
+ if (current > ushort.MaxValue || !mastery((ushort)current))
+ foreach (uint next in graph.GetValueOrDefault(current) ?? [])
+ if (requested.Contains(next) && graph.ContainsKey(next) && reached.Add(next)) queue.Enqueue(next);
+ return allocated.Where(n => reached.Contains(n)).ToHashSet();
+ }
+}
diff --git a/mods/pob/Converter/Source/NativeNames.cs b/mods/pob/Converter/Source/NativeNames.cs
new file mode 100644
index 0000000..f4629da
--- /dev/null
+++ b/mods/pob/Converter/Source/NativeNames.cs
@@ -0,0 +1,47 @@
+using System.Text.Json;
+using GameServer.Core.Protocol.Instance;
+
+// One immutable catalogue per input data directory, shared by every item in a batch.
+static class NativeNames
+{
+ sealed record Word(int Index, string Text, string Alternate, uint Hash, int List);
+ sealed record Data(Word[] Prefixes, Dictionary Suffixes, Dictionary Uniques, Dictionary Visuals);
+ static readonly Dictionary Cache = new(StringComparer.OrdinalIgnoreCase);
+ static string Plain(string text) => string.Concat(text.Select(c => "àáâãäåèéêëìíîïòóôõöùúûüñçýÀÁÂÃÄÅÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÑÇÝ".IndexOf(c) is int i and >= 0
+ ? "aaaaaaeeeeiiiiooooouuuuncyAAAAAAEEEEIIIIOOOOOUUUUNCY"[i] : c));
+ static Data Load(string folder)
+ {
+ if (Cache.TryGetValue(folder, out var data)) return data;
+ using var words = NativeData.Read(Path.Combine(folder, "tables/Words.json"));
+ using var uniques = NativeData.Read(Path.Combine(folder, "tables/UniqueStashLayout.json"));
+ using var visuals = NativeData.Read(Path.Combine(folder, "tables/ItemVisualIdentity.json"));
+ var names = words.RootElement.EnumerateArray().Select((r, i) => new Word(i, r.GetProperty("Text").GetString() ?? "",
+ r.TryGetProperty("Text2", out var alt) ? alt.GetString() ?? "" : "", r.GetProperty("HASH32").GetUInt32(), r.GetProperty("Wordlist").GetInt32())).ToArray();
+ var art = new Dictionary();
+ foreach (var row in uniques.RootElement.EnumerateArray())
+ if (!row.TryGetProperty("IsAlternateArt", out var alt) || !alt.GetBoolean())
+ art.TryAdd(row.GetProperty("WordsKey").GetInt32(), (ushort)visuals.RootElement[row.GetProperty("ItemVisualIdentityKey").GetInt32()].GetProperty("HASH16").GetInt32());
+ var byName = names.Where(w => w.List == 6).SelectMany(w => new[] { (Key: Plain(w.Text), Word: w), (Key: Plain(w.Alternate), Word: w) })
+ .Where(p => p.Key.Length > 0).GroupBy(p => p.Key, StringComparer.OrdinalIgnoreCase)
+ .ToDictionary(g => g.Key, g => g.Select(p => p.Word).Distinct().ToArray(), StringComparer.OrdinalIgnoreCase);
+ return Cache[folder] = new(names.Where(w => w.List == 1).ToArray(),
+ names.Where(w => w.List == 2).GroupBy(w => w.Text).ToDictionary(g => g.Key, g => g.First()), byName, art);
+ }
+ public static Item WithName(Item item, string title, string folder, List warnings)
+ {
+ var data = Load(folder);
+ if (item.Rarity == ItemRarity.Unique)
+ {
+ if (title.StartsWith("Foulborn ", StringComparison.Ordinal)) title = title[9..];
+ var name = (data.Uniques.GetValueOrDefault(Plain(title)) ?? []).OrderByDescending(w => w.Text == title).FirstOrDefault()
+ ?? throw new PathOfBuildingUnsupportedException($"unique name '{title}' cannot be identified in this client");
+ if (!data.Visuals.TryGetValue(name.Index, out ushort art)) throw new PathOfBuildingUnsupportedException($"unique artwork for '{title}' is unavailable");
+ return item with { NameWords = [name.Hash], VisualIdentity = art };
+ }
+ foreach (var prefix in data.Prefixes.Where(w => title.StartsWith(w.Text, StringComparison.Ordinal)))
+ if (data.Suffixes.TryGetValue(title[prefix.Text.Length..], out var suffix))
+ return item with { NameWords = [prefix.Hash, suffix.Hash] };
+ warnings.Add($"Rare item name '{title}' has no native Words.dat name; its base name is used, with its stats preserved.");
+ return item;
+ }
+}
diff --git a/mods/pob/Converter/Source/NativeProgress.cs b/mods/pob/Converter/Source/NativeProgress.cs
new file mode 100644
index 0000000..812bee5
--- /dev/null
+++ b/mods/pob/Converter/Source/NativeProgress.cs
@@ -0,0 +1,30 @@
+using System.Text.Json;
+using GameServer.Core.Imports;
+
+static class NativeProgress
+{
+ sealed record Node(int Ascendancy, int Points);
+ static readonly Dictionary Ascendancies, Dictionary Nodes)> Cache = new();
+ public static int AscendancyPoints(PathOfBuildingBuild build, string folder)
+ {
+ if (!Cache.TryGetValue(folder, out var data))
+ {
+ using var asc = NativeData.Read(Path.Combine(folder, "tables/Ascendancy.json"));
+ var names = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ int index = 0;
+ foreach (var row in asc.RootElement.EnumerateArray())
+ {
+ names.TryAdd(row.GetProperty("Id").GetString()!, index);
+ names.TryAdd(row.GetProperty("Name").GetString()!, index++);
+ }
+ using var passives = NativeData.Read(Path.Combine(folder, "tables/PassiveSkills.json"));
+ var nodes = new Dictionary();
+ foreach (var row in passives.RootElement.EnumerateArray())
+ if (row.GetProperty("AscendancyKey") is { ValueKind: JsonValueKind.Number } key && !row.GetProperty("IsAscendancyStartingNode").GetBoolean())
+ nodes.TryAdd(row.GetProperty("PassiveSkillGraphId").GetUInt32(), new(key.GetInt32(), row.GetProperty("SkillPointsGranted").GetInt32()));
+ data = (names, nodes); Cache[folder] = data;
+ }
+ if (build.Ascendancy is null || !data.Ascendancies.TryGetValue(build.Ascendancy, out int selected)) return 0;
+ return build.Tree.Nodes.Distinct().Where(id => data.Nodes.TryGetValue(id, out var node) && node.Ascendancy == selected).Sum(id => data.Nodes[id].Points);
+ }
+}
diff --git a/mods/pob/Converter/Source/NativeSource.cs b/mods/pob/Converter/Source/NativeSource.cs
new file mode 100644
index 0000000..ada80bd
--- /dev/null
+++ b/mods/pob/Converter/Source/NativeSource.cs
@@ -0,0 +1,304 @@
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using System.IO.Compression;
+using System.Xml.Linq;
+using GameServer.Core.Imports;
+using GameServer.Core.Protocol.Instance;
+
+// The downloaded ninja response retains native modifier IDs/values and physical socket
+// indexes which its PoB export omits (notably Energy Blade's computed lightning implicit).
+// Accept a response only when its complete PoB code matches the requested build.
+static class NativeSource
+{
+ static JsonDocument? document;
+ static Dictionary items = new(StringComparer.Ordinal);
+ static Dictionary definitions = new(StringComparer.Ordinal);
+ static readonly Dictionary identities = new(StringComparer.Ordinal);
+ static readonly List partialDocuments = [];
+ static readonly HashSet partialItems = new(StringComparer.Ordinal);
+ internal static Action>? SnapshotLoaded { get; set; }
+ static Dictionary? index;
+ public static string? SourcePath { get; private set; }
+ public static int ResolvedItems { get; private set; }
+ public static bool Available => SourcePath is not null;
+
+ static string? Find(string code, string? sourceFile)
+ {
+ if (!string.IsNullOrWhiteSpace(sourceFile)) return sourceFile;
+ string path = Environment.GetEnvironmentVariable("POB_SOURCE_INDEX") ?? "data/pob-import/source-index.json";
+ index ??= File.Exists(path) ? JsonSerializer.Deserialize>(File.ReadAllBytes(path))! : [];
+ var source = index.GetValueOrDefault(Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(code.Trim()))));
+ return source is not null && File.Exists(source) ? source : null;
+ }
+
+ public static PathOfBuildingBuild Parse(string code, string? sourceFile)
+ {
+ try { return PathOfBuilding.Parse(code); }
+ catch (FormatException e) when (e.Message.Contains("A gem has no name or identity.") && Find(code, sourceFile) is { } path)
+ {
+ using var source = JsonDocument.Parse(File.ReadAllBytes(path));
+ if (source.RootElement.GetProperty("pob").GetString()?.Trim() != code.Trim()) throw;
+ // The strict parser has already validated the XML/size; ninja sometimes exports empty
+ // calculation placeholders. Physical gems are restored by socket index from this exact snapshot.
+ string xml = code.Trim();
+ if (!xml.StartsWith('<'))
+ {
+ string b64 = xml.Replace('-', '+').Replace('_', '/');
+ using var input = new MemoryStream(Convert.FromBase64String(b64.PadRight((b64.Length + 3) / 4 * 4, '=')));
+ using var zipped = new ZLibStream(input, CompressionMode.Decompress);
+ using var reader = new StreamReader(zipped, Encoding.UTF8);
+ xml = reader.ReadToEnd();
+ }
+ var document = XDocument.Parse(xml);
+ document.Descendants("Gem").Where(g => new[] { "nameSpec", "gemId", "skillId" }.All(a => string.IsNullOrWhiteSpace((string?)g.Attribute(a)))).Remove();
+ return PathOfBuilding.Parse(document.ToString());
+ }
+ }
+
+ public static void Begin(string code, PathOfBuildingBuild build, string? sourceFile)
+ {
+ document?.Dispose(); document = null;
+ foreach (var partial in partialDocuments) partial.Dispose();
+ partialDocuments.Clear(); partialItems.Clear();
+ items.Clear(); definitions.Clear(); identities.Clear(); SourcePath = null; ResolvedItems = 0;
+ foreach (var definition in build.Items)
+ if (UniqueId(definition.Text) is { } id) definitions.TryAdd(id, definition);
+ sourceFile = Find(code, sourceFile);
+ if (sourceFile is not null)
+ {
+ document = JsonDocument.Parse(File.ReadAllBytes(sourceFile));
+ if (document.RootElement.GetProperty("pob").GetString()?.Trim() != code.Trim())
+ throw new ArgumentException("The native snapshot belongs to a different PoB code.");
+ SourcePath = sourceFile;
+ Visit(document.RootElement.GetProperty("build"));
+ }
+ // A complete export can retain an unallocated jewel absent from its current API equipment.
+ // Resolve missing items by the exact fingerprint, never by UID alone, without foreign sockets or trees.
+ var sources = new Dictionary Items)>();
+ var needed = build.Slots.Select(s => s.ItemId).Concat(build.Tree.Jewels.Select(j => j.ItemId)).ToHashSet();
+ foreach (var definition in build.Items.Where(d => needed.Contains(d.Id)))
+ {
+ if (UniqueId(definition.Text) is not { } id || items.ContainsKey(id)
+ || NativeItemSources.Find(definition) is not { } path || !File.Exists(path)) continue;
+ if (!sources.TryGetValue(path, out var native))
+ {
+ var source = JsonDocument.Parse(File.ReadAllBytes(path));
+ partialDocuments.Add(source);
+ string original = source.RootElement.GetProperty("pob").GetString()!;
+ native = (Parse(original, path), []);
+ VisitInto(source.RootElement.GetProperty("build"), native.Items);
+ sources[path] = native;
+ }
+ if (!native.Build.Items.Any(i => UniqueId(i.Text) == id && NativeItemSources.Key(i) == NativeItemSources.Key(definition))) continue;
+ if (native.Items.TryGetValue(id, out var row)) { items[id] = row; partialItems.Add(id); }
+ }
+ if (SourcePath is { } complete) SnapshotLoaded?.Invoke(complete, build, items);
+ }
+
+ static void Visit(JsonElement node)
+ => VisitInto(node, items);
+ static void VisitInto(JsonElement node, Dictionary target)
+ {
+ if (node.ValueKind == JsonValueKind.Object)
+ {
+ if (node.TryGetProperty("id", out var id) && id.ValueKind == JsonValueKind.String
+ && node.TryGetProperty("baseType", out _)) target.TryAdd(id.GetString()!, node);
+ foreach (var property in node.EnumerateObject()) VisitInto(property.Value, target);
+ }
+ else if (node.ValueKind == JsonValueKind.Array)
+ foreach (var child in node.EnumerateArray()) VisitInto(child, target);
+ }
+
+ static string? UniqueId(string text)
+ {
+ if (identities.TryGetValue(text, out var id)) return id;
+ return identities[text] = Regex.Match(text, @"(?m)^Unique ID: ([^\r\n]+)") is { Success: true } m ? m.Groups[1].Value.Trim() : null;
+ }
+ static bool Flag(JsonElement row, string field) => row.TryGetProperty(field, out var p) && p.ValueKind == JsonValueKind.True;
+ public static bool HasExactMods(PathOfBuildingItem definition) => UniqueId(definition.Text) is { } id && items.TryGetValue(id, out var row)
+ && row.TryGetProperty("mods", out var mods) && mods.ValueKind == JsonValueKind.Object;
+ public static string? BaseName(PathOfBuildingItem definition) => UniqueId(definition.Text) is { } id && items.TryGetValue(id, out var row)
+ ? row.GetProperty("baseType").GetString() : null;
+ public static (string Name, int Value)? Quality(PathOfBuildingItem definition)
+ {
+ if (UniqueId(definition.Text) is not { } id || !items.TryGetValue(id, out var row) || !row.TryGetProperty("properties", out var properties)) return null;
+ foreach (var property in properties.EnumerateArray())
+ if (property.GetProperty("name").GetString() is { } name && name.StartsWith("Quality (", StringComparison.Ordinal)
+ && Regex.Match(property.GetProperty("values")[0][0].GetString()!, @"\d+") is { Success: true } number)
+ return (name, int.Parse(number.Value));
+ return null;
+ }
+
+ public static IReadOnlyDictionary? Defences(PathOfBuildingItem definition)
+ {
+ if (UniqueId(definition.Text) is not { } id || !items.TryGetValue(id, out var row)
+ || !row.TryGetProperty("properties", out var properties)) return null;
+ var result = new Dictionary();
+ foreach (var property in properties.EnumerateArray())
+ {
+ string name = property.GetProperty("name").GetString() ?? "";
+ string? key = name switch { "Armour" => "Armour", "Evasion Rating" => "Evasion", "Energy Shield" => "EnergyShield", "Ward" => "Ward", _ => null };
+ if (key is not null && int.TryParse(property.GetProperty("values")[0][0].GetString(), out int value)) result.Add(key, value);
+ }
+ return result.Count == 0 ? null : result;
+ }
+
+ public static ItemCatalog.BaseType[] IdentifyBases(PathOfBuildingItem definition, ItemCatalog.BaseType[] candidates, string folder)
+ {
+ if (UniqueId(definition.Text) is not { } id || !items.TryGetValue(id, out var row)) return candidates;
+ if (row.TryGetProperty("mods", out var sections) && sections.TryGetProperty("implicit", out var list))
+ {
+ var implicitIds = list.EnumerateArray().Select(m => m.GetProperty("id").GetString()).ToHashSet();
+ var matching = candidates.Where(b => b.Implicits is { Count: > 0 } && b.Implicits.All(m => implicitIds.Contains(m.Id))).ToArray();
+ if (matching.Length > 0) candidates = matching;
+ }
+ if (candidates.Length > 1 && row.TryGetProperty("mods", out var allMods)
+ && allMods.TryGetProperty("enchant", out var enchants)
+ && enchants.EnumerateArray().Any(m => m.GetProperty("id").GetString()!.StartsWith("TalismanEnchant", StringComparison.Ordinal)))
+ {
+ var talismans = NativeData.Shared("talisman-base-rows", () =>
+ {
+ using var bases = NativeData.Read(Path.Combine(folder, "tables", "BaseItemTypes.json"));
+ return bases.RootElement.EnumerateArray().Select((b, i) => (b, i))
+ .Where(p => p.b.GetProperty("TalismanEnchants").GetArrayLength() > 0).Select(p => p.i).ToHashSet();
+ });
+ var matching = candidates.Where(b => talismans.Contains(b.Row)).ToArray();
+ if (matching.Length > 0) candidates = matching;
+ }
+ if (candidates.Length > 1 && row.TryGetProperty("icon", out var icon) && Uri.TryCreate(icon.GetString(), UriKind.Absolute, out var uri))
+ {
+ string name = Path.GetFileNameWithoutExtension(uri.AbsolutePath);
+ var icons = NativeData.Shared("base-icons", () =>
+ {
+ using var visuals = NativeData.Read(Path.Combine(folder, "tables", "ItemVisualIdentity.json"));
+ return visuals.RootElement.EnumerateArray().ToDictionary(v => v.GetProperty("HASH16").GetInt32(),
+ v => Path.GetFileNameWithoutExtension((v.GetProperty("DDSFile").GetString() ?? "").Replace('/', Path.DirectorySeparatorChar)));
+ });
+ var matching = candidates.Where(b => string.Equals(icons.GetValueOrDefault(b.VisualIdentity), name, StringComparison.OrdinalIgnoreCase)).ToArray();
+ if (matching.Length > 0) candidates = matching;
+ }
+ // Corrupted and unique text exports can identify only a base family: their replaced innate implicit
+ // and unique art no longer identify a variant. Canonicalize only equivalent non-weapon families;
+ // full native modifiers and the recorded requirement replace the family's defaults.
+ if (candidates.Length > 1 && row.TryGetProperty("mods", out _)
+ && (Flag(row, "corrupted") || row.TryGetProperty("frameTypeId", out var rarity)
+ && (rarity.ValueKind == JsonValueKind.Number && rarity.GetInt32() == 3
+ || rarity.ValueKind == JsonValueKind.String && rarity.GetString() is "Unique" or "Relic" or "SupporterFoil"))
+ && candidates.All(b => b.Class is "Ring" or "Amulet" or "Quiver")
+ && candidates.Select(b => (b.Class, b.Width, b.Height, b.ModDomain)).Distinct().Count() == 1
+ && candidates.All(b => b.Components.SequenceEqual(candidates[0].Components)))
+ candidates = [candidates.OrderBy(b => b.DropLevel).ThenBy(b => b.Row).First()];
+ return candidates;
+ }
+
+ public static Item Apply(PathOfBuildingItem definition, ItemCatalog.BaseType type, Item item, ItemCatalog catalog, string folder, List warnings)
+ {
+ try { return ApplyCore(definition, type, item, catalog, folder, warnings); }
+ catch (Exception e) when (e is ArgumentException or PathOfBuildingUnsupportedException)
+ { throw new InvalidDataException($"Native snapshot of {type.Name}: {e.Message}", e); }
+ }
+
+ static Item ApplyCore(PathOfBuildingItem definition, ItemCatalog.BaseType type, Item item, ItemCatalog catalog, string folder, List warnings)
+ {
+ if (UniqueId(definition.Text) is not { } id || !items.TryGetValue(id, out var row))
+ {
+ if (type.Components.Contains("Transformed")) throw new ArgumentException("PoB omits Energy Blade's calculated damage; a matching downloaded native snapshot is required.");
+ return item;
+ }
+ if (row.TryGetProperty("mods", out var sections) && sections.ValueKind == JsonValueKind.Object)
+ {
+ var native = new List();
+ var fractured = new HashSet();
+ foreach (var section in sections.EnumerateObject())
+ {
+ ModSection target = section.Name switch
+ {
+ "implicit" => ModSection.Implicit, "explicit" or "crafted" or "fractured" or "veiled" => ModSection.Explicit,
+ "enchant" => ModSection.Enchant, "scourge" => ModSection.Scourge,
+ "crucible" => ModSection.Enchant,
+ _ => throw new ArgumentException($"Unknown native modifier section '{section.Name}' on {type.Name}.")
+ };
+ foreach (var entry in section.Value.EnumerateArray())
+ {
+ string modId = entry.GetProperty("id").GetString()!;
+ var mod = catalog.Mods.ById(modId) ?? throw new ArgumentException($"Native modifier '{modId}' is absent from this client.");
+ var placement = section.Name == "crafted" ? mod.GenerationType == 10 ? ModSection.Enchant
+ : mod.Domain == 42 ? ModSection.Implicit : ModSection.Explicit : target;
+ var stats = entry.GetProperty("stats");
+ // The supported client renamed Aylardex's single cosmetic stat. Its mod ID and
+ // fixed value are unchanged; migrate that key only, not arbitrary unknown stats.
+ string NativeKey(string key) => modId == "PowerChargeArtVariationUnique__1" && key == "power_charge_art_variation"
+ ? "power_charge_art_variation_aylardex" : key;
+ var namedStats = stats.EnumerateObject().ToDictionary(s => NativeKey(s.Name), s => s.Value);
+ var values = mod.Stats.Select(s => namedStats.TryGetValue(s.Id, out var value) && value.TryGetInt32(out int v)
+ ? v : throw new ArgumentException($"Native modifier '{modId}' omits integer stat '{s.Id}'.")).ToArray();
+ if (namedStats.Any(s => !mod.Stats.Any(m => m.Id == s.Key)))
+ throw new ArgumentException($"Native modifier '{modId}' has a different stat layout.");
+ native.Add(new(placement, mod.Hash, values));
+ if (section.Name == "fractured") fractured.Add(mod.Hash);
+ }
+ }
+ item = item with { Mods = [.. native.Where(m => fractured.Contains(m.Hash)), .. native.Where(m => !fractured.Contains(m.Hash))],
+ NativeMods = true, FracturedCount = checked((byte)native.Count(m => m.Section == ModSection.Explicit && fractured.Contains(m.Hash))) };
+ warnings.RemoveAll(w => w.StartsWith("Skipped modifier", StringComparison.Ordinal) || w.Contains("kept a value beyond the native roll"));
+ }
+ ItemInfluence influences = ItemInfluence.None;
+ if (row.TryGetProperty("influences", out var influenceRows))
+ foreach (var name in Enum.GetNames().Where(n => n != "None"))
+ if (Flag(influenceRows, name.ToLowerInvariant())) influences |= Enum.Parse(name);
+ item = item with { Corrupted = Flag(row, "corrupted"), Mirrored = Flag(row, "duplicated"),
+ Split = Flag(row, "split"), Synthesised = Flag(row, "synthesised"), Influences = influences,
+ Vestigial = item.Vestigial || Flag(row, "vestigial") };
+ warnings.RemoveAll(w => w.Contains("skipped influence identity"));
+ if (!partialItems.Contains(id) && type.Components.Contains("Sockets") && row.TryGetProperty("sockets", out var socketRows))
+ {
+ var sockets = new List(); var links = new List(); int previousGroup = -1;
+ foreach (var socket in socketRows.EnumerateArray())
+ {
+ string colour = socket.GetProperty("sColour").GetString()!;
+ var nativeColour = colour switch { "R" => SocketColour.Red, "G" => SocketColour.Green, "B" => SocketColour.Blue,
+ "W" => SocketColour.White, "A" => SocketColour.Abyss, _ => throw new ArgumentException($"Unknown socket colour '{colour}'.") };
+ int group = socket.GetProperty("group").GetInt32();
+ if (group == previousGroup) links[^1]++;
+ else { links.Add(1); previousGroup = group; }
+ sockets.Add(new(nativeColour));
+ }
+ foreach (var child in row.GetProperty("socketedItems").EnumerateArray())
+ {
+ int slot = child.GetProperty("socket").GetInt32();
+ if (slot < 0 || slot >= sockets.Count || sockets[slot].Gem is not null) throw new ArgumentException("Invalid native socket index.");
+ Item content;
+ if (Flag(child, "abyssJewel"))
+ {
+ if (sockets[slot].Colour != SocketColour.Abyss) throw new ArgumentException("A native abyss jewel occupies a gem socket.");
+ string childId = child.GetProperty("id").GetString()!;
+ if (!definitions.TryGetValue(childId, out var jewel)) throw new ArgumentException($"PoB omits native socketed jewel '{childId}'.");
+ content = PathOfBuildingItems.ParseItem(jewel, catalog, folder, warnings).Item;
+ }
+ else
+ {
+ if (sockets[slot].Colour == SocketColour.Abyss) throw new ArgumentException("A native skill gem occupies an abyss socket.");
+ content = PathOfBuildingItems.CreateGem(new(child.GetProperty("baseType").GetString()!, null, null, null,
+ Property(child, "Level", 1), Property(child, "Quality", 0), true), catalog, folder);
+ }
+ sockets[slot] = sockets[slot] with { Gem = content };
+ }
+ item = item with { Sockets = sockets, Links = links, NativeSockets = true };
+ }
+ ResolvedItems++;
+ return item;
+ }
+
+ static int Property(JsonElement row, string name, int fallback)
+ {
+ foreach (var p in row.GetProperty("properties").EnumerateArray())
+ if (p.GetProperty("name").GetString() == name)
+ {
+ var text = p.GetProperty("values")[0][0].GetString()!;
+ if (Regex.Match(text, @"\d+") is { Success: true } match) return int.Parse(match.Value);
+ }
+ return fallback;
+ }
+}
diff --git a/mods/pob/Converter/Source/PassiveTree.cs b/mods/pob/Converter/Source/PassiveTree.cs
new file mode 100644
index 0000000..7ca08af
--- /dev/null
+++ b/mods/pob/Converter/Source/PassiveTree.cs
@@ -0,0 +1,152 @@
+// Adapted from LocalExile feature/pob-import, 5394de0a. See NOTICE.md.
+using System.Text.Json;
+
+///
+/// The passive skill tree's nodes: PassiveSkills.dat rows by PassiveSkillGraphId (the id the client allocates and S→C
+/// 0x3d lists), with their stats (Stats.dat rows + 1 = the client's stat keys) and the skill points they grant. Game data:
+/// data/tables/PassiveSkills.json, loaded on first use. OrdinaryPassiveRules validates ordinary connectivity against
+/// the selected generated PSG topology; AscendancyRules validates the separate ascendancy allocation.
+/// Masteries: PassiveSkillMasteryGroups.dat groups a mastery node's options and PassiveSkillMasteryEffects.dat holds the
+/// effects' stats. The client's 0x3d list carries the selected effects as node | effect << 16; the effect is the
+/// effect row's HASH16 (the value in the client's passive tree data), not its data-table row index.
+/// Gold respec (Bestel's Respecialisation): a node costs VillageBalancePerLevelShared.dat's GoldRespecCost at the
+/// character's level times the node's multiplier, as the client's per-node cost 0x141efb140 computes it.
+///
+sealed class PassiveTree(string folder = "data", bool ruthless = false)
+{
+ public sealed record Node(ushort GraphId, string Id, string Name, IReadOnlyList<(uint Key, int Value)> Stats, int PointsGranted,
+ bool IsAscendancy, bool IsStart, int MasteryGroup, int RespecMultiplier = 1);
+
+ public sealed record MasteryEffect(int Row, ushort Hash, string Id, IReadOnlyList<(uint Key, int Value)> Stats);
+
+ private readonly Lazy> _nodes = new(() => LoadNodes(folder, ruthless));
+ private readonly Lazy> _effects = new(() => LoadEffects(folder));
+ private readonly Lazy>> _groups = new(() => LoadGroups(folder, LoadEffects(folder)));
+ private readonly Lazy> _respecCosts = new(() => LoadRespecCosts(folder));
+
+ public Node? Find(ushort graphId) => _nodes.Value.GetValueOrDefault(graphId);
+
+ public bool Loaded => _nodes.Value.Count > 0;
+
+ /// The effects a mastery node offers, in the table's order (the client shows them in this order).
+ public IReadOnlyList EffectsFor(ushort graphId) =>
+ Find(graphId) is { MasteryGroup: >= 0 } node && _groups.Value.TryGetValue(node.MasteryGroup, out var effects)
+ ? effects : [];
+
+ /// The effect by the client's HASH16, falling back to the data-table row index.
+ public MasteryEffect? FindEffect(int id) =>
+ _effects.Value.Values.FirstOrDefault(e => e.Hash == id) ?? _effects.Value.GetValueOrDefault(id);
+
+ /// The skill points the allocated nodes grant themselves (the client counts them as extra points).
+ public int PointsGranted(IEnumerable nodes) => nodes.Sum(n => Find(n)?.PointsGranted ?? 0);
+
+ ///
+ /// The gold a respec of these nodes costs at the character's level (client 0x141efb140): GoldRespecCost of the
+ /// VillageBalancePerLevelShared.dat row for the level, times each node's multiplier (1; 0 for a multiple-choice
+ /// node; an expansion node's own value). Ascendancy nodes are not part of a gold respec (the client's full cost
+ /// skips them too). Unknown nodes cost nothing.
+ ///
+ public long GoldRespecCost(IEnumerable nodes, int level)
+ {
+ long perNode = _respecCosts.Value.GetValueOrDefault(level);
+ return nodes.Sum(n => Find(n) is { IsAscendancy: false } node ? perNode * node.RespecMultiplier : 0);
+ }
+
+ /// The allocated nodes' stats, with their selected mastery effects, summed by key.
+ public Dictionary Stats(IEnumerable nodes, IReadOnlyDictionary? masteries = null)
+ {
+ var sum = new Dictionary();
+ foreach (var n in nodes)
+ {
+ if (Find(n) is { } node)
+ foreach (var (k, v) in node.Stats) sum[k] = ActorScale.Add(k, sum.GetValueOrDefault(k), v);
+ if (masteries is not null && masteries.TryGetValue(n, out var effect) && FindEffect(effect) is { } mastery)
+ foreach (var (k, v) in mastery.Stats) sum[k] = ActorScale.Add(k, sum.GetValueOrDefault(k), v);
+ }
+ return sum;
+ }
+
+ /// Whether the effect belongs to the mastery node's group (the client only offers those).
+ public bool IsEffectFor(ushort graphId, MasteryEffect effect) =>
+ EffectsFor(graphId).Any(e => e.Row == effect.Row && e.Hash == effect.Hash);
+
+ private static Dictionary LoadNodes(string folder, bool ruthless)
+ {
+ string path = Path.Combine(folder, "tables", "PassiveSkills.json");
+ var nodes = new Dictionary();
+ if (!NativeData.Exists(path)) return nodes;
+ using var d = NativeData.Read(path);
+ foreach (var r in d.RootElement.EnumerateArray())
+ {
+ int graphId = r.GetProperty("PassiveSkillGraphId").GetInt32();
+ if (graphId is <= 0 or > ushort.MaxValue) continue;
+ // The mode flag is per catalog, never global: regular and Ruthless characters may be online together.
+ // A marked alternate replaces the entire vector, including an empty vector or explicit zero values.
+ bool alternate = ruthless && r.TryGetProperty("HasHardmodeAlternate", out var hardmode) && hardmode.GetBoolean();
+ var keys = r.GetProperty(alternate ? "StatsHardmode" : "Stats").EnumerateArray().Select(s => s.GetInt32()).ToList();
+ var stats = new List<(uint, int)>();
+ for (int i = 0; i < keys.Count && i < 5; i++)
+ stats.Add(((uint)keys[i] + 1, r.GetProperty($"Stat{i + 1}Value{(alternate ? "Hardmode" : "")}").GetInt32()));
+ int masteryGroup = r.TryGetProperty("MasteryGroup", out var group) && group.ValueKind == JsonValueKind.Number
+ ? group.GetInt32() : -1;
+ // The client's multiplier: an expansion node's own value (unnamed column at +0xb2), 0 for a multiple-choice node.
+ int respec = r.GetProperty("IsExpansion").GetBoolean() ? r.GetProperty("__col26").GetInt32()
+ : r.GetProperty("IsMultipleChoice").GetBoolean() ? 0 : 1;
+ string name = r.GetProperty("Name").GetString() ?? "";
+ if (alternate && r.GetProperty("NameHardmode").GetString() is { Length: > 0 } alternateName) name = alternateName;
+ nodes.TryAdd((ushort)graphId, new Node((ushort)graphId, r.GetProperty("Id").GetString() ?? "", name,
+ stats, r.GetProperty(alternate ? "SkillPointsGrantedHardmode" : "SkillPointsGranted").GetInt32(), r.GetProperty("AscendancyKey").ValueKind == JsonValueKind.Number,
+ r.GetProperty("Characters").GetArrayLength() > 0, masteryGroup, respec));
+ }
+ return nodes;
+ }
+
+ private static Dictionary LoadRespecCosts(string folder)
+ {
+ string path = Path.Combine(folder, "tables", "VillageBalancePerLevelShared.json");
+ var costs = new Dictionary();
+ if (!NativeData.Exists(path)) return costs;
+ using var d = NativeData.Read(path);
+ // The client looks the row up by its first column (the level, 1–100).
+ foreach (var r in d.RootElement.EnumerateArray())
+ costs[r.GetProperty("MaxAccountLevel").GetInt32()] = r.GetProperty("GoldRespecCost").GetInt32();
+ return costs;
+ }
+
+ private static Dictionary LoadEffects(string folder)
+ {
+ string path = Path.Combine(folder, "tables", "PassiveSkillMasteryEffects.json");
+ var effects = new Dictionary();
+ if (!NativeData.Exists(path)) return effects;
+ using var d = NativeData.Read(path);
+ int row = 0;
+ foreach (var r in d.RootElement.EnumerateArray())
+ {
+ var keys = r.GetProperty("Stats").EnumerateArray().Select(s => s.GetInt32()).ToList();
+ var stats = new List<(uint, int)>();
+ for (int i = 0; i < keys.Count && i < 3; i++)
+ stats.Add(((uint)keys[i] + 1, r.GetProperty($"Stat{i + 1}Value").GetInt32()));
+ int hash = r.GetProperty("HASH16").GetInt32();
+ effects[row] = new MasteryEffect(row, (ushort)hash, r.GetProperty("Id").GetString() ?? "", stats);
+ row++;
+ }
+ return effects;
+ }
+
+ private static Dictionary> LoadGroups(string folder, Dictionary effects)
+ {
+ string path = Path.Combine(folder, "tables", "PassiveSkillMasteryGroups.json");
+ var groups = new Dictionary>();
+ if (!NativeData.Exists(path)) return groups;
+ using var d = NativeData.Read(path);
+ int row = 0;
+ foreach (var r in d.RootElement.EnumerateArray())
+ {
+ var list = new List();
+ foreach (var e in r.GetProperty("MasteryEffects").EnumerateArray())
+ if (effects.TryGetValue(e.GetInt32(), out var effect)) list.Add(effect);
+ groups[row++] = list;
+ }
+ return groups;
+ }
+}
diff --git a/mods/pob/Converter/Source/PathOfBuilding.cs b/mods/pob/Converter/Source/PathOfBuilding.cs
new file mode 100644
index 0000000..dd416bb
--- /dev/null
+++ b/mods/pob/Converter/Source/PathOfBuilding.cs
@@ -0,0 +1,391 @@
+// Adapted from LocalExile feature/pob-import, 5394de0a. See NOTICE.md.
+using System.Collections.ObjectModel;
+using System.Buffers.Binary;
+using System.Globalization;
+using System.IO.Compression;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Xml;
+using System.Xml.Linq;
+using GameServer.Core.Accounts;
+
+namespace GameServer.Core.Imports;
+
+public sealed record PathOfBuildingBuild(CharacterClass Class, int Level, PathOfBuildingTree Tree,
+ IReadOnlyList Items, IReadOnlyList Slots,
+ IReadOnlyList Skills, string? Ascendancy, bool UseSecondWeaponSet = false,
+ string? Bandit = null, string? PantheonMajor = null, string? PantheonMinor = null);
+public sealed record PathOfBuildingTree(int ClassId, int AscendancyId, string? Version, IReadOnlyList Nodes,
+ IReadOnlyDictionary Masteries, IReadOnlyList Jewels,
+ IReadOnlyList