diff --git a/UoFiddler.Plugin.MultiEditor/Classes/HouseStyles.cs b/UoFiddler.Plugin.MultiEditor/Classes/HouseStyles.cs
deleted file mode 100644
index 0d2d73d5..00000000
--- a/UoFiddler.Plugin.MultiEditor/Classes/HouseStyles.cs
+++ /dev/null
@@ -1,442 +0,0 @@
-/***************************************************************************
- *
- * $Author: Turley
- *
- * "THE BEER-WARE LICENSE"
- * As long as you retain this notice you can do whatever you want with
- * this stuff. If we meet some day, and you think this stuff is worth it,
- * you can buy me a beer in return.
- *
- ***************************************************************************/
-
-using System;
-using System.Collections.Generic;
-using UoFiddler.Controls.Classes.TilesInfo;
-
-namespace UoFiddler.Plugin.MultiEditor.Classes
-{
- internal enum HousePartKind
- {
- Wall,
- Floor,
- Door,
- Stair,
- Roof,
- Misc,
- Teleporter
- }
-
- ///
- /// One row of a client house design table (walls.txt, floors.txt ...): a named set of pieces,
- /// each under the column label the client uses (South1, Corner, F3, MultiNorth ...).
- ///
- internal sealed class HouseStyle
- {
- private readonly Dictionary _slots = new Dictionary();
-
- public HouseStyle(HousePartKind kind, string group, string name)
- {
- Kind = kind;
- Group = group;
- Name = name;
- }
-
- public HousePartKind Kind { get; }
-
- /// The category name (the first style's comment), grouping a material's styles.
- public string Group { get; }
-
- public string Name { get; }
-
- public IReadOnlyDictionary Slots => _slots;
-
- /// A piece to show for the style in lists.
- public ushort IconId { get; private set; }
-
- /// The piece under a column label, or 0 when the style has none.
- public ushort Get(string label) => _slots.TryGetValue(label, out ushort id) ? id : (ushort)0;
-
- internal void Add(string label, ushort id)
- {
- _slots[label] = id;
- if (IconId == 0)
- {
- IconId = id;
- }
- }
-
- public override string ToString() => Name;
- }
-
- ///
- /// The client's house design tables, read once per client, with a lookup from tile id to the
- /// style and column it belongs to.
- ///
- internal sealed class HouseStyles
- {
- private static readonly Dictionary _kinds = new Dictionary
- {
- ["Walls"] = HousePartKind.Wall,
- ["Floors"] = HousePartKind.Floor,
- ["Doors"] = HousePartKind.Door,
- ["Stairs"] = HousePartKind.Stair,
- ["Roof"] = HousePartKind.Roof,
- ["Misc"] = HousePartKind.Misc,
- ["Teleporters"] = HousePartKind.Teleporter
- };
-
- private readonly Dictionary _roles = new Dictionary();
-
- // Listed pieces by art hash, for tiles that copy one under another id. Filled on first use.
- private Dictionary _listedByArt;
-
- // Stair corner pieces: the set of four each belongs to and its place in it. Filled on first use.
- private Dictionary _stairCorners;
-
- private HouseStyles()
- {
- }
-
- public List Styles { get; } = new List();
-
- public List Errors { get; } = new List();
-
- ///
- /// Reads the tables. With a floors.txt row, which is a
- /// palette of up to 16 tiles often in several colours, becomes one style per colour, so a
- /// floor laid with a style does not mix them.
- ///
- public static HouseStyles Load(bool splitFloorsByColour = false)
- {
- // New tables mean the client files may have changed: measure the art again.
- ArtFacing.Clear();
-
- var result = new HouseStyles();
- List files = TileGroupRegistry.LoadAll(out List errors);
- foreach (TileGroupFile file in files)
- {
- if (!_kinds.TryGetValue(file.DisplayName, out HousePartKind kind))
- {
- continue;
- }
-
- foreach (TileCategory category in file.Categories)
- {
- foreach (TileStyle tileStyle in category.Styles)
- {
- var style = new HouseStyle(kind, category.Name, tileStyle.Name);
- foreach (TileSlot slot in tileStyle.Slots)
- {
- // Stairs list stair multis; they are multi ids, not art.
- bool multiColumn = slot.Label.StartsWith("Multi", System.StringComparison.Ordinal);
- if (slot.IsEmpty || slot.TileId > ushort.MaxValue || (!multiColumn && !slot.IsValid))
- {
- continue;
- }
-
- style.Add(slot.Label, (ushort)slot.TileId);
- }
-
- if (style.Slots.Count == 0)
- {
- continue;
- }
-
- IEnumerable parts = splitFloorsByColour && kind == HousePartKind.Floor
- ? SplitByColour(style)
- : new[] { style };
- foreach (HouseStyle part in parts)
- {
- result.Styles.Add(part);
- foreach (KeyValuePair piece in part.Slots)
- {
- // Stair multi columns hold multi ids, not art.
- if (!piece.Key.StartsWith("Multi", System.StringComparison.Ordinal))
- {
- result._roles.TryAdd(piece.Value, (part, piece.Key));
- }
- }
- }
- }
- }
- }
-
- result.Errors.AddRange(errors);
- return result;
- }
-
- /// How far apart two radar colours may be (RGB distance) and still count as one floor colour.
- private const int _sameColour = 20;
-
- ///
- /// Splits a floor row into styles of one colour each, by the tiles' radar colours. Pieces keep
- /// their column labels; a tile listed twice counts once. Each part is named after its tiles'
- /// tiledata name, numbered where a row has several of the same, and grouped under the row's name.
- ///
- private static List SplitByColour(HouseStyle style)
- {
- var clusters = new List<(System.Drawing.Color Colour, List> Pieces)>();
- var seen = new HashSet();
- foreach (KeyValuePair piece in style.Slots)
- {
- if (!seen.Add(piece.Value))
- {
- continue;
- }
-
- System.Drawing.Color colour = Ultima.Helpers.HueHelpers.HueToColor(Ultima.RadarCol.GetItemColor(piece.Value));
- int index = clusters.FindIndex(c =>
- {
- int dr = c.Colour.R - colour.R, dg = c.Colour.G - colour.G, db = c.Colour.B - colour.B;
- return (dr * dr) + (dg * dg) + (db * db) <= _sameColour * _sameColour;
- });
- if (index < 0)
- {
- clusters.Add((colour, new List> { piece }));
- }
- else
- {
- clusters[index].Pieces.Add(piece);
- }
- }
-
- if (clusters.Count <= 1)
- {
- return new List { style };
- }
-
- var names = new List();
- foreach (var (_, pieces) in clusters)
- {
- string name = Ultima.TileData.ItemTable[pieces[0].Value].Name?.Trim();
- if (string.IsNullOrEmpty(name) || name.StartsWith("Missing", System.StringComparison.OrdinalIgnoreCase))
- {
- name = style.Name;
- }
-
- names.Add(char.ToUpperInvariant(name[0]) + name.Substring(1));
- }
-
- var result = new List();
- for (int i = 0; i < clusters.Count; i++)
- {
- string name = names[i];
- if (names.FindAll(n => n == name).Count > 1)
- {
- name += " " + (names.GetRange(0, i + 1).FindAll(n => n == names[i]).Count);
- }
-
- var part = new HouseStyle(style.Kind, style.Name, name);
- foreach (KeyValuePair piece in clusters[i].Pieces)
- {
- part.Add(piece.Key, piece.Value);
- }
-
- result.Add(part);
- }
-
- return result;
- }
-
- /// The style and column a tile id is listed under, when any.
- public bool TryGetRole(ushort id, out HouseStyle style, out string slot)
- {
- if (_roles.TryGetValue(id, out var role))
- {
- style = role.Style;
- slot = role.Slot;
- return true;
- }
-
- style = null;
- slot = null;
- return false;
- }
-
- ///
- /// The style and column of a tile, also when the tables list it under another id with the
- /// same art: the classic roof and stair tiles are copies of the custom house pieces, which
- /// is how their facing is known. tells the two cases apart.
- ///
- public bool TryGetRoleByArt(ushort id, out HouseStyle style, out string slot, out bool exact)
- {
- exact = TryGetRole(id, out style, out slot);
- if (exact)
- {
- return true;
- }
-
- return TryGetListedTwin(id, out ushort listed) && TryGetRole(listed, out style, out slot);
- }
-
- ///
- /// The listed piece a tile copies. Either the art is the same, or the tile sits in a run of
- /// ids that copies a listed run piece by piece (the classic roof sets do; one or two of
- /// their pieces were redrawn, and those are found by their place in the run).
- ///
- public bool TryGetListedTwin(ushort id, out ushort listed)
- {
- if (_roles.ContainsKey(id))
- {
- listed = id;
- return true;
- }
-
- if (TryGetSameArt(id, out listed))
- {
- return true;
- }
-
- // Neighbours of the same kind that copy a listed piece say where this one's twin should be.
- if (id >= Ultima.TileData.ItemTable.Length)
- {
- listed = 0;
- return false;
- }
-
- string name = Ultima.TileData.ItemTable[id].Name;
- var votes = new Dictionary<(int Offset, HouseStyle Style), int>();
- for (int distance = 1; distance <= 6; distance++)
- {
- foreach (int neighbour in new[] { id - distance, id + distance })
- {
- if (neighbour >= 0 && neighbour < Ultima.TileData.ItemTable.Length && !_roles.ContainsKey((ushort)neighbour) &&
- SameSet(Ultima.TileData.ItemTable[neighbour].Name, name) &&
- TryGetSameArt((ushort)neighbour, out ushort twin))
- {
- var key = (twin - neighbour, _roles[twin].Style);
- votes[key] = votes.TryGetValue(key, out int count) ? count + 1 : 1;
- }
- }
- }
-
- foreach (KeyValuePair<(int Offset, HouseStyle Style), int> vote in votes)
- {
- int candidate = id + vote.Key.Offset;
- if (vote.Value >= 3 && candidate >= 0 && candidate <= ushort.MaxValue &&
- _roles.TryGetValue((ushort)candidate, out (HouseStyle Style, string Slot) role) &&
- role.Style == vote.Key.Style)
- {
- listed = (ushort)candidate;
- return true;
- }
- }
-
- listed = 0;
- return false;
- }
-
- ///
- /// The four corner pieces of a stair set, in the order a left turn goes through them
- /// (south-east, north-east, north-west, south-west), and where is in
- /// it. stairs.txt names only the two front corners of a stair that climbs north: the one
- /// that is its own mirror image is the south-east one, the mirror twin of the other is the
- /// north-east one, and the fourth is the id next to those three.
- ///
- public bool TryGetStairCorner(ushort id, out ushort[] corners, out int index)
- {
- if (_stairCorners == null)
- {
- _stairCorners = new Dictionary();
- foreach (HouseStyle style in Styles)
- {
- if (style.Kind != HousePartKind.Stair)
- {
- continue;
- }
-
- AddStairCorners(style.Get("Squared1"), style.Get("Squared2"));
- AddStairCorners(style.Get("Rounded1"), style.Get("Rounded2"));
- }
- }
-
- if (_stairCorners.TryGetValue(id, out (ushort[] Corners, int Index) found))
- {
- corners = found.Corners;
- index = found.Index;
- return true;
- }
-
- corners = null;
- index = -1;
- return false;
- }
-
- private void AddStairCorners(ushort first, ushort second)
- {
- if (first == 0 || second == 0)
- {
- return;
- }
-
- bool firstSymmetric = ArtFacing.Transpose(first) == first;
- bool secondSymmetric = ArtFacing.Transpose(second) == second;
- if (firstSymmetric == secondSymmetric)
- {
- return;
- }
-
- ushort southEast = firstSymmetric ? first : second;
- ushort southWest = firstSymmetric ? second : first;
- ushort northEast = ArtFacing.Transpose(southWest);
-
- int low = Math.Min(southEast, Math.Min(southWest, northEast));
- int high = Math.Max(southEast, Math.Max(southWest, northEast));
- if (high - low != 2)
- {
- return;
- }
-
- foreach (int candidate in new[] { low - 1, high + 1 })
- {
- if (candidate < 0 || candidate > ushort.MaxValue || _roles.ContainsKey((ushort)candidate) ||
- ArtFacing.ArtHash((ushort)candidate) == 0 || ArtFacing.Transpose((ushort)candidate) != candidate)
- {
- continue;
- }
-
- ushort[] corners = { southEast, northEast, (ushort)candidate, southWest };
- for (int i = 0; i < corners.Length; i++)
- {
- _stairCorners.TryAdd(corners[i], (corners, i));
- }
-
- return;
- }
- }
-
- /// Tiledata names of one set: equal, or one is the other with a letter more ("shingle", "shingles").
- private static bool SameSet(string a, string b)
- {
- a ??= string.Empty;
- b ??= string.Empty;
- return Math.Abs(a.Length - b.Length) <= 1 &&
- (a.StartsWith(b, StringComparison.OrdinalIgnoreCase) || b.StartsWith(a, StringComparison.OrdinalIgnoreCase));
- }
-
- private bool TryGetSameArt(ushort id, out ushort listed)
- {
- if (_listedByArt == null)
- {
- _listedByArt = new Dictionary();
- foreach (KeyValuePair role in _roles)
- {
- if (role.Value.Style.Kind is not (HousePartKind.Roof or HousePartKind.Stair))
- {
- continue;
- }
-
- ulong roleHash = ArtFacing.ArtHash(role.Key);
- if (roleHash != 0)
- {
- _listedByArt.TryAdd(roleHash, role.Key);
- }
- }
- }
-
- ulong hash = ArtFacing.ArtHash(id);
- listed = 0;
- return hash != 0 && _listedByArt.TryGetValue(hash, out listed);
- }
- }
-}
diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorLevel.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorLevel.cs
new file mode 100644
index 00000000..f132a50e
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorLevel.cs
@@ -0,0 +1,21 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Plugin.MultiEditor.Editing
+{
+ ///
+ /// A floor of the multi: tiles from Floor up to (not including) Ceiling. BaseZ is the Z new
+ /// tiles get on it. The lowest level also takes what lies below its base, the highest what
+ /// lies above.
+ ///
+ internal readonly record struct EditorLevel(string Name, string ShortName, int Floor, int Ceiling, int BaseZ)
+ {
+ public string Description => Ceiling > sbyte.MaxValue ? $"{Name} (Z {BaseZ} and up)" : $"{Name} (Z {BaseZ} to {Ceiling - 1})";
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Clipboard.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Clipboard.cs
new file mode 100644
index 00000000..9b33ec05
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Clipboard.cs
@@ -0,0 +1,125 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Windows.Forms;
+using UoFiddler.Plugin.MultiEditor.Model;
+
+namespace UoFiddler.Plugin.MultiEditor.Editing
+{
+ internal sealed partial class EditorSession
+ {
+ // Shared by every open document, so a copy in one tab pastes into another.
+ private static List _clipboard;
+
+ // ---------------------------------------------------------------- clipboard
+
+ ///
+ /// Copies the selection, relative to its lowest X, Y and Z, for pasting in any document and
+ /// as multi text lines to the Windows clipboard, so another editor or a text file can take it.
+ ///
+ public bool Copy()
+ {
+ if (_selection.Count == 0)
+ {
+ return false;
+ }
+
+ _clipboard = ToClipboard(_selection);
+ try
+ {
+ Clipboard.SetText(ClipboardTile.Format(_clipboard));
+ }
+ catch (ExternalException)
+ {
+ // Clipboard busy in another program: the editor's own copy still works.
+ }
+
+ return true;
+ }
+
+ public void Cut()
+ {
+ if (Copy())
+ {
+ DeleteSelection();
+ }
+ }
+
+ /// Starts placing the clipboard tiles with the mouse.
+ public void Paste()
+ {
+ BeginPaste(ReadClipboard());
+ }
+
+ public bool CanPaste => _clipboard != null || ClipboardHasTiles();
+
+ /// Puts a copy of the selection on the cursor to place with the mouse. The clipboard is left alone.
+ public void Duplicate()
+ {
+ BeginPaste(SelectionAsClipboard(), "Duplicate");
+ }
+
+ /// The selection as tiles relative to its lowest X, Y and Z (also used to save a blueprint).
+ public List SelectionAsClipboard()
+ {
+ return _selection.Count == 0 ? null : ToClipboard(_selection);
+ }
+
+ /// Every tile of the design, relative to its lowest X, Y and Z; null when it is empty.
+ public List DesignAsClipboard()
+ {
+ List tiles = CompList.RealTiles.ToList();
+ return tiles.Count == 0 ? null : ToClipboard(tiles);
+ }
+
+ private static List ToClipboard(IReadOnlyCollection tiles)
+ {
+ int ox = tiles.Min(t => t.X);
+ int oy = tiles.Min(t => t.Y);
+ int oz = tiles.Min(t => t.Z);
+ return tiles
+ .OrderBy(t => t.X).ThenBy(t => t.Y).ThenBy(t => t.Z)
+ .Select(t => new ClipboardTile(t.Id, t.X - ox, t.Y - oy, t.Z - oz, t.Invisible, t.Extra))
+ .ToList();
+ }
+
+ /// Tiles from the Windows clipboard when it holds multi text lines, else the editor's own copy.
+ private static List ReadClipboard()
+ {
+ try
+ {
+ if (Clipboard.ContainsText() && ClipboardTile.Parse(Clipboard.GetText()) is { } fromText)
+ {
+ return fromText;
+ }
+ }
+ catch (ExternalException)
+ {
+ // Clipboard busy: fall back to the editor's own copy.
+ }
+
+ return _clipboard;
+ }
+
+ private static bool ClipboardHasTiles()
+ {
+ try
+ {
+ return Clipboard.ContainsText();
+ }
+ catch (ExternalException)
+ {
+ return false;
+ }
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs
index 0712822d..c479ba57 100644
--- a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs
+++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs
@@ -11,105 +11,21 @@
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
-using System.Runtime.InteropServices;
-using System.Windows.Forms;
-using Ultima;
-using UoFiddler.Plugin.MultiEditor.Classes;
-using UoFiddler.Plugin.MultiEditor.Tools;
+using UoFiddler.Plugin.MultiEditor.House;
+using UoFiddler.Plugin.MultiEditor.Model;
+using UoFiddler.Plugin.MultiEditor.Rendering;
+using UoFiddler.Plugin.MultiEditor.Storage;
+using UoFiddler.Plugin.MultiEditor.Styles;
namespace UoFiddler.Plugin.MultiEditor.Editing
{
- ///
- /// A floor of the multi: tiles from Floor up to (not including) Ceiling. BaseZ is the Z new
- /// tiles get on it. The lowest level also takes what lies below its base, the highest what
- /// lies above.
- ///
- internal readonly record struct EditorLevel(string Name, string ShortName, int Floor, int Ceiling, int BaseZ)
- {
- public string Description => Ceiling > sbyte.MaxValue ? $"{Name} (Z {BaseZ} and up)" : $"{Name} (Z {BaseZ} to {Ceiling - 1})";
- }
-
- /// How the user splits a design into levels: a name and the Z the level starts at.
- internal readonly record struct LevelDefinition(string Name, int StartZ);
-
- /// The ground a previewed multi stands on.
- internal enum PreviewTerrain
- {
- None,
- Grass,
- Dirt,
- Sand,
- Snow
- }
-
///
/// The edit commands of a session: clipboard, selection edits, group transforms and levels.
///
internal sealed partial class EditorSession
{
- // Shared by every open document, so a copy in one tab pastes into another.
- private static List _clipboard;
private static RotationTable _rotationTable;
- private readonly List _levels = new List();
- private int _levelIndex;
- private int _firstFloorZ;
- private readonly List _levelDefinitions = new List();
-
- /// Highest Z a first floor is looked for at; above that it is a second storey.
- public const int MaxFirstFloorZ = 12;
-
- /// Storeys between the foundation and the roof, as in the client's house designer.
- public const int FloorCount = 4;
-
- // ---------------------------------------------------------------- clipboard
-
- ///
- /// Copies the selection, relative to its lowest X, Y and Z, for pasting in any document and
- /// as multi text lines to the Windows clipboard, so another editor or a text file can take it.
- ///
- public bool Copy()
- {
- if (_selection.Count == 0)
- {
- return false;
- }
-
- _clipboard = ToClipboard(_selection);
- try
- {
- Clipboard.SetText(ClipboardTile.Format(_clipboard));
- }
- catch (ExternalException)
- {
- // Clipboard busy in another program: the editor's own copy still works.
- }
-
- return true;
- }
-
- public void Cut()
- {
- if (Copy())
- {
- DeleteSelection();
- }
- }
-
- /// Starts placing the clipboard tiles with the mouse.
- public void Paste()
- {
- BeginPaste(ReadClipboard());
- }
-
- public bool CanPaste => _clipboard != null || ClipboardHasTiles();
-
- /// Puts a copy of the selection on the cursor to place with the mouse. The clipboard is left alone.
- public void Duplicate()
- {
- BeginPaste(SelectionAsClipboard(), "Duplicate");
- }
-
// ---------------------------------------------------------------- layers
public IReadOnlyList Layers => CompList.Layers;
@@ -239,7 +155,7 @@ public DesignData ToDesign()
{
return new DesignData(Title, CompList.Width, CompList.Height, FirstFloorZ,
CustomLevels ? _levelDefinitions.ToList() : null, CompList.DesignLayers(),
- CompList.Layers.ToList().IndexOf(CompList.ActiveLayer));
+ CompList.Layers.ToList().IndexOf(CompList.ActiveLayer), PlacedHouses.ToList());
}
/// Opens what a design file holds as this session's document.
@@ -247,13 +163,14 @@ public void LoadDesign(DesignData design)
{
NewBlank(design.Width, design.Height, design.FirstFloorZ);
CompList.RestoreLayers(design.Layers, design.ActiveLayer, (0, 0));
+ SetPlacedHouses(design.Houses);
if (design.Levels != null)
{
SetLevelDefinitions(design.Levels);
}
RebuildLevels();
- Modified = false;
+ MarkClean();
DocumentChanged?.Invoke();
LayersChanged?.Invoke();
OnViewChanged();
@@ -358,60 +275,6 @@ public void RepeatSelection(int copies, int dx, int dy, int dz)
AfterEdit(dz > 0 ? tiles.Max(t => t.z) : null);
}
- /// The selection as tiles relative to its lowest X, Y and Z (also used to save a blueprint).
- public List SelectionAsClipboard()
- {
- return _selection.Count == 0 ? null : ToClipboard(_selection);
- }
-
- /// Every tile of the design, relative to its lowest X, Y and Z; null when it is empty.
- public List DesignAsClipboard()
- {
- List tiles = CompList.RealTiles.ToList();
- return tiles.Count == 0 ? null : ToClipboard(tiles);
- }
-
- private static List ToClipboard(IReadOnlyCollection tiles)
- {
- int ox = tiles.Min(t => t.X);
- int oy = tiles.Min(t => t.Y);
- int oz = tiles.Min(t => t.Z);
- return tiles
- .OrderBy(t => t.X).ThenBy(t => t.Y).ThenBy(t => t.Z)
- .Select(t => new ClipboardTile(t.Id, t.X - ox, t.Y - oy, t.Z - oz, t.Invisible, t.Extra))
- .ToList();
- }
-
- /// Tiles from the Windows clipboard when it holds multi text lines, else the editor's own copy.
- private static List ReadClipboard()
- {
- try
- {
- if (Clipboard.ContainsText() && ClipboardTile.Parse(Clipboard.GetText()) is { } fromText)
- {
- return fromText;
- }
- }
- catch (ExternalException)
- {
- // Clipboard busy: fall back to the editor's own copy.
- }
-
- return _clipboard;
- }
-
- private static bool ClipboardHasTiles()
- {
- try
- {
- return Clipboard.ContainsText();
- }
- catch (ExternalException)
- {
- return false;
- }
- }
-
// ---------------------------------------------------------------- selection edits
public void SelectAll()
@@ -833,271 +696,5 @@ public PointF TileAnchor(MultiTile tile)
PointF corner = CellCorner(tile.X, tile.Y, tile.Z);
return new PointF(corner.X, corner.Y + 22);
}
-
- // ---------------------------------------------------------------- levels
-
- /// The floors of the multi, bottom to top.
- public IReadOnlyList Levels => _levels;
-
- /// 0 shows all levels; n works on Levels[n - 1].
- public int LevelIndex
- {
- get => _levelIndex;
- set
- {
- value = Math.Clamp(value, 0, _levels.Count);
- if (value == _levelIndex)
- {
- return;
- }
-
- _levelIndex = value;
- ApplyLevel();
- }
- }
-
- public void StepLevel(int step)
- {
- if (_levels.Count == 0)
- {
- return;
- }
-
- // From "all levels", stepping up starts at the bottom level.
- LevelIndex = _levelIndex == 0 && step > 0 ? 1 : _levelIndex + step;
- }
-
- ///
- /// Z of the first floor. 0 for a multi built from the ground; above 0 the multi stands on a
- /// foundation, which is then a level of its own below the floors. Custom house foundations
- /// and most classic houses use 7, some classic houses 4, 5, 6 or 8. Found from the tiles on
- /// load. Setting it puts the levels back to the standard split from that Z.
- ///
- public int FirstFloorZ
- {
- get => _firstFloorZ;
- set
- {
- value = Math.Clamp(value, 0, MaxFirstFloorZ);
- if (_firstFloorZ == value && !CustomLevels)
- {
- return;
- }
-
- _firstFloorZ = value;
- ApplyLevelDefinitions(StandardLevels(value), custom: false);
- }
- }
-
- public bool HasFoundation => _firstFloorZ > 0;
-
- /// True when the user set the levels by hand, so they are no longer the standard split.
- public bool CustomLevels { get; private set; }
-
- /// The levels as defined: name and starting Z, lowest first.
- public IReadOnlyList LevelDefinitions => _levelDefinitions;
-
- ///
- /// The standard split: an optional foundation below the first floor, four floors 20 high,
- /// and a roof level above them. These are the client's house designer numbers.
- ///
- public static List StandardLevels(int firstFloorZ)
- {
- var levels = new List();
- if (firstFloorZ > 0)
- {
- levels.Add(new LevelDefinition("Foundation", 0));
- }
-
- for (int n = 1; n <= FloorCount; n++)
- {
- levels.Add(new LevelDefinition($"Floor {n}", firstFloorZ + ((n - 1) * 20)));
- }
-
- levels.Add(new LevelDefinition("Roof", firstFloorZ + (FloorCount * 20)));
- return levels;
- }
-
- ///
- /// A split fitted to this design: floors 20 high from the first floor up to where its roof
- /// tiles begin, then the roof. Without roof tiles it is the standard split.
- ///
- public List FittedLevels()
- {
- int roof = int.MaxValue;
- foreach (MultiTile tile in CompList.RealTiles)
- {
- if ((TileData.ItemTable[tile.Id].Flags & TileFlag.Roof) != 0 && tile.Z > _firstFloorZ)
- {
- roof = Math.Min(roof, tile.Z);
- }
- }
-
- if (roof == int.MaxValue)
- {
- return StandardLevels(_firstFloorZ);
- }
-
- var levels = new List();
- if (_firstFloorZ > 0)
- {
- levels.Add(new LevelDefinition("Foundation", 0));
- }
-
- // A floor needs most of a storey below the roof to count; a roof starting a few Z into
- // the next band still belongs over the floor below.
- int n = 1;
- for (int floor = _firstFloorZ; floor == _firstFloorZ || floor + 10 <= roof; floor += 20)
- {
- levels.Add(new LevelDefinition($"Floor {n++}", floor));
- }
-
- levels.Add(new LevelDefinition("Roof", Math.Max(roof, levels[^1].StartZ + 1)));
- return levels;
- }
-
- /// Sets the levels by hand. Starts are kept within a multi's Z range and must differ; at least one level stays.
- public void SetLevelDefinitions(IEnumerable levels)
- {
- ApplyLevelDefinitions(levels, custom: true);
- }
-
- private void ApplyLevelDefinitions(IEnumerable levels, bool custom)
- {
- var cleaned = new List();
- foreach (LevelDefinition level in levels.OrderBy(l => l.StartZ))
- {
- int start = Math.Clamp(level.StartZ, sbyte.MinValue, sbyte.MaxValue);
- string name = string.IsNullOrWhiteSpace(level.Name) ? $"Level {cleaned.Count + 1}" : level.Name.Trim();
- if (cleaned.Count == 0 || cleaned[^1].StartZ != start)
- {
- cleaned.Add(new LevelDefinition(name, start));
- }
- }
-
- if (cleaned.Count == 0)
- {
- cleaned = StandardLevels(_firstFloorZ);
- custom = false;
- }
-
- _levelDefinitions.Clear();
- _levelDefinitions.AddRange(cleaned);
- CustomLevels = custom;
- RebuildLevels();
- if (_levelIndex > 0)
- {
- ApplyLevel();
- }
- else
- {
- OnViewChanged();
- }
- }
-
- ///
- /// The first floor is the lowest Z, up to , that holds a real
- /// share of the flat walkable tiles. One stray flat tile low down does not make a floor.
- ///
- private int DetectFirstFloorZ()
- {
- var flat = new SortedDictionary();
- foreach (MultiTile tile in CompList.RealTiles)
- {
- if (tile.Height == 0 && (TileData.ItemTable[tile.Id].Flags & TileFlag.Surface) != 0)
- {
- flat[tile.Z] = flat.GetValueOrDefault(tile.Z) + 1;
- }
- }
-
- if (flat.Count == 0)
- {
- return 0;
- }
-
- int needed = Math.Max(4, flat.Values.Max() / 4);
- foreach ((int z, int count) in flat)
- {
- if (z >= 0 && z <= MaxFirstFloorZ && count >= needed)
- {
- return z;
- }
- }
-
- return 0;
- }
-
- /// A short label for a level's button: the number of "Floor 2", else the start of the name.
- private static string ShortNameOf(string name)
- {
- if (name.StartsWith("Floor ", StringComparison.OrdinalIgnoreCase) && name.Length > 6)
- {
- return name.Substring(6);
- }
-
- return name.Equals("Foundation", StringComparison.OrdinalIgnoreCase) ? "Fnd" : name.Length <= 5 ? name : name.Substring(0, 5);
- }
-
- ///
- /// Builds the levels from their definitions. Every level is there whether it holds tiles or
- /// not, so an empty floor can be chosen and built on.
- ///
- public void RebuildLevels()
- {
- var levels = new List();
- if (HasDocument)
- {
- if (_levelDefinitions.Count == 0)
- {
- _levelDefinitions.AddRange(StandardLevels(_firstFloorZ));
- }
-
- for (int i = 0; i < _levelDefinitions.Count; i++)
- {
- LevelDefinition level = _levelDefinitions[i];
- int from = i == 0 ? sbyte.MinValue : level.StartZ;
- int to = i + 1 < _levelDefinitions.Count ? _levelDefinitions[i + 1].StartZ : sbyte.MaxValue + 1;
- levels.Add(new EditorLevel(level.Name, ShortNameOf(level.Name), from, to, level.StartZ));
- }
- }
-
- if (levels.SequenceEqual(_levels))
- {
- return;
- }
-
- _levels.Clear();
- _levels.AddRange(levels);
- if (_levelIndex > _levels.Count)
- {
- _levelIndex = 0;
- ApplyLevel();
- }
- else if (_levelIndex > 0)
- {
- // Same index, possibly a different Z band.
- _activeLevel = (_levels[_levelIndex - 1].Floor, _levels[_levelIndex - 1].Ceiling);
- }
- }
-
- ///
- /// Limits the view to the chosen level and puts the work plane on its base, where drawing
- /// then lands ().
- ///
- private void ApplyLevel()
- {
- _workPlaneOffset = 0;
- if (_levelIndex > 0)
- {
- EditorLevel level = _levels[_levelIndex - 1];
- _activeLevel = (level.Floor, level.Ceiling);
- }
- else
- {
- _activeLevel = null;
- }
-
- OnViewChanged();
- }
}
}
diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Drafts.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Drafts.cs
new file mode 100644
index 00000000..07827442
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Drafts.cs
@@ -0,0 +1,157 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using UoFiddler.Plugin.MultiEditor.Tools;
+using UoFiddler.Plugin.MultiEditor.House;
+using UoFiddler.Plugin.MultiEditor.Model;
+using UoFiddler.Plugin.MultiEditor.Storage;
+
+namespace UoFiddler.Plugin.MultiEditor.Editing
+{
+ internal sealed partial class EditorSession
+ {
+ // ---------------------------------------------------------------- placed houses
+
+ private readonly List _placedHouses = new List();
+
+ ///
+ /// The houses placed with the House tool, each as the draft it was placed from. They are
+ /// kept with the design (design file, layers file), so a placed house can be opened as a
+ /// draft again.
+ ///
+ public IReadOnlyList PlacedHouses => _placedHouses;
+
+ private string FreeHouseName()
+ {
+ for (int n = _placedHouses.Count + 1; ; ++n)
+ {
+ string name = $"House {n}";
+ if (_placedHouses.All(h => (string)h.Attribute("name") != name) && CompList.Layers.All(l => l.Name != name))
+ {
+ return name;
+ }
+ }
+ }
+
+ /// Sets the placed houses of a design just opened, moved by an offset (the layers file counts cells from the save origin).
+ public void SetPlacedHouses(IEnumerable houses, int dx = 0, int dy = 0)
+ {
+ _placedHouses.Clear();
+ foreach (System.Xml.Linq.XElement house in houses ?? Enumerable.Empty())
+ {
+ try
+ {
+ _placedHouses.Add(dx == 0 && dy == 0 ? new System.Xml.Linq.XElement(house) : HouseDraftFile.Shifted(house, dx, dy, HouseStyles));
+ }
+ catch (System.IO.InvalidDataException)
+ {
+ // A house that cannot be read is only lost as a draft: its tiles are in the multi.
+ }
+ }
+
+ DraftChanged?.Invoke();
+ }
+
+ /// The placed houses moved by an offset, for a file that counts cells from another origin.
+ public List PlacedHousesShifted(int dx, int dy)
+ {
+ return _placedHouses.Select(h => HouseDraftFile.Shifted(h, dx, dy, HouseStyles)).ToList();
+ }
+
+ ///
+ /// Opens a placed house as a draft again: the tiles it was placed with that are still in
+ /// the multi are taken out (one undo step) and the House tool gets its draft back. Tiles
+ /// changed by hand since stay where they are. Returns what is wrong, or null.
+ ///
+ public string ReopenHouse(System.Xml.Linq.XElement house)
+ {
+ if (House.HasPending)
+ {
+ return "Place or drop the house being designed first.";
+ }
+
+ List<(ushort Id, int X, int Y, int Z, string Layer)> built;
+ try
+ {
+ built = House.TilesOf(house);
+ }
+ catch (System.IO.InvalidDataException ex)
+ {
+ return ex.Message;
+ }
+
+ // The house is on the layer named after it, or on a layer per part.
+ string name = (string)house.Attribute("name");
+ var remove = new List();
+ foreach ((ushort id, int x, int y, int z, string layer) in built)
+ {
+ MultiTile tile = CompList.GetTilesAt(x, y).FirstOrDefault(t =>
+ t.Id == id && t.Z == z && (t.Layer.Name == name || t.Layer.Name == layer) && !remove.Contains(t));
+ if (tile != null)
+ {
+ remove.Add(tile);
+ }
+ }
+
+ _placedHouses.Remove(house);
+ if (remove.Count * 2 < built.Count)
+ {
+ DraftChanged?.Invoke();
+ return "This house is no longer in the multi: most of its tiles were changed or removed.";
+ }
+
+ CompList.ReplaceTilesOnLayers(remove, new List<(ushort, int, int, int, string)>(), "Edit house", HouseDraft.WallsLayer);
+ House.OpenXml(house, keepName: true);
+ AfterEdit();
+ LayersChanged?.Invoke();
+ return null;
+ }
+
+ /// The house tool, for its draft and options.
+ public HouseTool House => (HouseTool)_tools[ToolKind.House];
+
+ /// Raised when a roof or house draft starts, changes or ends.
+ public event Action DraftChanged;
+
+ /// The roof or house tool when it is the tool in use, else null.
+ public WingDraftTool WingTool => _temporaryTool == null ? _tools[_toolKind] as WingDraftTool : null;
+
+ ///
+ /// The draft that Enter places, Esc drops and undo steps through: the one of the wing
+ /// tool in use, else an open house draft (which stays open under the other tools).
+ ///
+ public WingDraftTool OpenDraft => WingTool is { HasPending: true } tool ? tool : House.HasPending ? House : null;
+
+ ///
+ /// The open draft when the tool in use works on it (a wing tool, or a tool that edits the
+ /// house draft): the one Enter places and Esc drops.
+ ///
+ public WingDraftTool DraftInFocus => _temporaryTool != null ? null
+ : WingTool is { HasPending: true } tool ? tool
+ : House.HasPending && ActiveTool is DraftEditTool ? House : null;
+
+ /// True while a wing tool is in use and holds a draft that is not placed yet.
+ public bool ShapingRoof => WingTool is { HasPending: true };
+
+ /// The storey of an open house draft that the chosen floor means.
+ public int DraftStorey => House.StoreyFor(WorkZ);
+
+ /// Draws an open house draft while a tool that does not work on it is in use.
+ public void PaintIdleDraft(IToolOverlay overlay)
+ {
+ if (House.HasPending && _temporaryTool == null && ActiveTool is not (HouseTool or DraftEditTool))
+ {
+ House.PaintDraft(overlay, active: false);
+ }
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Levels.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Levels.cs
new file mode 100644
index 00000000..34d8a8a3
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Levels.cs
@@ -0,0 +1,316 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Ultima;
+using UoFiddler.Plugin.MultiEditor.Model;
+
+namespace UoFiddler.Plugin.MultiEditor.Editing
+{
+ internal sealed partial class EditorSession
+ {
+ private readonly List _levels = new List();
+ private int _levelIndex;
+ private int _firstFloorZ;
+ private readonly List _levelDefinitions = new List();
+
+ /// Highest Z a first floor is looked for at; above that it is a second storey.
+ public const int MaxFirstFloorZ = 12;
+
+ /// Storeys between the foundation and the roof, as in the client's house designer.
+ public const int FloorCount = 4;
+
+ // ---------------------------------------------------------------- levels
+
+ /// The floors of the multi, bottom to top.
+ public IReadOnlyList Levels => _levels;
+
+ /// 0 shows all levels; n works on Levels[n - 1].
+ public int LevelIndex
+ {
+ get => _levelIndex;
+ set
+ {
+ value = Math.Clamp(value, 0, _levels.Count);
+ if (value == _levelIndex)
+ {
+ return;
+ }
+
+ _levelIndex = value;
+ ApplyLevel();
+ }
+ }
+
+ public void StepLevel(int step)
+ {
+ if (_levels.Count == 0)
+ {
+ return;
+ }
+
+ // From "all levels", stepping up starts at the bottom level.
+ LevelIndex = _levelIndex == 0 && step > 0 ? 1 : _levelIndex + step;
+ }
+
+ ///
+ /// Z of the first floor. 0 for a multi built from the ground; above 0 the multi stands on a
+ /// foundation, which is then a level of its own below the floors. Custom house foundations
+ /// and most classic houses use 7, some classic houses 4, 5, 6 or 8. Found from the tiles on
+ /// load. Setting it puts the levels back to the standard split from that Z.
+ ///
+ public int FirstFloorZ
+ {
+ get => _firstFloorZ;
+ set
+ {
+ value = Math.Clamp(value, 0, MaxFirstFloorZ);
+ if (_firstFloorZ == value && !CustomLevels)
+ {
+ return;
+ }
+
+ _firstFloorZ = value;
+ ApplyLevelDefinitions(StandardLevels(value), custom: false);
+ }
+ }
+
+ public bool HasFoundation => _firstFloorZ > 0;
+
+ /// True when the user set the levels by hand, so they are no longer the standard split.
+ public bool CustomLevels { get; private set; }
+
+ /// The levels as defined: name and starting Z, lowest first.
+ public IReadOnlyList LevelDefinitions => _levelDefinitions;
+
+ ///
+ /// The standard split: an optional foundation below the first floor, four floors 20 high,
+ /// and a roof level above them. These are the client's house designer numbers.
+ ///
+ public static List StandardLevels(int firstFloorZ)
+ {
+ var levels = new List();
+ if (firstFloorZ > 0)
+ {
+ levels.Add(new LevelDefinition("Foundation", 0));
+ }
+
+ for (int n = 1; n <= FloorCount; n++)
+ {
+ levels.Add(new LevelDefinition($"Floor {n}", firstFloorZ + ((n - 1) * 20)));
+ }
+
+ levels.Add(new LevelDefinition("Roof", firstFloorZ + (FloorCount * 20)));
+ return levels;
+ }
+
+ ///
+ /// A split fitted to this design: floors 20 high from the first floor up to where its roof
+ /// tiles begin, then the roof. Without roof tiles it is the standard split.
+ ///
+ public List FittedLevels()
+ {
+ int roof = int.MaxValue;
+ foreach (MultiTile tile in CompList.RealTiles)
+ {
+ if ((TileData.ItemTable[tile.Id].Flags & TileFlag.Roof) != 0 && tile.Z > _firstFloorZ)
+ {
+ roof = Math.Min(roof, tile.Z);
+ }
+ }
+
+ if (roof == int.MaxValue)
+ {
+ return StandardLevels(_firstFloorZ);
+ }
+
+ var levels = new List();
+ if (_firstFloorZ > 0)
+ {
+ levels.Add(new LevelDefinition("Foundation", 0));
+ }
+
+ // A floor needs most of a storey below the roof to count; a roof starting a few Z into
+ // the next band still belongs over the floor below.
+ int n = 1;
+ for (int floor = _firstFloorZ; floor == _firstFloorZ || floor + 10 <= roof; floor += 20)
+ {
+ levels.Add(new LevelDefinition($"Floor {n++}", floor));
+ }
+
+ levels.Add(new LevelDefinition("Roof", Math.Max(roof, levels[^1].StartZ + 1)));
+ return levels;
+ }
+
+ /// Sets the levels by hand. Starts are kept within a multi's Z range and must differ; at least one level stays.
+ public void SetLevelDefinitions(IEnumerable levels)
+ {
+ ApplyLevelDefinitions(levels, custom: true);
+ }
+
+ private void ApplyLevelDefinitions(IEnumerable levels, bool custom)
+ {
+ var cleaned = new List();
+ foreach (LevelDefinition level in levels.OrderBy(l => l.StartZ))
+ {
+ int start = Math.Clamp(level.StartZ, sbyte.MinValue, sbyte.MaxValue);
+ string name = string.IsNullOrWhiteSpace(level.Name) ? $"Level {cleaned.Count + 1}" : level.Name.Trim();
+ if (cleaned.Count == 0 || cleaned[^1].StartZ != start)
+ {
+ cleaned.Add(new LevelDefinition(name, start));
+ }
+ }
+
+ if (cleaned.Count == 0)
+ {
+ cleaned = StandardLevels(_firstFloorZ);
+ custom = false;
+ }
+
+ _levelDefinitions.Clear();
+ _levelDefinitions.AddRange(cleaned);
+ CustomLevels = custom;
+ RebuildLevels();
+ if (_levelIndex > 0)
+ {
+ ApplyLevel();
+ }
+ else
+ {
+ OnViewChanged();
+ }
+ }
+
+ ///
+ /// The first floor is the lowest Z, up to , that holds a real
+ /// share of the flat walkable tiles. One stray flat tile low down does not make a floor.
+ /// A design without a floor has it where most of its walls stand.
+ ///
+ private int DetectFirstFloorZ()
+ {
+ var flat = new SortedDictionary();
+ foreach (MultiTile tile in CompList.RealTiles)
+ {
+ if (tile.Height == 0 && (TileData.ItemTable[tile.Id].Flags & TileFlag.Surface) != 0)
+ {
+ flat[tile.Z] = flat.GetValueOrDefault(tile.Z) + 1;
+ }
+ }
+
+ if (flat.Count > 0)
+ {
+ int needed = Math.Max(4, flat.Values.Max() / 4);
+ foreach ((int z, int count) in flat)
+ {
+ if (z >= 0 && z <= MaxFirstFloorZ && count >= needed)
+ {
+ return z;
+ }
+ }
+ }
+
+ // No floor laid (a building lifted off the map stands on terrain): where its walls stand.
+ var walls = new Dictionary();
+ foreach (MultiTile tile in CompList.RealTiles)
+ {
+ if (tile.Z >= 0 && tile.Z <= MaxFirstFloorZ && tile.Height >= 10 &&
+ (TileData.ItemTable[tile.Id].Flags & TileFlag.Wall) != 0)
+ {
+ walls[tile.Z] = walls.GetValueOrDefault(tile.Z) + 1;
+ }
+ }
+
+ int best = 0, most = 3;
+ foreach ((int z, int count) in walls)
+ {
+ if (count > most)
+ {
+ (best, most) = (z, count);
+ }
+ }
+
+ return best;
+ }
+
+ /// A short label for a level's button: the number of "Floor 2", else the start of the name.
+ private static string ShortNameOf(string name)
+ {
+ if (name.StartsWith("Floor ", StringComparison.OrdinalIgnoreCase) && name.Length > 6)
+ {
+ return name.Substring(6);
+ }
+
+ return name.Equals("Foundation", StringComparison.OrdinalIgnoreCase) ? "Fnd" : name.Length <= 5 ? name : name.Substring(0, 5);
+ }
+
+ ///
+ /// Builds the levels from their definitions. Every level is there whether it holds tiles or
+ /// not, so an empty floor can be chosen and built on.
+ ///
+ public void RebuildLevels()
+ {
+ var levels = new List();
+ if (HasDocument)
+ {
+ if (_levelDefinitions.Count == 0)
+ {
+ _levelDefinitions.AddRange(StandardLevels(_firstFloorZ));
+ }
+
+ for (int i = 0; i < _levelDefinitions.Count; i++)
+ {
+ LevelDefinition level = _levelDefinitions[i];
+ int from = i == 0 ? sbyte.MinValue : level.StartZ;
+ int to = i + 1 < _levelDefinitions.Count ? _levelDefinitions[i + 1].StartZ : sbyte.MaxValue + 1;
+ levels.Add(new EditorLevel(level.Name, ShortNameOf(level.Name), from, to, level.StartZ));
+ }
+ }
+
+ if (levels.SequenceEqual(_levels))
+ {
+ return;
+ }
+
+ _levels.Clear();
+ _levels.AddRange(levels);
+ if (_levelIndex > _levels.Count)
+ {
+ _levelIndex = 0;
+ ApplyLevel();
+ }
+ else if (_levelIndex > 0)
+ {
+ // Same index, possibly a different Z band.
+ _activeLevel = (_levels[_levelIndex - 1].Floor, _levels[_levelIndex - 1].Ceiling);
+ }
+ }
+
+ ///
+ /// Limits the view to the chosen level and puts the work plane on its base, where drawing
+ /// then lands ().
+ ///
+ private void ApplyLevel()
+ {
+ _workPlaneOffset = 0;
+ if (_levelIndex > 0)
+ {
+ EditorLevel level = _levels[_levelIndex - 1];
+ _activeLevel = (level.Floor, level.Ceiling);
+ }
+ else
+ {
+ _activeLevel = null;
+ }
+
+ OnViewChanged();
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Selection.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Selection.cs
new file mode 100644
index 00000000..ea049ef8
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Selection.cs
@@ -0,0 +1,276 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System.Collections.Generic;
+using System.Drawing;
+using System.Linq;
+using System.Windows.Forms;
+using UoFiddler.Plugin.MultiEditor.Tools;
+using UoFiddler.Plugin.MultiEditor.Rendering;
+using UoFiddler.Plugin.MultiEditor.Model;
+
+namespace UoFiddler.Plugin.MultiEditor.Editing
+{
+ internal sealed partial class EditorSession
+ {
+ // ---------------------------------------------------------------- selection and hover
+
+ public MultiTile HoverTile { get; private set; }
+
+ public IReadOnlyCollection Selection => _selection;
+
+ /// The selected tile when exactly one is selected.
+ public MultiTile SelectedTile => _selection.Count == 1 ? _selection.First() : null;
+
+ public bool IsSelected(MultiTile tile) => _selection.Contains(tile);
+
+ public (int X, int Y, int Z) CursorCell => _cursorCell;
+
+ public bool MouseInside => _mouseInside;
+
+ public void SetSelection(IEnumerable tiles, bool add)
+ {
+ if (!add)
+ {
+ _selection.Clear();
+ }
+
+ foreach (MultiTile tile in tiles)
+ {
+ _selection.Add(tile);
+ }
+
+ SelectionChanged?.Invoke();
+ Invalidated?.Invoke();
+ }
+
+ public void ToggleSelected(MultiTile tile)
+ {
+ if (!_selection.Remove(tile))
+ {
+ _selection.Add(tile);
+ }
+
+ SelectionChanged?.Invoke();
+ Invalidated?.Invoke();
+ }
+
+ public void ClearSelection()
+ {
+ if (_selection.Count == 0)
+ {
+ return;
+ }
+
+ _selection.Clear();
+ SelectionChanged?.Invoke();
+ Invalidated?.Invoke();
+ }
+
+ /// Takes tiles out of the selection, with one change notice.
+ public void Deselect(IEnumerable tiles)
+ {
+ bool changed = false;
+ foreach (MultiTile tile in tiles)
+ {
+ changed |= _selection.Remove(tile);
+ }
+
+ if (changed)
+ {
+ SelectionChanged?.Invoke();
+ Invalidated?.Invoke();
+ }
+ }
+
+ private HashSet _listHighlight = new HashSet();
+
+ ///
+ /// Tiles pointed at outside the canvas (a row of the selection list), drawn like the hovered
+ /// tile. Empty for none.
+ ///
+ public IReadOnlyCollection ListHighlight
+ {
+ get => _listHighlight;
+ set
+ {
+ var next = value == null ? new HashSet() : new HashSet(value);
+ if (next.SetEquals(_listHighlight))
+ {
+ return;
+ }
+
+ _listHighlight = next;
+ Invalidated?.Invoke();
+ }
+ }
+
+ public bool IsListHighlighted(MultiTile tile) => _listHighlight.Count > 0 && _listHighlight.Contains(tile);
+
+ /// True when a tile can be hovered, selected and edited with the current view.
+ public bool IsEditable(MultiTile tile)
+ {
+ return tile.Z <= EditMaxHeight && !(WorkZ is { } baseZ && baseZ > tile.Z) && CompList.IsShown(tile);
+ }
+
+ /// The topmost editable tile with a drawn pixel at a world point, or null.
+ public MultiTile HitTest(Point world)
+ {
+ if (_planMode)
+ {
+ (int cx, int cy) = PlanView.CellAt(world);
+ return CompList.InBounds(cx, cy) ? Plan.TopTile(cx, cy, EditMaxHeight, EditMinZ) : null;
+ }
+
+ MultiTile hit = null;
+
+ // Draw order: the last match is the one on top. Runs on every mouse move over every
+ // tile, so the point is first checked against the art's rectangle, which rules out
+ // almost all of them without a lookup.
+ foreach (MultiTile tile in CompList.RealTiles)
+ {
+ int px = world.X - tile.XMod;
+ int py = world.Y - tile.YMod;
+ if ((uint)px >= (uint)tile.ArtWidth || (uint)py >= (uint)tile.ArtHeight)
+ {
+ continue;
+ }
+
+ if (IsEditable(tile) && _masks.Hit(tile.Id, px, py))
+ {
+ hit = tile;
+ }
+ }
+
+ return hit;
+ }
+
+ /// How long the last hover update's hit test took, for the performance box.
+ public double LastHitTestMs { get; private set; }
+
+ private bool UpdateHover()
+ {
+ long start = System.Diagnostics.Stopwatch.GetTimestamp();
+ MultiTile hover = _mouseInside && HasDocument && !_previewMode ? HitTest(_mouseLoc) : null;
+ LastHitTestMs = System.Diagnostics.Stopwatch.GetElapsedTime(start).TotalMilliseconds;
+ if (hover == HoverTile)
+ {
+ return false;
+ }
+
+ HoverTile = hover;
+ HoverChanged?.Invoke();
+ return true;
+ }
+
+ private bool UpdateCursorCell()
+ {
+ if (!_mouseInside || !HasDocument)
+ {
+ return false;
+ }
+
+ ConvertCoords(_mouseLoc, out int x, out int y, out int z);
+ if ((x, y, z) == _cursorCell)
+ {
+ return false;
+ }
+
+ _cursorCell = (x, y, z);
+ CursorCellChanged?.Invoke();
+ return true;
+ }
+
+ // ---------------------------------------------------------------- pointer input (world space)
+
+ public void PointerMove(Point world, MouseEventArgs e)
+ {
+ _mouseLoc = world;
+ _mouseInside = true;
+ if (!HasDocument || _previewMode)
+ {
+ return;
+ }
+
+ // Hover first: tools read the cell under the mouse, which depends on the hovered tile.
+ bool hoverChanged = UpdateHover();
+ bool cellChanged = UpdateCursorCell();
+ EditorTool tool = ActiveTool;
+ tool.OnMouseMove(e);
+ if (hoverChanged || tool.IsDragging || (cellChanged && tool.TracksCursorCell))
+ {
+ Invalidated?.Invoke();
+ }
+ }
+
+ public void PointerLeave()
+ {
+ _mouseInside = false;
+ _cursorCell = (int.MinValue, int.MinValue, int.MinValue);
+ UpdateHover();
+ CursorCellChanged?.Invoke();
+ Invalidated?.Invoke();
+ }
+
+ public void PointerDown(Point world, MouseEventArgs e)
+ {
+ _mouseLoc = world;
+ _mouseInside = true;
+ if (HasDocument && !_previewMode && e.Button == MouseButtons.Left)
+ {
+ UpdateHover();
+ UpdateCursorCell();
+
+ // Alt+click with a draw tool picks a tile: the tool does not see the click.
+ _pickClick = PickingWithAlt;
+ if (!_pickClick)
+ {
+ ActiveTool.OnMouseDown(e);
+ }
+
+ Invalidated?.Invoke();
+ }
+ }
+
+ public void PointerUp(Point world, MouseEventArgs e)
+ {
+ _mouseLoc = world;
+ if (!HasDocument || _previewMode)
+ {
+ return;
+ }
+
+ if (e.Button == MouseButtons.Middle)
+ {
+ // Selects the hovered tile with any tool, so the cell stack lists its cell.
+ if (HoverTile != null)
+ {
+ SetSelection(new[] { HoverTile }, add: false);
+ }
+ }
+ else if (e.Button == MouseButtons.Left)
+ {
+ if (_pickClick)
+ {
+ _pickClick = false;
+ if (HoverTile != null)
+ {
+ PickDrawTile(HoverTile.Id);
+ }
+ }
+ else
+ {
+ ActiveTool.OnMouseUp(e);
+ }
+ }
+
+ Invalidated?.Invoke();
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs
index 2fa581f9..95e8293d 100644
--- a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs
+++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs
@@ -10,40 +10,15 @@
using System;
using System.Collections.Generic;
using System.Drawing;
-using System.Linq;
using System.Windows.Forms;
using Ultima;
-using UoFiddler.Plugin.MultiEditor.Classes;
using UoFiddler.Plugin.MultiEditor.Tools;
using UoFiddler.Plugin.MultiEditor.Rendering;
+using UoFiddler.Plugin.MultiEditor.Model;
+using UoFiddler.Plugin.MultiEditor.Styles;
namespace UoFiddler.Plugin.MultiEditor.Editing
{
- ///
- /// The tools of the editor, by the name the UI shows.
- ///
- internal enum ToolKind
- {
- Select,
- Lasso,
- Draw,
- Remove,
- Altitude,
- Pipette,
- Transparent,
- RectFill,
- Line,
- Wall,
- Floor,
- Door,
- Stair,
- Roof,
- Foundation,
-
- /// Lays a bordered floor pattern; chosen from the House page, not the palette.
- FloorPattern
- }
-
///
/// One multi being edited: the tiles, what is selected and hovered, the view options and the
/// active tool. It knows nothing about controls; the canvas feeds it pointer events and the
@@ -53,6 +28,7 @@ internal sealed partial class EditorSession : IEditorContext, IMultiViewSettings
{
private readonly HashSet _selection = new HashSet();
private readonly Dictionary _tools = new Dictionary();
+ private readonly Dictionary _draftTools = new Dictionary();
private readonly ArtMasks _masks;
private readonly PasteTool _pasteTool;
private readonly RepeatPreviewTool _repeatTool;
@@ -92,7 +68,28 @@ public EditorSession(ArtMasks masks, HouseStyles houseStyles)
_tools[ToolKind.Floor] = new FloorStyleTool(this);
_tools[ToolKind.Door] = new DoorTool(this);
_tools[ToolKind.Stair] = new StairTool(this);
- _tools[ToolKind.Roof] = new RoofTool(this);
+ var roof = new RoofTool(this);
+ var house = new HouseTool(this, roof);
+ foreach (WingDraftTool draft in new WingDraftTool[] { roof, house })
+ {
+ draft.Changed += () =>
+ {
+ DraftChanged?.Invoke();
+ ToolChanged?.Invoke();
+ Invalidated?.Invoke();
+ };
+ draft.Committed += () => LayersChanged?.Invoke();
+ }
+
+ house.FreeName = FreeHouseName;
+ house.Placed += placed => _placedHouses.Add(placed);
+
+ _tools[ToolKind.Roof] = roof;
+ _tools[ToolKind.House] = house;
+ _draftTools[ToolKind.Wall] = new DraftWallTool(this, house);
+ _draftTools[ToolKind.Door] = new DraftDoorTool(this, house);
+ _draftTools[ToolKind.Floor] = new DraftFloorTool(this, house);
+ _draftTools[ToolKind.Stair] = new DraftStairTool(this, house);
_tools[ToolKind.Foundation] = new FoundationTool(this);
_tools[ToolKind.FloorPattern] = new FloorPatternTool(this);
_pasteTool = new PasteTool(this);
@@ -136,9 +133,43 @@ public EditorSession(ArtMasks masks, HouseStyles houseStyles)
/// Name shown on the document tab.
public string Title { get; set; } = "Untitled";
- /// True when there are edits since the last save or load.
+ ///
+ /// True when there are edits since the last save or load. Undoing back to the step that
+ /// was saved makes the design unchanged again; an edit that left no step in the history
+ /// keeps it changed.
+ ///
public bool Modified { get; private set; }
+ // The history step on top when the design was saved, and when it was last looked at.
+ private EditCommand _savedStep;
+ private EditCommand _lastStep;
+ private bool _unloggedEdit;
+ private bool _steppingHistory;
+
+ private EditCommand TopStep => CompList.UndoList.Count > 0 ? CompList.UndoList[0] : null;
+
+ private void MarkClean()
+ {
+ _savedStep = _lastStep = TopStep;
+ _unloggedEdit = false;
+ Modified = false;
+ }
+
+ /// The names of the steps Undo would take back, the latest first.
+ public IReadOnlyList UndoSteps(int most)
+ {
+ var names = new List();
+ if (UndoDraftTool == null)
+ {
+ for (int i = 0; i < CompList.UndoList.Count && i < most; ++i)
+ {
+ names.Add(CompList.UndoList[i].Action);
+ }
+ }
+
+ return names;
+ }
+
public void NewBlank(int width, int height, int firstFloorZ = 0)
{
SetDocument(new MultiEditorComponentList(width, height, this));
@@ -152,35 +183,104 @@ public void Load(MultiComponentList list)
public void MarkSaved()
{
- Modified = false;
+ MarkClean();
DocumentChanged?.Invoke();
}
+ /// True when Undo has something to take back: a step of an open draft, or of the multi.
+ public bool CanUndo => HasDocument && (UndoDraftTool != null || CompList.UndoList.Count > 0);
+
+ public bool CanRedo => HasDocument && (RedoDraftTool != null || (OpenDraft == null && CompList.RedoList.Count > 0) ||
+ (OpenDraft is { ReopenedFrom: not null } reopened && CompList.RedoList.Count > 0 &&
+ ReferenceEquals(CompList.RedoList[0], reopened.ReopenedFrom)));
+
+ // The draft whose history undo and redo walk first: the wing tool in use, else the house.
+ private WingDraftTool UndoDraftTool => WingTool is { CanUndoDraft: true } tool ? tool : House.CanUndoDraft ? House : null;
+
+ private WingDraftTool RedoDraftTool => WingTool is { CanRedoDraft: true } tool ? tool : House.CanRedoDraft ? House : null;
+
+ ///
+ /// Takes back the last step: of the draft being shaped while there is one, else of the
+ /// multi. Undoing the step that placed a roof or house brings its draft back as it was.
+ ///
public bool Undo()
{
+ if (UndoDraftTool is { } draft)
+ {
+ return draft.UndoDraft();
+ }
+
+ EditCommand step = CompList.UndoList.Count > 0 ? CompList.UndoList[0] : null;
if (!CompList.UndoStep())
{
return false;
}
+ foreach (WingDraftTool tool in new WingDraftTool[] { House, Roof })
+ {
+ // A roof draft shows only with the roof tool, so it comes back only there; a
+ // house draft shows under every tool.
+ if (tool.PlacedBy != null && ReferenceEquals(tool.PlacedBy, step) && !tool.HasPending &&
+ (tool is HouseTool || _toolKind == ToolKind.Roof))
+ {
+ tool.Reopen();
+ if (tool is HouseTool reopened && reopened.LastPlaced != null)
+ {
+ _placedHouses.Remove(reopened.LastPlaced);
+ }
+ }
+ }
+
+ _steppingHistory = true;
AfterEdit();
+ _steppingHistory = false;
+ LayersChanged?.Invoke();
return true;
}
+ ///
+ /// Redoes a step of the draft being shaped, else of the multi. While a draft is open the
+ /// multi's steps wait, except the one that placed that very draft.
+ ///
public bool Redo()
{
+ if (RedoDraftTool is { } draft)
+ {
+ return draft.RedoDraft();
+ }
+
+ if (OpenDraft is { } open)
+ {
+ if (open.ReopenedFrom == null || CompList.RedoList.Count == 0 || !ReferenceEquals(CompList.RedoList[0], open.ReopenedFrom))
+ {
+ return false;
+ }
+
+ open.CloseReopened();
+ if (open is HouseTool closed && closed.LastPlaced != null && !_placedHouses.Contains(closed.LastPlaced))
+ {
+ _placedHouses.Add(closed.LastPlaced);
+ }
+ }
+
if (!CompList.RedoStep())
{
return false;
}
+ _steppingHistory = true;
AfterEdit();
+ _steppingHistory = false;
+ LayersChanged?.Invoke();
return true;
}
private void SetDocument(MultiEditorComponentList list)
{
CancelTool();
+ Roof.Reset();
+ House.Reset();
+ _placedHouses.Clear();
CompList = list;
_selection.Clear();
HoverTile = null;
@@ -188,7 +288,7 @@ private void SetDocument(MultiEditorComponentList list)
_activeLevel = null;
_levelIndex = 0;
_workPlaneOffset = 0;
- Modified = false;
+ MarkClean();
_firstFloorZ = DetectFirstFloorZ();
_levelDefinitions.Clear();
CustomLevels = false;
@@ -343,6 +443,13 @@ public ToolKind Tool
get => _toolKind;
set
{
+ // A roof still being shaped is placed when another tool is taken up.
+ // A house draft stays open instead: the wall, door, floor and stair tools work on it.
+ if (_toolKind == ToolKind.Roof && value != ToolKind.Roof)
+ {
+ Roof.Commit();
+ }
+
CancelTool();
_toolKind = value;
if (IsTileTool(value))
@@ -355,7 +462,12 @@ public ToolKind Tool
}
}
- public EditorTool ActiveTool => _temporaryTool ?? _tools[_toolKind];
+ ///
+ /// The tool in use. While a house draft is open the wall, door, floor and stair tools are
+ /// the ones that change the draft.
+ ///
+ public EditorTool ActiveTool => _temporaryTool ??
+ (House.HasPending && _draftTools.TryGetValue(_toolKind, out EditorTool draftTool) ? draftTool : _tools[_toolKind]);
/// True for the tools that place the draw tile (draw, rectangle, line).
public static bool IsTileTool(ToolKind kind)
@@ -374,7 +486,7 @@ public static bool IsTileTool(ToolKind kind)
/// The bordered floor laid by the floor pattern tool, or null.
public FloorPattern FloorPattern { get; set; }
- /// The roof tool, for its shape options (ridge, gables, gable fill).
+ /// The roof tool, for its shape options (ridge, gables, gable fill) and the roof being shaped.
public RoofTool Roof => (RoofTool)_tools[ToolKind.Roof];
/// Call after a tool option changed, so the preview under the cursor follows.
@@ -455,260 +567,6 @@ public void PickDrawTile(ushort id)
}
}
- // ---------------------------------------------------------------- selection and hover
-
- public MultiTile HoverTile { get; private set; }
-
- public IReadOnlyCollection Selection => _selection;
-
- /// The selected tile when exactly one is selected.
- public MultiTile SelectedTile => _selection.Count == 1 ? _selection.First() : null;
-
- public bool IsSelected(MultiTile tile) => _selection.Contains(tile);
-
- public (int X, int Y, int Z) CursorCell => _cursorCell;
-
- public bool MouseInside => _mouseInside;
-
- public void SetSelection(IEnumerable tiles, bool add)
- {
- if (!add)
- {
- _selection.Clear();
- }
-
- foreach (MultiTile tile in tiles)
- {
- _selection.Add(tile);
- }
-
- SelectionChanged?.Invoke();
- Invalidated?.Invoke();
- }
-
- public void ToggleSelected(MultiTile tile)
- {
- if (!_selection.Remove(tile))
- {
- _selection.Add(tile);
- }
-
- SelectionChanged?.Invoke();
- Invalidated?.Invoke();
- }
-
- public void ClearSelection()
- {
- if (_selection.Count == 0)
- {
- return;
- }
-
- _selection.Clear();
- SelectionChanged?.Invoke();
- Invalidated?.Invoke();
- }
-
- /// Takes tiles out of the selection, with one change notice.
- public void Deselect(IEnumerable tiles)
- {
- bool changed = false;
- foreach (MultiTile tile in tiles)
- {
- changed |= _selection.Remove(tile);
- }
-
- if (changed)
- {
- SelectionChanged?.Invoke();
- Invalidated?.Invoke();
- }
- }
-
- private HashSet _listHighlight = new HashSet();
-
- ///
- /// Tiles pointed at outside the canvas (a row of the selection list), drawn like the hovered
- /// tile. Empty for none.
- ///
- public IReadOnlyCollection ListHighlight
- {
- get => _listHighlight;
- set
- {
- var next = value == null ? new HashSet() : new HashSet(value);
- if (next.SetEquals(_listHighlight))
- {
- return;
- }
-
- _listHighlight = next;
- Invalidated?.Invoke();
- }
- }
-
- public bool IsListHighlighted(MultiTile tile) => _listHighlight.Count > 0 && _listHighlight.Contains(tile);
-
- /// True when a tile can be hovered, selected and edited with the current view.
- public bool IsEditable(MultiTile tile)
- {
- return tile.Z <= EditMaxHeight && !(WorkZ is { } baseZ && baseZ > tile.Z) && CompList.IsShown(tile);
- }
-
- /// The topmost editable tile with a drawn pixel at a world point, or null.
- public MultiTile HitTest(Point world)
- {
- if (_planMode)
- {
- (int cx, int cy) = PlanView.CellAt(world);
- return CompList.InBounds(cx, cy) ? Plan.TopTile(cx, cy, EditMaxHeight, EditMinZ) : null;
- }
-
- MultiTile hit = null;
-
- // Draw order: the last match is the one on top. Runs on every mouse move over every
- // tile, so the point is first checked against the art's rectangle, which rules out
- // almost all of them without a lookup.
- foreach (MultiTile tile in CompList.RealTiles)
- {
- int px = world.X - tile.XMod;
- int py = world.Y - tile.YMod;
- if ((uint)px >= (uint)tile.ArtWidth || (uint)py >= (uint)tile.ArtHeight)
- {
- continue;
- }
-
- if (IsEditable(tile) && _masks.Hit(tile.Id, px, py))
- {
- hit = tile;
- }
- }
-
- return hit;
- }
-
- /// How long the last hover update's hit test took, for the performance box.
- public double LastHitTestMs { get; private set; }
-
- private bool UpdateHover()
- {
- long start = System.Diagnostics.Stopwatch.GetTimestamp();
- MultiTile hover = _mouseInside && HasDocument && !_previewMode ? HitTest(_mouseLoc) : null;
- LastHitTestMs = System.Diagnostics.Stopwatch.GetElapsedTime(start).TotalMilliseconds;
- if (hover == HoverTile)
- {
- return false;
- }
-
- HoverTile = hover;
- HoverChanged?.Invoke();
- return true;
- }
-
- private bool UpdateCursorCell()
- {
- if (!_mouseInside || !HasDocument)
- {
- return false;
- }
-
- ConvertCoords(_mouseLoc, out int x, out int y, out int z);
- if ((x, y, z) == _cursorCell)
- {
- return false;
- }
-
- _cursorCell = (x, y, z);
- CursorCellChanged?.Invoke();
- return true;
- }
-
- // ---------------------------------------------------------------- pointer input (world space)
-
- public void PointerMove(Point world, MouseEventArgs e)
- {
- _mouseLoc = world;
- _mouseInside = true;
- if (!HasDocument || _previewMode)
- {
- return;
- }
-
- // Hover first: tools read the cell under the mouse, which depends on the hovered tile.
- bool hoverChanged = UpdateHover();
- bool cellChanged = UpdateCursorCell();
- EditorTool tool = ActiveTool;
- tool.OnMouseMove(e);
- if (hoverChanged || tool.IsDragging || (cellChanged && tool.TracksCursorCell))
- {
- Invalidated?.Invoke();
- }
- }
-
- public void PointerLeave()
- {
- _mouseInside = false;
- _cursorCell = (int.MinValue, int.MinValue, int.MinValue);
- UpdateHover();
- CursorCellChanged?.Invoke();
- Invalidated?.Invoke();
- }
-
- public void PointerDown(Point world, MouseEventArgs e)
- {
- _mouseLoc = world;
- _mouseInside = true;
- if (HasDocument && !_previewMode && e.Button == MouseButtons.Left)
- {
- UpdateHover();
- UpdateCursorCell();
-
- // Alt+click with a draw tool picks a tile: the tool does not see the click.
- _pickClick = PickingWithAlt;
- if (!_pickClick)
- {
- ActiveTool.OnMouseDown(e);
- }
-
- Invalidated?.Invoke();
- }
- }
-
- public void PointerUp(Point world, MouseEventArgs e)
- {
- _mouseLoc = world;
- if (!HasDocument || _previewMode)
- {
- return;
- }
-
- if (e.Button == MouseButtons.Middle)
- {
- // Selects the hovered tile with any tool, so the cell stack lists its cell.
- if (HoverTile != null)
- {
- SetSelection(new[] { HoverTile }, add: false);
- }
- }
- else if (e.Button == MouseButtons.Left)
- {
- if (_pickClick)
- {
- _pickClick = false;
- if (HoverTile != null)
- {
- PickDrawTile(HoverTile.Id);
- }
- }
- else
- {
- ActiveTool.OnMouseUp(e);
- }
- }
-
- Invalidated?.Invoke();
- }
-
// ---------------------------------------------------------------- IEditorContext
Point IEditorContext.MouseLoc => _mouseLoc;
@@ -762,7 +620,15 @@ public void AfterEdit(int? raiseTo = null)
SelectionChanged?.Invoke();
}
- Modified = true;
+ // A change that left no step in the history cannot be undone back to the saved state.
+ EditCommand top = TopStep;
+ if (ReferenceEquals(top, _lastStep) && !_steppingHistory)
+ {
+ _unloggedEdit = true;
+ }
+
+ _lastStep = top;
+ Modified = _unloggedEdit || !ReferenceEquals(top, _savedStep);
RebuildLevels();
if (_showWalkables)
{
diff --git a/UoFiddler.Plugin.MultiEditor/Editing/FloorPattern.cs b/UoFiddler.Plugin.MultiEditor/Editing/FloorPattern.cs
index f052304e..dcf46056 100644
--- a/UoFiddler.Plugin.MultiEditor/Editing/FloorPattern.cs
+++ b/UoFiddler.Plugin.MultiEditor/Editing/FloorPattern.cs
@@ -9,15 +9,8 @@
using System;
using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
using System.Linq;
-using System.Windows.Forms;
-using System.Xml;
-using Ultima;
-using UoFiddler.Controls.Classes;
-using UoFiddler.Plugin.MultiEditor.Classes;
-using UoFiddler.Plugin.MultiEditor.Tools;
+using UoFiddler.Plugin.MultiEditor.Model;
namespace UoFiddler.Plugin.MultiEditor.Editing
{
@@ -251,326 +244,4 @@ private static List Period(List run)
return run;
}
}
-
- ///
- /// The floor patterns: a few shipped ones for tile sets whose border pieces are known, and the
- /// ones the user saved (MultiEditorFloorPatterns.xml next to the other multi editor files).
- ///
- internal static class FloorPatterns
- {
- private static List _user;
-
- public static string FilePath => Path.Combine(Options.AppDataPath ?? string.Empty, "plugins", "MultiEditorFloorPatterns.xml");
-
- /// User patterns first (newest last), then the shipped ones this client has the art for.
- public static List All()
- {
- _user ??= LoadUser();
- var all = new List(_user);
- foreach (FloorPattern pattern in BuiltIn())
- {
- if (pattern.Pieces().All(id => Art.IsValidStatic(id)) && all.All(p => p.Name != pattern.Name))
- {
- all.Add(pattern);
- }
- }
-
- return all;
- }
-
- public static void Save(FloorPattern pattern)
- {
- _user ??= LoadUser();
- _user.RemoveAll(p => string.Equals(p.Name, pattern.Name, StringComparison.OrdinalIgnoreCase));
- _user.Add(pattern);
- SaveUser();
- }
-
- public static void Delete(FloorPattern pattern)
- {
- _user ??= LoadUser();
- if (_user.Remove(pattern))
- {
- SaveUser();
- }
- }
-
- /// Forgets what was read, after the profile or client changed.
- public static void Reset()
- {
- _user = null;
- }
-
- ///
- /// Sets read off the client's art: the piece with its band on a side goes on that side of
- /// the floor. Checked by eye against the 7.0.114.4 art.
- ///
- private static IEnumerable BuiltIn()
- {
- yield return new FloorPattern
- {
- Name = "Gargish Green, bordered",
- BuiltIn = true,
- NorthWest = 16821, NorthEast = 16823, SouthWest = 16826, SouthEast = 16828,
- North = { 16822 }, West = { 16824 }, East = { 16825 }, South = { 16827 },
- Fill = { 16815, 16816, 16817, 16818 },
- FillWidth = 2
- };
- yield return new FloorPattern
- {
- Name = "Gargish Motif, bordered",
- BuiltIn = true,
- NorthWest = 16860, NorthEast = 16862, SouthWest = 16866, SouthEast = 16868,
- North = { 16861 }, West = { 16863 }, East = { 16865 }, South = { 16867 },
- Fill = { 16864 },
- FillWidth = 1
- };
- }
-
- private static List LoadUser()
- {
- var result = new List();
- try
- {
- if (!File.Exists(FilePath))
- {
- return result;
- }
-
- var dom = new XmlDocument();
- dom.Load(FilePath);
- foreach (XmlElement node in dom.SelectNodes("/FloorPatterns/Pattern"))
- {
- var pattern = new FloorPattern
- {
- Name = node.GetAttribute("name"),
- NorthWest = One(node, "nw"),
- NorthEast = One(node, "ne"),
- SouthWest = One(node, "sw"),
- SouthEast = One(node, "se"),
- North = Many(node, "north"),
- South = Many(node, "south"),
- West = Many(node, "west"),
- East = Many(node, "east"),
- Fill = Many(node, "fill"),
- FillWidth = Math.Max(1, (int)One(node, "fillWidth"))
- };
- if (!string.IsNullOrWhiteSpace(pattern.Name) && pattern.Pieces().Any())
- {
- result.Add(pattern);
- }
- }
- }
- catch (Exception ex) when (ex is IOException or XmlException or UnauthorizedAccessException)
- {
- // A damaged file must not keep the editor from opening; the patterns in it are skipped.
- }
-
- return result;
- }
-
- private static void SaveUser()
- {
- try
- {
- var dom = new XmlDocument();
- XmlElement root = dom.CreateElement("FloorPatterns");
- dom.AppendChild(root);
- foreach (FloorPattern pattern in _user)
- {
- XmlElement node = dom.CreateElement("Pattern");
- node.SetAttribute("name", pattern.Name);
- node.SetAttribute("nw", Text(pattern.NorthWest));
- node.SetAttribute("ne", Text(pattern.NorthEast));
- node.SetAttribute("sw", Text(pattern.SouthWest));
- node.SetAttribute("se", Text(pattern.SouthEast));
- node.SetAttribute("north", Text(pattern.North));
- node.SetAttribute("south", Text(pattern.South));
- node.SetAttribute("west", Text(pattern.West));
- node.SetAttribute("east", Text(pattern.East));
- node.SetAttribute("fillWidth", pattern.FillWidth.ToString(CultureInfo.InvariantCulture));
- node.SetAttribute("fill", Text(pattern.Fill));
- root.AppendChild(node);
- }
-
- Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
- dom.Save(FilePath);
- }
- catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
- {
- MessageBox.Show("The floor patterns could not be saved: " + ex.Message, "Multi Editor", MessageBoxButtons.OK, MessageBoxIcon.Warning);
- }
- }
-
- private static string Text(ushort id) => "0x" + id.ToString("X4", CultureInfo.InvariantCulture);
-
- private static string Text(IEnumerable ids) => string.Join(",", ids.Select(Text));
-
- private static ushort One(XmlElement node, string attribute) => Many(node, attribute).FirstOrDefault();
-
- private static List Many(XmlElement node, string attribute)
- {
- var result = new List();
- foreach (string part in node.GetAttribute(attribute).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
- {
- bool hex = part.StartsWith("0x", StringComparison.OrdinalIgnoreCase);
- if (ushort.TryParse(hex ? part.AsSpan(2) : part.AsSpan(), hex ? NumberStyles.HexNumber : NumberStyles.Integer,
- CultureInfo.InvariantCulture, out ushort id))
- {
- result.Add(id);
- }
- }
-
- return result;
- }
- }
-
- ///
- /// Lays the session's floor pattern over a dragged rectangle on the work plane (or on top of
- /// what the mouse points at). Flat tiles already at that Z in those cells are replaced.
- ///
- internal sealed class FloorPatternTool : EditorTool
- {
- private readonly EditorSession _session;
- private bool _dragging;
- private int _z;
- private int _startX;
- private int _startY;
- private int _endX;
- private int _endY;
-
- public FloorPatternTool(EditorSession session) : base(session)
- {
- _session = session;
- }
-
- public override bool IsDragging => _dragging;
-
- public override bool TracksCursorCell => true;
-
- public override void OnMouseDown(MouseEventArgs e)
- {
- if (_session.FloorPattern == null)
- {
- return;
- }
-
- BaseCell(out _startX, out _startY, out _z);
- _endX = _startX;
- _endY = _startY;
- _dragging = true;
- }
-
- public override void OnMouseMove(MouseEventArgs e)
- {
- if (_dragging)
- {
- Context.PlaneCell(Context.MouseLoc, _z, out _endX, out _endY);
- }
- }
-
- public override void OnMouseUp(MouseEventArgs e)
- {
- if (!_dragging)
- {
- return;
- }
-
- _dragging = false;
- Context.PlaneCell(Context.MouseLoc, _z, out _endX, out _endY);
- var (remove, add) = Plan(_startX, _startY, _endX, _endY, _z);
- if (remove.Count > 0 || add.Count > 0)
- {
- Context.CompList.ReplaceTiles(remove, add, "Floor pattern");
- Context.AfterEdit(_z);
- }
- }
-
- public override void Cancel()
- {
- _dragging = false;
- }
-
- public override void PaintOverlay(IToolOverlay overlay)
- {
- if (_session.FloorPattern == null)
- {
- return;
- }
-
- int sx, sy, ex, ey, z;
- if (_dragging)
- {
- (sx, sy, ex, ey, z) = (_startX, _startY, _endX, _endY, _z);
- }
- else
- {
- BaseCell(out sx, out sy, out z);
- (ex, ey) = (sx, sy);
- }
-
- var (remove, add) = Plan(sx, sy, ex, ey, z);
- foreach (MultiTile tile in remove)
- {
- overlay.Highlight(tile, TileHighlight.Remove);
- }
-
- foreach ((ushort id, int x, int y, int tz) in add)
- {
- overlay.Ghost(id, x, y, tz);
- }
- }
-
- private void BaseCell(out int x, out int y, out int z)
- {
- Context.CellAt(Context.MouseLoc, out x, out y, out z);
- if (Context.WorkZ is { } baseZ)
- {
- z = baseZ;
- Context.PlaneCell(Context.MouseLoc, z, out x, out y);
- }
- }
-
- private (List Remove, List<(ushort Id, int X, int Y, int Z)> Add) Plan(int startX, int startY, int endX, int endY, int z)
- {
- var remove = new List();
- var add = new List<(ushort, int, int, int)>();
- MultiEditorComponentList list = Context.CompList;
- int x0 = Math.Min(startX, endX), x1 = Math.Max(startX, endX);
- int y0 = Math.Min(startY, endY), y1 = Math.Max(startY, endY);
-
- foreach ((ushort id, int x, int y) in _session.FloorPattern.Layout(x0, y0, x1, y1))
- {
- if (!list.InBounds(x, y))
- {
- continue;
- }
-
- bool there = false;
- foreach (MultiTile tile in list.GetTilesAt(x, y))
- {
- if (tile.Z != z || tile.Height != 0)
- {
- continue;
- }
-
- if (tile.Id == id)
- {
- there = true;
- }
- else
- {
- remove.Add(tile);
- }
- }
-
- if (!there)
- {
- add.Add((id, x, y, z));
- }
- }
-
- return (remove, add);
- }
- }
}
diff --git a/UoFiddler.Plugin.MultiEditor/Editing/FloorPatterns.cs b/UoFiddler.Plugin.MultiEditor/Editing/FloorPatterns.cs
new file mode 100644
index 00000000..777dd39c
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Editing/FloorPatterns.cs
@@ -0,0 +1,194 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Windows.Forms;
+using System.Xml;
+using Ultima;
+using UoFiddler.Controls.Classes;
+
+namespace UoFiddler.Plugin.MultiEditor.Editing
+{
+ ///
+ /// The floor patterns: a few shipped ones for tile sets whose border pieces are known, and the
+ /// ones the user saved (MultiEditorFloorPatterns.xml next to the other multi editor files).
+ ///
+ internal static class FloorPatterns
+ {
+ private static List _user;
+
+ public static string FilePath => Path.Combine(Options.AppDataPath ?? string.Empty, "plugins", "MultiEditorFloorPatterns.xml");
+
+ /// User patterns first (newest last), then the shipped ones this client has the art for.
+ public static List All()
+ {
+ _user ??= LoadUser();
+ var all = new List(_user);
+ foreach (FloorPattern pattern in BuiltIn())
+ {
+ if (pattern.Pieces().All(id => Art.IsValidStatic(id)) && all.All(p => p.Name != pattern.Name))
+ {
+ all.Add(pattern);
+ }
+ }
+
+ return all;
+ }
+
+ public static void Save(FloorPattern pattern)
+ {
+ _user ??= LoadUser();
+ _user.RemoveAll(p => string.Equals(p.Name, pattern.Name, StringComparison.OrdinalIgnoreCase));
+ _user.Add(pattern);
+ SaveUser();
+ }
+
+ public static void Delete(FloorPattern pattern)
+ {
+ _user ??= LoadUser();
+ if (_user.Remove(pattern))
+ {
+ SaveUser();
+ }
+ }
+
+ /// Forgets what was read, after the profile or client changed.
+ public static void Reset()
+ {
+ _user = null;
+ }
+
+ ///
+ /// Sets read off the client's art: the piece with its band on a side goes on that side of
+ /// the floor. Checked by eye against the 7.0.114.4 art.
+ ///
+ private static IEnumerable BuiltIn()
+ {
+ yield return new FloorPattern
+ {
+ Name = "Gargish Green, bordered",
+ BuiltIn = true,
+ NorthWest = 16821, NorthEast = 16823, SouthWest = 16826, SouthEast = 16828,
+ North = { 16822 }, West = { 16824 }, East = { 16825 }, South = { 16827 },
+ Fill = { 16815, 16816, 16817, 16818 },
+ FillWidth = 2
+ };
+ yield return new FloorPattern
+ {
+ Name = "Gargish Motif, bordered",
+ BuiltIn = true,
+ NorthWest = 16860, NorthEast = 16862, SouthWest = 16866, SouthEast = 16868,
+ North = { 16861 }, West = { 16863 }, East = { 16865 }, South = { 16867 },
+ Fill = { 16864 },
+ FillWidth = 1
+ };
+ }
+
+ private static List LoadUser()
+ {
+ var result = new List();
+ try
+ {
+ if (!File.Exists(FilePath))
+ {
+ return result;
+ }
+
+ var dom = new XmlDocument();
+ dom.Load(FilePath);
+ foreach (XmlElement node in dom.SelectNodes("/FloorPatterns/Pattern"))
+ {
+ var pattern = new FloorPattern
+ {
+ Name = node.GetAttribute("name"),
+ NorthWest = One(node, "nw"),
+ NorthEast = One(node, "ne"),
+ SouthWest = One(node, "sw"),
+ SouthEast = One(node, "se"),
+ North = Many(node, "north"),
+ South = Many(node, "south"),
+ West = Many(node, "west"),
+ East = Many(node, "east"),
+ Fill = Many(node, "fill"),
+ FillWidth = Math.Max(1, (int)One(node, "fillWidth"))
+ };
+ if (!string.IsNullOrWhiteSpace(pattern.Name) && pattern.Pieces().Any())
+ {
+ result.Add(pattern);
+ }
+ }
+ }
+ catch (Exception ex) when (ex is IOException or XmlException or UnauthorizedAccessException)
+ {
+ // A damaged file must not keep the editor from opening; the patterns in it are skipped.
+ }
+
+ return result;
+ }
+
+ private static void SaveUser()
+ {
+ try
+ {
+ var dom = new XmlDocument();
+ XmlElement root = dom.CreateElement("FloorPatterns");
+ dom.AppendChild(root);
+ foreach (FloorPattern pattern in _user)
+ {
+ XmlElement node = dom.CreateElement("Pattern");
+ node.SetAttribute("name", pattern.Name);
+ node.SetAttribute("nw", Text(pattern.NorthWest));
+ node.SetAttribute("ne", Text(pattern.NorthEast));
+ node.SetAttribute("sw", Text(pattern.SouthWest));
+ node.SetAttribute("se", Text(pattern.SouthEast));
+ node.SetAttribute("north", Text(pattern.North));
+ node.SetAttribute("south", Text(pattern.South));
+ node.SetAttribute("west", Text(pattern.West));
+ node.SetAttribute("east", Text(pattern.East));
+ node.SetAttribute("fillWidth", pattern.FillWidth.ToString(CultureInfo.InvariantCulture));
+ node.SetAttribute("fill", Text(pattern.Fill));
+ root.AppendChild(node);
+ }
+
+ Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
+ dom.Save(FilePath);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ MessageBox.Show("The floor patterns could not be saved: " + ex.Message, "Multi Editor", MessageBoxButtons.OK, MessageBoxIcon.Warning);
+ }
+ }
+
+ private static string Text(ushort id) => "0x" + id.ToString("X4", CultureInfo.InvariantCulture);
+
+ private static string Text(IEnumerable ids) => string.Join(",", ids.Select(Text));
+
+ private static ushort One(XmlElement node, string attribute) => Many(node, attribute).FirstOrDefault();
+
+ private static List Many(XmlElement node, string attribute)
+ {
+ var result = new List();
+ foreach (string part in node.GetAttribute(attribute).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
+ {
+ bool hex = part.StartsWith("0x", StringComparison.OrdinalIgnoreCase);
+ if (ushort.TryParse(hex ? part.AsSpan(2) : part.AsSpan(), hex ? NumberStyles.HexNumber : NumberStyles.Integer,
+ CultureInfo.InvariantCulture, out ushort id))
+ {
+ result.Add(id);
+ }
+ }
+
+ return result;
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Editing/LevelDefinition.cs b/UoFiddler.Plugin.MultiEditor/Editing/LevelDefinition.cs
new file mode 100644
index 00000000..1c9886b4
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Editing/LevelDefinition.cs
@@ -0,0 +1,14 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Plugin.MultiEditor.Editing
+{
+ /// How the user splits a design into levels: a name and the Z the level starts at.
+ internal readonly record struct LevelDefinition(string Name, int StartZ);
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Editing/PreviewTerrain.cs b/UoFiddler.Plugin.MultiEditor/Editing/PreviewTerrain.cs
new file mode 100644
index 00000000..12c9b371
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Editing/PreviewTerrain.cs
@@ -0,0 +1,21 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Plugin.MultiEditor.Editing
+{
+ /// The ground a previewed multi stands on.
+ internal enum PreviewTerrain
+ {
+ None,
+ Grass,
+ Dirt,
+ Sand,
+ Snow
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Editing/ToolKind.cs b/UoFiddler.Plugin.MultiEditor/Editing/ToolKind.cs
new file mode 100644
index 00000000..70a33721
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Editing/ToolKind.cs
@@ -0,0 +1,39 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Plugin.MultiEditor.Editing
+{
+ ///
+ /// The tools of the editor, by the name the UI shows.
+ ///
+ internal enum ToolKind
+ {
+ Select,
+ Lasso,
+ Draw,
+ Remove,
+ Altitude,
+ Pipette,
+ Transparent,
+ RectFill,
+ Line,
+ Wall,
+ Floor,
+ Door,
+ Stair,
+ Roof,
+ Foundation,
+
+ /// Lays a bordered floor pattern; chosen from the House page, not the palette.
+ FloorPattern,
+
+ /// Designs a whole house as a draft and places it.
+ House
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/FrontDoorSide.cs b/UoFiddler.Plugin.MultiEditor/House/FrontDoorSide.cs
new file mode 100644
index 00000000..0c3a48b3
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/FrontDoorSide.cs
@@ -0,0 +1,28 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ ///
+ /// A house being designed, beside its wings: the materials of each storey and what was changed
+ /// by hand (partitions, openings, doors, windows, floor areas, stairs).
+ /// turns wings and draft into tiles. A wing's box is its wall cells, as the wall tool drags
+ /// them: walls stand on the +Y / +X edges of their cells, so the rooms inside are the box
+ /// without its first row and column.
+ ///
+ /// The outer wall of the first wing that gets the front door.
+ internal enum FrontDoorSide
+ {
+ None,
+ South,
+ East
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/HouseDraft.Build.cs b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.Build.cs
new file mode 100644
index 00000000..bb8e60c4
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.Build.cs
@@ -0,0 +1,344 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using UoFiddler.Plugin.MultiEditor.Styles;
+using UoFiddler.Plugin.MultiEditor.Tools;
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ internal sealed partial class HouseDraft
+ {
+ /// The tiles of a built draft, each with its layer, and the walls among them.
+ public sealed class Built
+ {
+ public List<(ushort Id, int X, int Y, int Z, string Layer)> Tiles { get; } = new List<(ushort, int, int, int, string)>();
+
+ public List<(ushort Id, int X, int Y, int Z)> Walls { get; } = new List<(ushort, int, int, int)>();
+ }
+
+ ///
+ /// Foundation, walls with their doors and windows, floors and stairs of the house, storey
+ /// by storey. The roof is not part of it: the roof tool plans it over these walls.
+ ///
+ public Built Build(IReadOnlyList wings, HouseStyles styles)
+ {
+ var built = new Built();
+ int top = Top(wings);
+ var cut = new HashSet<(int X, int Y)>[MaxStoreys + 1];
+
+ // Stairs first: a run opens the floor of the storey it climbs to.
+ foreach ((int storey, int x, int y, string column, HouseStyle style) in Stairs)
+ {
+ if (storey >= top || !Region(wings, storey).Contains((x, y)))
+ {
+ continue;
+ }
+
+ foreach ((ushort id, int tx, int ty, int tz) in StairTool.Tiles(style, column, x, y, BaseZ + (storey * StoreyHeight)))
+ {
+ built.Tiles.Add((id, tx, ty, tz, StairsLayer));
+ (cut[storey + 1] ??= new HashSet<(int X, int Y)>()).Add((tx, ty));
+ }
+ }
+
+ for (int storey = 0; storey < top; ++storey)
+ {
+ int z = BaseZ + (storey * StoreyHeight);
+ HashSet<(int X, int Y)> region = Region(wings, storey);
+ StoreyLayout layout = LayOut(wings, storey);
+ HashSet<(int X, int Y)> south = layout.South, east = layout.East;
+
+ HouseStyle foundation = FoundationStyle;
+ if (foundation == null)
+ {
+ styles.TryGetRole(FoundationTool.FoundationPost, out foundation, out _);
+ }
+
+ if (storey == 0 && Foundation && foundation != null)
+ {
+ var ringSouth = new HashSet<(int X, int Y)>();
+ var ringEast = new HashSet<(int X, int Y)>();
+ Outline(region, ringSouth, ringEast);
+ foreach ((int x, int y) in WallCells(ringSouth, ringEast))
+ {
+ string column = WallPlanner.PieceFor(ringSouth, ringEast, x, y);
+ ushort id = column != null ? foundation.Get(column) : (ushort)0;
+ // One row, or rows one on the other, each as high as the piece.
+ int rise = id != 0 ? Math.Max(1, (int)Ultima.TileData.ItemTable[id].Height) : 0;
+ for (int tier = 0; id != 0 && tier < Math.Clamp(FoundationTiers, 1, 3); ++tier)
+ {
+ built.Tiles.Add((id, x, y, z - FoundationHeight + (tier * rise), FoundationLayer));
+ }
+ }
+ }
+
+ HouseStyle wallStyle = WallStyles[storey];
+ foreach ((int x, int y) in WallCells(south, east))
+ {
+ if (Doors.TryGetValue((storey, x, y), out (HouseStyle Style, string Piece) door) &&
+ (WallPlanner.DoorAlongX(door.Piece) ? south : east).Contains((x, y)) && door.Style.Get(door.Piece) is var doorId and not 0)
+ {
+ built.Tiles.Add((doorId, x, y, z, WallsLayer));
+ built.Walls.Add((doorId, x, y, z));
+ continue;
+ }
+
+ // A door the draft hangs by itself: between rooms, or the front door.
+ if (DoorStyle != null && layout.Doors.TryGetValue((x, y), out string ownPiece) &&
+ (WallPlanner.DoorAlongX(ownPiece) ? south : east).Contains((x, y)) && DoorStyle.Get(ownPiece) is var ownId and not 0)
+ {
+ built.Tiles.Add((ownId, x, y, z, WallsLayer));
+ built.Walls.Add((ownId, x, y, z));
+ continue;
+ }
+
+ string column = WallPlanner.PieceFor(wallStyle, south, east, x, y);
+ if (column == null || wallStyle == null)
+ {
+ continue;
+ }
+
+ ushort id = wallStyle.Get(column);
+ if ((Windows.Contains((storey, x, y)) || layout.Windows.Contains((x, y))) && column != "Corner" && column != "Post" &&
+ styles.WindowFor(wallStyle, south.Contains((x, y))) is var windowId and not 0)
+ {
+ id = windowId;
+ }
+
+ if (id != 0)
+ {
+ built.Tiles.Add((id, x, y, z, WallsLayer));
+ built.Walls.Add((id, x, y, z));
+ }
+ }
+
+ foreach ((int x, int y) in region)
+ {
+ if (cut[storey] != null && cut[storey].Contains((x, y)))
+ {
+ continue;
+ }
+
+ HouseStyle floorStyle = FloorStyles[storey];
+ foreach ((int areaStorey, int x0, int y0, int x1, int y1, HouseStyle areaStyle) in FloorAreas)
+ {
+ if (areaStorey == storey && x >= x0 && x <= x1 && y >= y0 && y <= y1)
+ {
+ floorStyle = areaStyle;
+ }
+ }
+
+ if (floorStyle == null)
+ {
+ continue;
+ }
+
+ ushort[] pieces = Pieces(floorStyle);
+ if (pieces.Length > 0)
+ {
+ // The same cell always gets the same piece, so the preview does not flicker.
+ built.Tiles.Add((pieces[(int)((uint)HashCode.Combine(x, y, storey) % (uint)pieces.Length)], x, y, z, FloorsLayer));
+ }
+ }
+ }
+
+ // Flat roofs: the floor of the wing's top storey once more, on top of its walls. Where a
+ // taller wing stands, its own floor is there already.
+ foreach (RoofWing wing in wings)
+ {
+ int storeys = Math.Clamp(wing.Storeys, 1, MaxStoreys);
+ HouseStyle style = FlatRoofStyle ?? FloorStyles[storeys - 1];
+ if (wing.NoRoof || wing.Shape != RoofShape.Flat || style == null)
+ {
+ continue;
+ }
+
+ HashSet<(int X, int Y)> above = Region(wings, storeys);
+ ushort[] pieces = Pieces(style);
+ for (int x = wing.X0 + 1; pieces.Length > 0 && x <= wing.X1; ++x)
+ {
+ for (int y = wing.Y0 + 1; y <= wing.Y1; ++y)
+ {
+ if (!above.Contains((x, y)))
+ {
+ built.Tiles.Add((pieces[(int)((uint)HashCode.Combine(x, y, storeys) % (uint)pieces.Length)], x, y,
+ BaseZ + (storeys * StoreyHeight), RoofTool.LayerName));
+ }
+ }
+ }
+ }
+
+ if (Parapet)
+ {
+ AddParapets(wings, styles, built);
+ }
+
+ if (Foundation && StairStyle != null && top > 0 && LayOut(wings, 0).FrontDoor is { } front)
+ {
+ AddSteps(front, styles, built);
+ }
+
+ return built;
+ }
+
+ ///
+ /// Steps up to the front door of a house on a foundation, as the client's houses have
+ /// them: one row outside the door, a step under it and a corner piece on each side, 5
+ /// below the floor (the pieces are 5 high).
+ ///
+ private void AddSteps((int X, int Y) door, HouseStyles styles, Built built)
+ {
+ bool south = FrontDoor == FrontDoorSide.South;
+ ushort step = StairStyle.Get(south ? "North" : "West");
+ if (step == 0)
+ {
+ return;
+ }
+
+ // The step's top meets the floor; on a foundation lower than the step it starts where the foundation does.
+ int z = BaseZ - Math.Min(FoundationHeight, Math.Max(1, (int)Ultima.TileData.ItemTable[step].Height));
+ (int X, int Y) at = south ? (door.X, door.Y + 1) : (door.X + 1, door.Y);
+ built.Tiles.Add((step, at.X, at.Y, z, StairsLayer));
+
+ // The corners: south-east, north-east, north-west, south-west of a stair set.
+ ushort before = StairStyle.Get("Squared1"), after = StairStyle.Get("Squared2");
+ if (after != 0 && styles.TryGetStairCorner(after, out ushort[] corners, out _) && corners.Length == 4)
+ {
+ (before, after) = south ? (corners[3], corners[0]) : (corners[1], corners[0]);
+ }
+ else if (!south)
+ {
+ (before, after) = (0, 0);
+ }
+
+ if (before != 0 && (south ? at.X : at.Y) > 0)
+ {
+ built.Tiles.Add((before, south ? at.X - 1 : at.X, south ? at.Y : at.Y - 1, z, StairsLayer));
+ }
+
+ if (after != 0)
+ {
+ built.Tiles.Add((after, south ? at.X + 1 : at.X, south ? at.Y : at.Y + 1, z, StairsLayer));
+ }
+ }
+
+ ///
+ /// Battlements around the flat roofs. The flat wings of one height are walled as one
+ /// roof: along its edge, but not where a taller wing stands (its wall is there). Measured
+ /// on the client's tower, keep and castle: the edging stands in the roof's wall cells at
+ /// the roof's Z and once more on top of that, and a third row has every second straight
+ /// piece, leaving the corners out.
+ ///
+ private void AddParapets(IReadOnlyList wings, HouseStyles styles, Built built)
+ {
+ // A wing without a roof is a walled yard: its walls carry battlements too.
+ foreach (IGrouping level in wings.Where(w => w.NoRoof || w.Shape == RoofShape.Flat).GroupBy(w => Math.Clamp(w.Storeys, 1, MaxStoreys)))
+ {
+ int storeys = level.Key;
+ HouseStyle style = styles.ParapetFor(WallStyles[storeys - 1]);
+ if (style == null)
+ {
+ continue;
+ }
+
+ HashSet<(int X, int Y)> above = Region(wings, storeys);
+ var roof = new HashSet<(int X, int Y)>();
+ foreach (RoofWing wing in level)
+ {
+ for (int x = wing.X0 + 1; x <= wing.X1; ++x)
+ {
+ for (int y = wing.Y0 + 1; y <= wing.Y1; ++y)
+ {
+ if (!above.Contains((x, y)))
+ {
+ roof.Add((x, y));
+ }
+ }
+ }
+ }
+
+ if (roof.Count == 0)
+ {
+ continue;
+ }
+
+ var south = new HashSet<(int X, int Y)>();
+ var east = new HashSet<(int X, int Y)>();
+ Outline(roof, south, east);
+ south.RemoveWhere(c => above.Contains(c) || above.Contains((c.X, c.Y + 1)));
+ east.RemoveWhere(c => above.Contains(c) || above.Contains((c.X + 1, c.Y)));
+
+ // The wall cells start one before the roof cells; the tower counts its merlons from there.
+ int minX = roof.Min(c => c.X) - 1, minY = roof.Min(c => c.Y) - 1;
+ int z = BaseZ + (storeys * StoreyHeight);
+ int tier = Math.Max(1, (int)Ultima.TileData.ItemTable[style.Get("South2")].Height);
+ foreach ((int x, int y) in WallCells(south, east))
+ {
+ string column = WallPlanner.PieceFor(south, east, x, y);
+ ushort id = column != null ? style.Get(column) : (ushort)0;
+ if (id == 0)
+ {
+ continue;
+ }
+
+ built.Tiles.Add((id, x, y, z, RoofTool.LayerName));
+ built.Tiles.Add((id, x, y, z + tier, RoofTool.LayerName));
+
+ // The merlons: every second straight piece.
+ bool alongX = column.StartsWith("South", StringComparison.Ordinal), alongY = column.StartsWith("East", StringComparison.Ordinal);
+ if ((alongX && (x - minX) % 2 == 0) || (alongY && (y - minY) % 2 == 0))
+ {
+ built.Tiles.Add((id, x, y, z + (2 * tier), RoofTool.LayerName));
+ }
+ else if (column == "Corner" && (x - minX) % 2 == 0 && style.Get("South2") is var merlon and not 0)
+ {
+ // A corner cell in step with the wall along X carries that wall's merlon (the tower's inner corner does).
+ built.Tiles.Add((merlon, x, y, z + (2 * tier), RoofTool.LayerName));
+ }
+ }
+ }
+ }
+
+ private readonly Dictionary _pieces = new Dictionary();
+
+ private ushort[] Pieces(HouseStyle style)
+ {
+ if (!_pieces.TryGetValue(style, out ushort[] pieces))
+ {
+ _pieces[style] = pieces = style.Slots.Values.Where(id => HouseStyle.InTileData(id)).Distinct().ToArray();
+ }
+
+ return pieces;
+ }
+
+ /// Every cell that may hold a wall piece: the cells with an edge, and the ones a post goes in.
+ private static HashSet<(int X, int Y)> WallCells(HashSet<(int X, int Y)> south, HashSet<(int X, int Y)> east)
+ {
+ var cells = new HashSet<(int X, int Y)>(south);
+ cells.UnionWith(east);
+ foreach ((int x, int y) in south)
+ {
+ cells.Add((x - 1, y));
+ }
+
+ foreach ((int x, int y) in east)
+ {
+ cells.Add((x, y - 1));
+ }
+
+ cells.RemoveWhere(c => c.X < 0 || c.Y < 0);
+ return cells;
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/HouseDraft.HandEdits.cs b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.HandEdits.cs
new file mode 100644
index 00000000..afd2318d
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.HandEdits.cs
@@ -0,0 +1,179 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System.Collections.Generic;
+using System.Linq;
+using UoFiddler.Plugin.MultiEditor.Styles;
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ internal sealed partial class HouseDraft
+ {
+ ///
+ /// Moves what was changed by hand inside a wing along with that wing: walls added and
+ /// taken away, doors, windows, floor areas and stairs whose cell lies in the box.
+ ///
+ public void ShiftWithin((int X0, int Y0, int X1, int Y1) box, int dx, int dy)
+ {
+ if (dx == 0 && dy == 0)
+ {
+ return;
+ }
+
+ bool In(int x, int y) => x >= box.X0 && x <= box.X1 && y >= box.Y0 && y <= box.Y1;
+ void Move(HashSet<(int X, int Y)> set)
+ {
+ var moved = new List<(int X, int Y)>();
+ foreach ((int x, int y) in set)
+ {
+ moved.Add(In(x, y) ? (x + dx, y + dy) : (x, y));
+ }
+
+ set.Clear();
+ set.UnionWith(moved);
+ }
+
+ void MoveOnStoreys(HashSet<(int Storey, int X, int Y)> set)
+ {
+ var moved = new List<(int Storey, int X, int Y)>();
+ foreach ((int storey, int x, int y) in set)
+ {
+ moved.Add(In(x, y) ? (storey, x + dx, y + dy) : (storey, x, y));
+ }
+
+ set.Clear();
+ set.UnionWith(moved);
+ }
+
+ for (int k = 0; k < MaxStoreys; ++k)
+ {
+ Move(AddedSouth[k]);
+ Move(AddedEast[k]);
+ Move(ErasedSouth[k]);
+ Move(ErasedEast[k]);
+ }
+
+ MoveOnStoreys(Windows);
+ MoveOnStoreys(Suppressed);
+ var doors = new List>(Doors);
+ Doors.Clear();
+ foreach (var door in doors)
+ {
+ (int storey, int x, int y) = door.Key;
+ Doors[In(x, y) ? (storey, x + dx, y + dy) : door.Key] = door.Value;
+ }
+
+ for (int i = 0; i < FloorAreas.Count; ++i)
+ {
+ var a = FloorAreas[i];
+ if (In(a.X0, a.Y0) && In(a.X1, a.Y1))
+ {
+ FloorAreas[i] = (a.Storey, a.X0 + dx, a.Y0 + dy, a.X1 + dx, a.Y1 + dy, a.Style);
+ }
+ }
+
+ for (int i = 0; i < Stairs.Count; ++i)
+ {
+ var s = Stairs[i];
+ if (In(s.X, s.Y))
+ {
+ Stairs[i] = (s.Storey, s.X + dx, s.Y + dy, s.Column, s.Style);
+ }
+ }
+ }
+
+ ///
+ /// What was changed by hand inside a wing, for a copy of the wing: walls added and taken
+ /// away, doors, windows, floor areas and stairs whose cell lies in the box.
+ ///
+ public HouseDraft CopyWithin((int X0, int Y0, int X1, int Y1) box)
+ {
+ var part = new HouseDraft();
+ CopyHandEditsInto(part, box);
+ return part;
+ }
+
+ // A box that holds every cell.
+ private static readonly (int X0, int Y0, int X1, int Y1) _everywhere = (int.MinValue, int.MinValue, int.MaxValue, int.MaxValue);
+
+ /// Adds the hand edits whose cell lies in the box to .
+ private void CopyHandEditsInto(HouseDraft part, (int X0, int Y0, int X1, int Y1) box)
+ {
+ bool In(int x, int y) => x >= box.X0 && x <= box.X1 && y >= box.Y0 && y <= box.Y1;
+ for (int k = 0; k < MaxStoreys; ++k)
+ {
+ part.AddedSouth[k].UnionWith(AddedSouth[k].Where(c => In(c.X, c.Y)));
+ part.AddedEast[k].UnionWith(AddedEast[k].Where(c => In(c.X, c.Y)));
+ part.ErasedSouth[k].UnionWith(ErasedSouth[k].Where(c => In(c.X, c.Y)));
+ part.ErasedEast[k].UnionWith(ErasedEast[k].Where(c => In(c.X, c.Y)));
+ }
+
+ foreach (var door in Doors)
+ {
+ if (In(door.Key.X, door.Key.Y))
+ {
+ part.Doors[door.Key] = door.Value;
+ }
+ }
+
+ part.Windows.UnionWith(Windows.Where(c => In(c.X, c.Y)));
+ part.Suppressed.UnionWith(Suppressed.Where(c => In(c.X, c.Y)));
+ part.FloorAreas.AddRange(FloorAreas.Where(a => In(a.X0, a.Y0) && In(a.X1, a.Y1)));
+ part.Stairs.AddRange(Stairs.Where(s => In(s.X, s.Y)));
+ }
+
+ /// Adds what took, moved by this many cells: the hand edits of a pasted wing.
+ public void AddShifted(HouseDraft part, int dx, int dy)
+ {
+ HouseDraft moved = part.Clone();
+ moved.Shift(dx, dy);
+
+ // Where the pasted wing says otherwise, it wins: a wall added there is no longer
+ // taken away, a door replaces a window, and the reverse.
+ for (int k = 0; k < MaxStoreys; ++k)
+ {
+ ErasedSouth[k].ExceptWith(moved.AddedSouth[k]);
+ ErasedEast[k].ExceptWith(moved.AddedEast[k]);
+ AddedSouth[k].ExceptWith(moved.ErasedSouth[k]);
+ AddedEast[k].ExceptWith(moved.ErasedEast[k]);
+ AddedSouth[k].UnionWith(moved.AddedSouth[k]);
+ AddedEast[k].UnionWith(moved.AddedEast[k]);
+ ErasedSouth[k].UnionWith(moved.ErasedSouth[k]);
+ ErasedEast[k].UnionWith(moved.ErasedEast[k]);
+ }
+
+ foreach (var door in moved.Doors)
+ {
+ Doors[door.Key] = door.Value;
+ Windows.Remove(door.Key);
+ }
+
+ foreach (var window in moved.Windows)
+ {
+ Windows.Add(window);
+ Doors.Remove(window);
+ }
+
+ Suppressed.UnionWith(moved.Suppressed);
+ FloorAreas.AddRange(moved.FloorAreas);
+
+ // A stair already starting in a cell gives way to the pasted one.
+ foreach (var stair in moved.Stairs)
+ {
+ Stairs.RemoveAll(s => s.Storey == stair.Storey && s.X == stair.X && s.Y == stair.Y);
+ Stairs.Add(stair);
+ }
+ }
+
+ /// Moves everything changed by hand along with the house.
+ public void Shift(int dx, int dy) => ShiftWithin(_everywhere, dx, dy);
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/HouseDraft.Layout.cs b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.Layout.cs
new file mode 100644
index 00000000..e0221dce
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.Layout.cs
@@ -0,0 +1,533 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using UoFiddler.Plugin.MultiEditor.Styles;
+using UoFiddler.Plugin.MultiEditor.Tools;
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ internal sealed partial class HouseDraft
+ {
+ /// Storeys of the tallest wing.
+ public static int Top(IReadOnlyList wings)
+ {
+ int top = 0;
+ foreach (RoofWing wing in wings)
+ {
+ top = Math.Max(top, Math.Clamp(wing.Storeys, 1, MaxStoreys));
+ }
+
+ return top;
+ }
+
+ /// The cells inside the house on a storey (0 is the ground floor): the rooms of every wing that high.
+ public static HashSet<(int X, int Y)> Region(IReadOnlyList wings, int storey)
+ {
+ var region = new HashSet<(int X, int Y)>();
+ foreach (RoofWing wing in wings)
+ {
+ if (wing.Storeys <= storey)
+ {
+ continue;
+ }
+
+ for (int x = wing.X0 + 1; x <= wing.X1; ++x)
+ {
+ for (int y = wing.Y0 + 1; y <= wing.Y1; ++y)
+ {
+ region.Add((x, y));
+ }
+ }
+ }
+
+ return region;
+ }
+
+ /// The wall edges around a region: its outline.
+ public static void Outline(HashSet<(int X, int Y)> region, HashSet<(int X, int Y)> south, HashSet<(int X, int Y)> east)
+ {
+ foreach ((int x, int y) in region)
+ {
+ if (!region.Contains((x, y + 1)))
+ {
+ south.Add((x, y));
+ }
+
+ if (!region.Contains((x, y - 1)))
+ {
+ south.Add((x, y - 1));
+ }
+
+ if (!region.Contains((x + 1, y)))
+ {
+ east.Add((x, y));
+ }
+
+ if (!region.Contains((x - 1, y)))
+ {
+ east.Add((x - 1, y));
+ }
+ }
+ }
+
+ /// The wall edges of a storey with its generated doors and windows.
+ public sealed class StoreyLayout
+ {
+ /// Cells with a wall on their +Y edge.
+ public HashSet<(int X, int Y)> South { get; } = new HashSet<(int X, int Y)>();
+
+ /// Cells with a wall on their +X edge.
+ public HashSet<(int X, int Y)> East { get; } = new HashSet<(int X, int Y)>();
+
+ /// Doors the draft makes itself (room doors, the front door): wall cell and door piece.
+ public Dictionary<(int X, int Y), string> Doors { get; } = new Dictionary<(int X, int Y), string>();
+
+ /// Wall cells the draft makes windows itself.
+ public HashSet<(int X, int Y)> Windows { get; } = new HashSet<(int X, int Y)>();
+
+ /// The wall cell of the front door, when the storey has one.
+ public (int X, int Y)? FrontDoor { get; set; }
+ }
+
+ ///
+ /// The wall edges of a storey: the outline of its rooms, with the edges added by hand that
+ /// still touch a room and without the ones taken away.
+ ///
+ public void Edges(IReadOnlyList wings, int storey, out HashSet<(int X, int Y)> south, out HashSet<(int X, int Y)> east)
+ {
+ StoreyLayout layout = LayOut(wings, storey);
+ south = layout.South;
+ east = layout.East;
+ }
+
+ ///
+ /// The walls of a storey and what the draft puts in them by itself: the outline of the
+ /// wings, the walls between the rooms of each wing with their doorways (doors, with
+ /// ), the edges added and taken away by hand, the front door and
+ /// the windows along the outer walls.
+ ///
+ public StoreyLayout LayOut(IReadOnlyList wings, int storey)
+ {
+ var layout = new StoreyLayout();
+ HashSet<(int X, int Y)> region = Region(wings, storey);
+ var outerSouth = new HashSet<(int X, int Y)>();
+ var outerEast = new HashSet<(int X, int Y)>();
+ Outline(region, outerSouth, outerEast);
+ layout.South.UnionWith(outerSouth);
+ layout.East.UnionWith(outerEast);
+
+ HashSet<(int X, int Y)> stairs = StairCells(storey);
+ RoomPlan firstPlan = null;
+ for (int index = 0; index < wings.Count; ++index)
+ {
+ RoofWing wing = wings[index];
+ if (wing.Storeys <= storey)
+ {
+ continue;
+ }
+
+ (int rooms, RoomLayout kind) = wing.RoomsOn(storey);
+ RoomPlan plan = RoomPlanner.Plan(wing.X0 + 1, wing.Y0 + 1, wing.X1, wing.Y1, kind, Math.Clamp(rooms, 1, MaxRooms));
+ RoomPlanner.Avoid(plan, stairs);
+ if (index == 0)
+ {
+ firstPlan = plan;
+ }
+
+ Partition(wings, index, storey, plan, stairs, layout);
+ }
+
+ WallOff(wings, storey, region, stairs, layout);
+
+ foreach ((int x, int y) in AddedSouth[storey])
+ {
+ if (region.Contains((x, y)) || region.Contains((x, y + 1)))
+ {
+ layout.South.Add((x, y));
+ }
+ }
+
+ foreach ((int x, int y) in AddedEast[storey])
+ {
+ if (region.Contains((x, y)) || region.Contains((x + 1, y)))
+ {
+ layout.East.Add((x, y));
+ }
+ }
+
+ layout.South.ExceptWith(ErasedSouth[storey]);
+ layout.East.ExceptWith(ErasedEast[storey]);
+
+ if (storey == 0)
+ {
+ AddFrontDoor(wings, firstPlan, outerSouth, outerEast, stairs, layout);
+ }
+
+ if (WindowSpacing > 0)
+ {
+ AddWindows(storey, outerSouth, true, layout);
+ AddWindows(storey, outerEast, false, layout);
+ }
+
+ return layout;
+ }
+
+ /// The cells stairs stand in on a storey: the stairs that start there and the opening of those that arrive.
+ private HashSet<(int X, int Y)> StairCells(int storey)
+ {
+ var cells = new HashSet<(int X, int Y)>();
+ foreach ((int stairStorey, int x, int y, string column, HouseStyle style) in Stairs)
+ {
+ if (stairStorey != storey && stairStorey != storey - 1)
+ {
+ continue;
+ }
+
+ foreach ((ushort _, int tx, int ty, int _) in StairTool.Tiles(style, column, x, y, 0))
+ {
+ cells.Add((tx, ty));
+ }
+ }
+
+ return cells;
+ }
+
+ ///
+ /// The walls between the rooms of a wing. Each pair of rooms the plan joins gets one
+ /// doorway, in the middle of the wall they share, or as near to it as stairs allow. A
+ /// wall is left out where another wing's rooms lie and where it would cut through stairs.
+ ///
+ private void Partition(IReadOnlyList wings, int index, int storey, RoomPlan plan, HashSet<(int X, int Y)> stairs, StoreyLayout layout)
+ {
+ if (plan.Rooms.Count < 2)
+ {
+ return;
+ }
+
+ RoofWing wing = wings[index];
+ int RoomAt(int x, int y)
+ {
+ for (int i = 0; i < plan.Rooms.Count; ++i)
+ {
+ (int x0, int y0, int x1, int y1) = plan.Rooms[i];
+ if (x >= x0 && x <= x1 && y >= y0 && y <= y1)
+ {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+
+ bool Other(int x, int y)
+ {
+ for (int j = 0; j < wings.Count; ++j)
+ {
+ RoofWing other = wings[j];
+ if (j != index && other.Storeys > storey && x > other.X0 && x <= other.X1 && y > other.Y0 && y <= other.Y1)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ var between = new Dictionary<(int A, int B), List<(int X, int Y, bool South)>>();
+ for (int x = wing.X0 + 1; x <= wing.X1; ++x)
+ {
+ for (int y = wing.Y0 + 1; y <= wing.Y1; ++y)
+ {
+ int room = RoomAt(x, y);
+ foreach ((int nx, int ny, bool south) in new[] { (x + 1, y, false), (x, y + 1, true) })
+ {
+ if (nx > wing.X1 || ny > wing.Y1)
+ {
+ continue;
+ }
+
+ int next = RoomAt(nx, ny);
+ if (next == room || Other(x, y) || Other(nx, ny) || (stairs.Contains((x, y)) && stairs.Contains((nx, ny))))
+ {
+ continue;
+ }
+
+ (int, int) key = (Math.Min(room, next), Math.Max(room, next));
+ if (!between.TryGetValue(key, out List<(int X, int Y, bool South)> shared))
+ {
+ between[key] = shared = new List<(int X, int Y, bool South)>();
+ }
+
+ shared.Add((x, y, south));
+ }
+ }
+ }
+
+ var doorways = new HashSet<(int X, int Y, bool South)>();
+ foreach ((int a, int b) in plan.Links)
+ {
+ if (!between.TryGetValue((Math.Min(a, b), Math.Max(a, b)), out List<(int X, int Y, bool South)> shared) || shared.Count == 0)
+ {
+ continue;
+ }
+
+ int middle = (shared.Count - 1) / 2, pick = middle, nearest = int.MaxValue;
+ for (int i = 0; i < shared.Count; ++i)
+ {
+ (int x, int y, bool south) = shared[i];
+ bool free = !stairs.Contains((x, y)) && !stairs.Contains(south ? (x, y + 1) : (x + 1, y));
+ if (free && Math.Abs(i - middle) < nearest)
+ {
+ (pick, nearest) = (i, Math.Abs(i - middle));
+ }
+ }
+
+ doorways.Add(shared[pick]);
+ }
+
+ foreach (List<(int X, int Y, bool South)> shared in between.Values)
+ {
+ foreach ((int x, int y, bool south) in shared)
+ {
+ if (doorways.Contains((x, y, south)))
+ {
+ // A doorway: open, or a door in the wall.
+ if (!AutoDoors || Suppressed.Contains((storey, x, y)))
+ {
+ continue;
+ }
+
+ layout.Doors[(x, y)] = south ? DoorAlongX : DoorAlongY;
+ }
+
+ (south ? layout.South : layout.East).Add((x, y));
+ }
+ }
+ }
+
+ ///
+ /// The walls of the wings that keep them () against the wings
+ /// they meet. Each cell belongs to one wing: a walled one where there is one, else the
+ /// first. A wall stands between cells of different wings when either is walled, and each
+ /// stretch of wall between the same two wings gets one doorway in its middle (a door, with
+ /// ), as near to it as stairs allow.
+ ///
+ private void WallOff(IReadOnlyList wings, int storey, HashSet<(int X, int Y)> region, HashSet<(int X, int Y)> stairs, StoreyLayout layout)
+ {
+ bool any = false;
+ foreach (RoofWing wing in wings)
+ {
+ any |= wing.Walled && wing.Storeys > storey;
+ }
+
+ if (!any)
+ {
+ return;
+ }
+
+ var owners = new Dictionary<(int X, int Y), int>();
+ int Owner((int X, int Y) cell)
+ {
+ if (owners.TryGetValue(cell, out int known))
+ {
+ return known;
+ }
+
+ int first = -1, walled = -1;
+ for (int i = 0; i < wings.Count && walled < 0; ++i)
+ {
+ RoofWing wing = wings[i];
+ if (wing.Storeys > storey && cell.X > wing.X0 && cell.X <= wing.X1 && cell.Y > wing.Y0 && cell.Y <= wing.Y1)
+ {
+ first = first < 0 ? i : first;
+ walled = wing.Walled ? i : walled;
+ }
+ }
+
+ return owners[cell] = walled >= 0 ? walled : first;
+ }
+
+ // Stretches of wall: along one line, between the same two wings, cell after cell.
+ var stretches = new Dictionary<(bool South, int Line, int A, int B), List<(int X, int Y)>>();
+ foreach ((int x, int y) in region)
+ {
+ foreach ((int nx, int ny, bool south) in new[] { (x + 1, y, false), (x, y + 1, true) })
+ {
+ if (!region.Contains((nx, ny)) || (south ? layout.South : layout.East).Contains((x, y)))
+ {
+ continue;
+ }
+
+ int a = Owner((x, y)), b = Owner((nx, ny));
+ if (a == b || a < 0 || b < 0 || !(wings[a].Walled || wings[b].Walled))
+ {
+ continue;
+ }
+
+ var key = (south, south ? y : x, a, b);
+ if (!stretches.TryGetValue(key, out List<(int X, int Y)> cells))
+ {
+ stretches[key] = cells = new List<(int X, int Y)>();
+ }
+
+ cells.Add((x, y));
+ }
+ }
+
+ foreach (KeyValuePair<(bool South, int Line, int A, int B), List<(int X, int Y)>> stretch in stretches)
+ {
+ bool south = stretch.Key.South;
+ List<(int X, int Y)> cells = stretch.Value.OrderBy(c => south ? c.X : c.Y).ToList();
+ for (int start = 0; start < cells.Count;)
+ {
+ int end = start;
+ while (end + 1 < cells.Count && (south ? cells[end + 1].X - cells[end].X : cells[end + 1].Y - cells[end].Y) == 1)
+ {
+ ++end;
+ }
+
+ int middle = (start + end) / 2, pick = middle, nearest = int.MaxValue;
+ for (int i = start; i <= end; ++i)
+ {
+ (int x, int y) = cells[i];
+ bool free = !stairs.Contains((x, y)) && !stairs.Contains(south ? (x, y + 1) : (x + 1, y));
+ if (free && Math.Abs(i - middle) < nearest)
+ {
+ (pick, nearest) = (i, Math.Abs(i - middle));
+ }
+ }
+
+ for (int i = start; i <= end; ++i)
+ {
+ (int x, int y) = cells[i];
+ if (i == pick)
+ {
+ if (!AutoDoors || Suppressed.Contains((storey, x, y)))
+ {
+ continue;
+ }
+
+ layout.Doors[(x, y)] = south ? DoorAlongX : DoorAlongY;
+ }
+
+ (south ? layout.South : layout.East).Add((x, y));
+ }
+
+ start = end + 1;
+ }
+ }
+ }
+
+ ///
+ /// The front door: in the chosen outer wall of the first wing, in the middle of it, or of
+ /// the corridor or hall where that reaches the wall. Corners, wall ends and stairs are passed over.
+ ///
+ private void AddFrontDoor(IReadOnlyList wings, RoomPlan plan, HashSet<(int X, int Y)> outerSouth, HashSet<(int X, int Y)> outerEast,
+ HashSet<(int X, int Y)> stairs, StoreyLayout layout)
+ {
+ if (FrontDoor == FrontDoorSide.None || wings.Count == 0)
+ {
+ return;
+ }
+
+ RoofWing wing = wings[0];
+ bool south = FrontDoor == FrontDoorSide.South;
+ int from = south ? wing.X0 + 1 : wing.Y0 + 1, to = south ? wing.X1 : wing.Y1;
+ double centre = (from + to) / 2.0;
+ if (plan is { Main: >= 0 })
+ {
+ (int x0, int y0, int x1, int y1) = plan.Rooms[plan.Main];
+ if (south ? y1 == wing.Y1 : x1 == wing.X1)
+ {
+ centre = south ? (x0 + x1) / 2.0 : (y0 + y1) / 2.0;
+ }
+ }
+
+ (int X, int Y)? best = null;
+ double nearest = double.MaxValue;
+ for (int i = from; i <= to; ++i)
+ {
+ (int X, int Y) cell = south ? (i, wing.Y1) : (wing.X1, i);
+ bool wall = (south ? outerSouth : outerEast).Contains(cell) && (south ? layout.South : layout.East).Contains(cell);
+ bool straight = wall && !(south ? layout.East : layout.South).Contains(cell);
+ if (straight && !stairs.Contains(cell) && Math.Abs(i - centre) < nearest)
+ {
+ (best, nearest) = (cell, Math.Abs(i - centre));
+ }
+ }
+
+ if (best is { } door && !Suppressed.Contains((0, door.X, door.Y)))
+ {
+ layout.Doors[door] = south ? DoorAlongX : DoorAlongY;
+ layout.FrontDoor = door;
+ }
+ }
+
+ ///
+ /// Windows along the outer walls, cells apart and centred on
+ /// each stretch of wall between corners and the walls that meet it (so on each room).
+ /// A stretch has wall left at both ends; doors and cells set back by hand are passed over.
+ ///
+ private void AddWindows(int storey, HashSet<(int X, int Y)> outer, bool alongX, StoreyLayout layout)
+ {
+ var run = new List<(int X, int Y)>();
+ void Close()
+ {
+ if (run.Count >= 3)
+ {
+ int count = 1 + ((run.Count - 3) / WindowSpacing);
+ int start = (run.Count - 1 - ((count - 1) * WindowSpacing)) / 2;
+ for (int i = 0; i < count; ++i)
+ {
+ (int X, int Y) cell = run[start + (i * WindowSpacing)];
+ if (!Doors.ContainsKey((storey, cell.X, cell.Y)) && !layout.Doors.ContainsKey(cell) && !Suppressed.Contains((storey, cell.X, cell.Y)))
+ {
+ layout.Windows.Add(cell);
+ }
+ }
+ }
+
+ run.Clear();
+ }
+
+ foreach (IGrouping line in outer.GroupBy(c => alongX ? c.Y : c.X))
+ {
+ int last = int.MinValue;
+ foreach ((int X, int Y) cell in line.OrderBy(c => alongX ? c.X : c.Y))
+ {
+ int at = alongX ? cell.X : cell.Y;
+ if (at != last + 1)
+ {
+ Close();
+ }
+
+ last = at;
+ bool straight = (alongX ? layout.South : layout.East).Contains(cell) && !(alongX ? layout.East : layout.South).Contains(cell);
+
+ // A wall that meets this one from the far side ends the stretch as a corner does.
+ bool joined = alongX ? layout.East.Contains((cell.X, cell.Y + 1)) : layout.South.Contains((cell.X + 1, cell.Y));
+ if (!straight || joined)
+ {
+ Close();
+ continue;
+ }
+
+ run.Add(cell);
+ }
+
+ Close();
+ }
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/HouseDraft.cs b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.cs
new file mode 100644
index 00000000..fc4d85a4
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/HouseDraft.cs
@@ -0,0 +1,180 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using UoFiddler.Plugin.MultiEditor.Styles;
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ internal sealed partial class HouseDraft
+ {
+ /// The door pieces the draft hangs by itself in a wall along X and in one along Y.
+ public const string DoorAlongX = "Piece3";
+ public const string DoorAlongY = "Piece5";
+
+ public const int StoreyHeight = 20;
+ public const int MaxStoreys = 4;
+ public const string WallsLayer = "Walls";
+ public const string FloorsLayer = "Floors";
+ public const string StairsLayer = "Stairs";
+ public const string FoundationLayer = "Foundation";
+
+ /// How far below the ground floor the foundation of most client houses starts.
+ public const int UsualFoundationHeight = 7;
+
+ /// Z of the ground floor.
+ public int BaseZ { get; set; }
+
+ public HouseStyle[] WallStyles { get; } = new HouseStyle[MaxStoreys];
+
+ public HouseStyle[] FloorStyles { get; } = new HouseStyle[MaxStoreys];
+
+ public HouseStyle RoofStyle { get; set; }
+
+ /// The floor style a flat roof is laid in; without one, the floor style of the wing's top storey.
+ public HouseStyle FlatRoofStyle { get; set; }
+
+ public bool Foundation { get; set; }
+
+ /// The wall style the foundation ring is built in; without one, the client houses' own (light brick).
+ public HouseStyle FoundationStyle { get; set; }
+
+ /// Rows of foundation pieces, one on the other: the stone tower, keep and castle have two.
+ public int FoundationTiers { get; set; } = 1;
+
+ /// How far below the ground floor the foundation starts.
+ public int FoundationHeight { get; set; } = UsualFoundationHeight;
+
+ /// The door style of the house: what a theme sets, and what doors made for the rooms are.
+ public HouseStyle DoorStyle { get; set; }
+
+ /// The stair style of the house.
+ public HouseStyle StairStyle { get; set; }
+
+ /// Which gable ends of the house's roofs are closed, and with what.
+ public RoofGables Gables { get; set; } = RoofGables.Front;
+
+ public RoofGableFill GableFill { get; set; } = RoofGableFill.Caps;
+
+ ///
+ /// True when flat roofs get battlements, as the client's tower, keep and castle have them:
+ /// two rows of the walls' roof edging around the roof and a third of every second piece.
+ ///
+ public bool Parapet { get; set; }
+
+ /// True when the doorways between rooms get a door of .
+ public bool AutoDoors { get; set; }
+
+ public FrontDoorSide FrontDoor { get; set; }
+
+ /// Cells between the windows the draft puts along the outer walls; 0 for none.
+ public int WindowSpacing { get; set; }
+
+ /// Wall cells where a door or window the draft made by itself was taken out by hand.
+ public HashSet<(int Storey, int X, int Y)> Suppressed { get; } = new HashSet<(int, int, int)>();
+
+ /// Most rooms a wing can be divided into.
+ public const int MaxRooms = 6;
+
+ // Wall edges added and taken away by hand, per storey: cells with a wall on their +Y edge
+ // (south) and on their +X edge (east).
+ public HashSet<(int X, int Y)>[] AddedSouth { get; } = Sets();
+
+ public HashSet<(int X, int Y)>[] AddedEast { get; } = Sets();
+
+ public HashSet<(int X, int Y)>[] ErasedSouth { get; } = Sets();
+
+ public HashSet<(int X, int Y)>[] ErasedEast { get; } = Sets();
+
+ /// Doors by storey and wall cell: the door style and its piece (hinge variant).
+ public Dictionary<(int Storey, int X, int Y), (HouseStyle Style, string Piece)> Doors { get; } = new Dictionary<(int, int, int), (HouseStyle, string)>();
+
+ /// Wall cells whose piece is the style's window.
+ public HashSet<(int Storey, int X, int Y)> Windows { get; } = new HashSet<(int, int, int)>();
+
+ /// Floor areas laid in another style than the storey's; later ones lie on top.
+ public List<(int Storey, int X0, int Y0, int X1, int Y1, HouseStyle Style)> FloorAreas { get; } = new List<(int, int, int, int, int, HouseStyle)>();
+
+ /// Stairs by storey: the cell of the bottom step, the stair column (MultiNorth ...) and the style.
+ public List<(int Storey, int X, int Y, string Column, HouseStyle Style)> Stairs { get; } = new List<(int, int, int, string, HouseStyle)>();
+
+ private static HashSet<(int X, int Y)>[] Sets()
+ {
+ var sets = new HashSet<(int X, int Y)>[MaxStoreys];
+ for (int i = 0; i < MaxStoreys; ++i)
+ {
+ sets[i] = new HashSet<(int X, int Y)>();
+ }
+
+ return sets;
+ }
+
+ /// A copy that shares nothing but the styles.
+ public HouseDraft Clone()
+ {
+ HouseDraft copy = Fresh();
+ copy.BaseZ = BaseZ;
+ CopyHandEditsInto(copy, _everywhere);
+ return copy;
+ }
+
+ /// Puts another style in the place of every style the draft holds: after the styles were read again.
+ public void Remap(Func successor)
+ {
+ for (int k = 0; k < MaxStoreys; ++k)
+ {
+ WallStyles[k] = successor(WallStyles[k]);
+ FloorStyles[k] = successor(FloorStyles[k]);
+ }
+
+ RoofStyle = successor(RoofStyle);
+ FlatRoofStyle = successor(FlatRoofStyle);
+ FoundationStyle = successor(FoundationStyle);
+ DoorStyle = successor(DoorStyle);
+ StairStyle = successor(StairStyle);
+ foreach (var key in new List<(int Storey, int X, int Y)>(Doors.Keys))
+ {
+ Doors[key] = (successor(Doors[key].Style), Doors[key].Piece);
+ }
+
+ for (int i = 0; i < FloorAreas.Count; ++i)
+ {
+ var a = FloorAreas[i];
+ FloorAreas[i] = (a.Storey, a.X0, a.Y0, a.X1, a.Y1, successor(a.Style));
+ }
+
+ for (int i = 0; i < Stairs.Count; ++i)
+ {
+ var s = Stairs[i];
+ Stairs[i] = (s.Storey, s.X, s.Y, s.Column, successor(s.Style));
+ }
+
+ _pieces.Clear();
+ }
+
+ /// A draft with the same materials and nothing changed by hand: the next house.
+ public HouseDraft Fresh()
+ {
+ var copy = new HouseDraft
+ {
+ RoofStyle = RoofStyle, FlatRoofStyle = FlatRoofStyle, Foundation = Foundation,
+ FoundationStyle = FoundationStyle, FoundationTiers = FoundationTiers, FoundationHeight = FoundationHeight,
+ DoorStyle = DoorStyle, StairStyle = StairStyle,
+ AutoDoors = AutoDoors, FrontDoor = FrontDoor, WindowSpacing = WindowSpacing,
+ Gables = Gables, GableFill = GableFill, Parapet = Parapet
+ };
+ Array.Copy(WallStyles, copy.WallStyles, MaxStoreys);
+ Array.Copy(FloorStyles, copy.FloorStyles, MaxStoreys);
+ return copy;
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/HouseFoundation.cs b/UoFiddler.Plugin.MultiEditor/House/HouseFoundation.cs
new file mode 100644
index 00000000..9ec22b5a
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/HouseFoundation.cs
@@ -0,0 +1,32 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ ///
+ /// A foundation as the client's houses have them: a low wall style around the house, in one
+ /// or two rows, with the ground floor a given height above where it starts. From the style
+ /// file; offered when the client has the wall style.
+ ///
+ internal sealed class HouseFoundation
+ {
+ public string Name { get; set; }
+
+ /// Anchor piece of the wall style; 0 for the usual one (light brick quarter walls).
+ public ushort Style { get; set; }
+
+ public int Tiers { get; set; } = 1;
+
+ public int Height { get; set; } = HouseDraft.UsualFoundationHeight;
+
+ public override string ToString() => Name;
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/HouseTheme.cs b/UoFiddler.Plugin.MultiEditor/House/HouseTheme.cs
new file mode 100644
index 00000000..4858e232
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/HouseTheme.cs
@@ -0,0 +1,50 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using UoFiddler.Plugin.MultiEditor.Styles;
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ ///
+ /// A house theme: the styles of every part of a house, picked together. Each style is named
+ /// by its anchor piece (); 0 leaves that part as it is, except
+ /// for the foundation (0 is the usual one, light brick).
+ /// Themes come from the style file; the ones the user saved are in the user's copy of it.
+ ///
+ internal sealed class HouseTheme
+ {
+ public string Name { get; set; }
+
+ public ushort Walls { get; set; }
+
+ public ushort Floor { get; set; }
+
+ public ushort Roof { get; set; }
+
+ public ushort FlatRoof { get; set; }
+
+ public ushort Door { get; set; }
+
+ public ushort Stairs { get; set; }
+
+ public ushort Foundation { get; set; }
+
+ /// Rows of the foundation's pieces, one on the other, and how far below the ground floor the foundation starts.
+ public int FoundationTiers { get; set; } = 1;
+
+ public int FoundationHeight { get; set; } = HouseDraft.UsualFoundationHeight;
+
+ /// True for a theme from the user's copy of the style file.
+ public bool IsUser { get; set; }
+
+ public override string ToString() => Name;
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/RoofGableFill.cs b/UoFiddler.Plugin.MultiEditor/House/RoofGableFill.cs
new file mode 100644
index 00000000..c0f324ac
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/RoofGableFill.cs
@@ -0,0 +1,23 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ /// What closes a gable.
+ internal enum RoofGableFill
+ {
+ /// 3 high cap pieces matching the walls.
+ Caps,
+
+ /// Whole wall pieces as far as they fit under the slope, caps for the rest: for big, high roofs.
+ Walls
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/RoofGables.cs b/UoFiddler.Plugin.MultiEditor/House/RoofGables.cs
new file mode 100644
index 00000000..7c569721
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/RoofGables.cs
@@ -0,0 +1,22 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ /// Which gable ends of a roof are closed.
+ internal enum RoofGables
+ {
+ /// The south or east end, as the official houses do.
+ Front,
+ Both,
+ None
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/RoofPlanner.cs b/UoFiddler.Plugin.MultiEditor/House/RoofPlanner.cs
new file mode 100644
index 00000000..0f74d446
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/RoofPlanner.cs
@@ -0,0 +1,383 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ ///
+ /// Roofs as a height per cell. A wing (a rectangle with a ridge direction) gives each of its
+ /// cells a height, wings are joined by taking the higher one, and the roof.txt piece of a cell
+ /// follows from how its neighbours' heights compare with its own. The rules were measured on
+ /// the official multis and the UO Architect designs (109,000 roof cells):
+ ///
+ /// - a slope is named for the side it comes down to: lower to the west is a West piece;
+ /// - a ridge cell (lower on both sides) is the crosspiece running the other way;
+ /// - a valley cell, level with two neighbours and below the other two, is a Dent piece:
+ /// higher to the west and south EDent, west and north SDent, east and north WDent, east and
+ /// south NDent;
+ /// - where a wing's ridge runs into another ridge of the same height the cell is the T
+ /// piece named for the side the wing comes from, and the X piece where two ridges cross.
+ /// - roof.txt has no pieces made for hips. The Dent pieces serve: each is a tile of two
+ /// faces, and on a hip line the one with the same two faces closes the corner when it sits 3
+ /// lower than the slopes beside it (the south-east one at their height). Found by drawing
+ /// every piece at every corner; it closes cleanly in thatch, stone, slate and shingles and
+ /// leaves small seams in Tile Roof.
+ ///
+ ///
+ internal static class RoofPlanner
+ {
+ /// Z a slope gains per cell: the roof pieces are 3 high.
+ public const int Rise = 3;
+
+ /// Marks a fixed piece that sits lower than its cell's height: "EDent@-3".
+ public const char LiftMark = '@';
+
+ // The corner pieces of a hip, by the corner of the wing they lie towards.
+ private const string _hipNorthWest = "NDent@-3";
+ private const string _hipNorthEast = "EDent@-3";
+ private const string _hipSouthEast = "SDent";
+ private const string _hipSouthWest = "WDent@-3";
+
+ /// Narrowest part of a house that gets a wing of its own.
+ private const int _minWing = 3;
+
+ ///
+ /// The ridge direction the official houses would give a box: across the odd side, so the
+ /// ridge gets its crosspiece; otherwise along the longer side, along Y when square.
+ ///
+ public static bool RidgeAlongY((int X0, int Y0, int X1, int Y1) box)
+ {
+ int spanX = box.X1 - box.X0 + 1, spanY = box.Y1 - box.Y0 + 1;
+ return spanX % 2 != spanY % 2 ? spanX % 2 == 1 : spanY >= spanX;
+ }
+
+ ///
+ /// Adds a wing to a roof: every cell of the box gets the wing's height there unless the
+ /// roof is already higher. A gable climbs from its two long sides to the ridge. A hip
+ /// climbs from all four sides; the cells on its hip lines get their corner piece in
+ /// . Cells with a negative coordinate are left out.
+ ///
+ public static void AddWing(Dictionary<(int X, int Y), int> heights, Dictionary<(int X, int Y), string> fixedPieces,
+ (int X0, int Y0, int X1, int Y1) box, bool ridgeAlongY, RoofShape shape, int eaveZ)
+ {
+ int across0 = ridgeAlongY ? box.X0 : box.Y0;
+ int across1 = ridgeAlongY ? box.X1 : box.Y1;
+ for (int x = Math.Max(0, box.X0); x <= box.X1; ++x)
+ {
+ for (int y = Math.Max(0, box.Y0); y <= box.Y1; ++y)
+ {
+ int a = ridgeAlongY ? x : y;
+ int steps = Math.Min(a - across0, across1 - a);
+ string corner = null;
+ if (shape == RoofShape.Hip)
+ {
+ int west = x - box.X0, east = box.X1 - x, north = y - box.Y0, south = box.Y1 - y;
+ steps = Math.Min(Math.Min(west, east), Math.Min(north, south));
+
+ // On a hip line two sides are equally near; on the ridge the opposite ones are.
+ if (west != east && north != south)
+ {
+ corner = west == steps && north == steps ? _hipNorthWest
+ : east == steps && north == steps ? _hipNorthEast
+ : east == steps && south == steps ? _hipSouthEast
+ : west == steps && south == steps ? _hipSouthWest
+ : null;
+ }
+ }
+
+ int z = eaveZ + (Rise * steps);
+ if (heights.TryGetValue((x, y), out int known) && known >= z)
+ {
+ continue;
+ }
+
+ heights[(x, y)] = z;
+ if (corner != null)
+ {
+ fixedPieces[(x, y)] = corner;
+ }
+ else
+ {
+ fixedPieces.Remove((x, y));
+ }
+ }
+ }
+ }
+
+ // -1 lower (or no roof there), 0 level, 1 higher: a neighbour's height against a cell's.
+ private static int Side(IReadOnlyDictionary<(int X, int Y), int> heights, int x, int y, int height)
+ {
+ return heights.TryGetValue((x, y), out int n) ? Math.Sign(n - height) : -1;
+ }
+
+ ///
+ /// The roof.txt column of the piece for a cell, from the heights around it; null for a
+ /// cell level with all its neighbours, which no piece fits. A style without the piece
+ /// named leaves the cell open: no other piece is put there in its place.
+ ///
+ public static string Piece(IReadOnlyDictionary<(int X, int Y), int> heights, int x, int y)
+ {
+ if (!heights.TryGetValue((x, y), out int h))
+ {
+ return null;
+ }
+
+ int Side(int cx, int cy, int ch) => RoofPlanner.Side(heights, cx, cy, ch);
+ bool RidgeAlongYAt(int cx, int cy) => heights.TryGetValue((cx, cy), out int ch) && Side(cx - 1, cy, ch) < 0 && Side(cx + 1, cy, ch) < 0;
+ bool RidgeAlongXAt(int cx, int cy) => heights.TryGetValue((cx, cy), out int ch) && Side(cx, cy - 1, ch) < 0 && Side(cx, cy + 1, ch) < 0;
+
+ int w = Side(x - 1, y, h), e = Side(x + 1, y, h), n = Side(x, y - 1, h), s = Side(x, y + 1, h);
+
+ // Valley: level with one neighbour and below the other on both axes.
+ if (w + e == 1 && w * e == 0 && n + s == 1 && n * s == 0)
+ {
+ if (w > 0)
+ {
+ return s > 0 ? "EDent" : "SDent";
+ }
+
+ return n > 0 ? "WDent" : "NDent";
+ }
+
+ // Ridges of this height leaving the cell.
+ bool armW = w == 0 && RidgeAlongXAt(x - 1, y), armE = e == 0 && RidgeAlongXAt(x + 1, y);
+ bool armN = n == 0 && RidgeAlongYAt(x, y - 1), armS = s == 0 && RidgeAlongYAt(x, y + 1);
+ int arms = (armW ? 1 : 0) + (armE ? 1 : 0) + (armN ? 1 : 0) + (armS ? 1 : 0);
+ if (arms == 4)
+ {
+ return "XPiece";
+ }
+
+ if (arms == 3)
+ {
+ return !armW ? "ETPiece" : !armE ? "WTPiece" : !armN ? "STPiece" : "NTPiece";
+ }
+
+ bool ridgeY = w < 0 && e < 0, ridgeX = n < 0 && s < 0;
+ if (ridgeY && ridgeX)
+ {
+ return armE || armW ? "EWCrosspiece" : "NSCrosspiece";
+ }
+
+ if (ridgeY)
+ {
+ return "NSCrosspiece";
+ }
+
+ if (ridgeX)
+ {
+ return "EWCrosspiece";
+ }
+
+ int climbX = e - w, climbY = s - n;
+ if (climbX == 0 && climbY == 0)
+ {
+ return null;
+ }
+
+ // The roof's edge counts as lower, so at a gable end a cell of the top rows of an even
+ // span drops as much to the edge as down its slope. The slope is the side where roof
+ // lies lower, not the edge.
+ if (Math.Abs(climbX) == Math.Abs(climbY))
+ {
+ bool roofLowerX = heights.ContainsKey((climbX > 0 ? x - 1 : x + 1, y));
+ bool roofLowerY = heights.ContainsKey((x, climbY > 0 ? y - 1 : y + 1));
+ if (roofLowerY && !roofLowerX)
+ {
+ return climbY > 0 ? "North" : "South";
+ }
+ }
+
+ return Math.Abs(climbX) >= Math.Abs(climbY) ? (climbX > 0 ? "West" : "East") : (climbY > 0 ? "North" : "South");
+ }
+
+ ///
+ /// The end piece of a ridge, for the sets that have them (the ceramic tiles): a ridge cell
+ /// lower on three sides and level on the fourth. North end MoreNS, south end NSEnd, west
+ /// end MoreEW, east end EWEnd, as the UO Architect ceramic roofs place them. Null for any
+ /// other cell; a set without end pieces ends its ridge with the crosspiece.
+ ///
+ public static string RidgeEnd(IReadOnlyDictionary<(int X, int Y), int> heights, int x, int y)
+ {
+ if (!heights.TryGetValue((x, y), out int h))
+ {
+ return null;
+ }
+
+ int w = Side(heights, x - 1, y, h), e = Side(heights, x + 1, y, h), n = Side(heights, x, y - 1, h), s = Side(heights, x, y + 1, h);
+ if (w < 0 && e < 0 && n + s == -1 && n * s == 0)
+ {
+ return n < 0 ? "MoreNS" : "NSEnd";
+ }
+
+ if (n < 0 && s < 0 && w + e == -1 && w * e == 0)
+ {
+ return w < 0 ? "MoreEW" : "EWEnd";
+ }
+
+ return null;
+ }
+
+ ///
+ /// Drops the hip corners that joined wings have covered. A corner stays only where the
+ /// roof still turns there: lower (or no roof) on its two outer sides, level on the two
+ /// inner ones. Any other cell is a joint, whose piece follows from the heights.
+ ///
+ public static void SettleCorners(IReadOnlyDictionary<(int X, int Y), int> heights, Dictionary<(int X, int Y), string> fixedPieces)
+ {
+ foreach (((int x, int y), string piece) in new List>(fixedPieces))
+ {
+ (int outerX, int outerY) = piece switch
+ {
+ _hipNorthWest => (-1, -1),
+ _hipNorthEast => (1, -1),
+ _hipSouthEast => (1, 1),
+ _hipSouthWest => (-1, 1),
+ _ => (0, 0)
+ };
+ if (outerX == 0 || !heights.TryGetValue((x, y), out int h))
+ {
+ continue;
+ }
+
+ bool corner = Side(heights, x + outerX, y, h) < 0 && Side(heights, x, y + outerY, h) < 0 &&
+ Side(heights, x - outerX, y, h) == 0 && Side(heights, x, y - outerY, h) == 0;
+ if (!corner)
+ {
+ fixedPieces.Remove((x, y));
+ }
+ }
+ }
+
+ ///
+ /// The wings that roof a house whose cells are : its largest
+ /// rectangles, biggest first, each with its ridge along its longer side. A wing that runs
+ /// through an earlier one across its ridge stops at that ridge, so the two meet in a T
+ /// instead of the wing showing a gable on the far side. Parts narrower than three cells
+ /// get no wing. A plain rectangle, or a shape too ragged to split, is one wing: the
+ /// region's box.
+ ///
+ public static List<((int X0, int Y0, int X1, int Y1) Box, bool RidgeAlongY)> Wings(ICollection<(int X, int Y)> region)
+ {
+ var wings = new List<((int X0, int Y0, int X1, int Y1) Box, bool RidgeAlongY)>();
+ if (region.Count == 0)
+ {
+ return wings;
+ }
+
+ int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue;
+ foreach ((int x, int y) in region)
+ {
+ minX = Math.Min(minX, x);
+ minY = Math.Min(minY, y);
+ maxX = Math.Max(maxX, x);
+ maxY = Math.Max(maxY, y);
+ }
+
+ var whole = (minX, minY, maxX, maxY);
+ int width = maxX - minX + 1, height = maxY - minY + 1;
+ if (region.Count == width * height)
+ {
+ wings.Add((whole, RidgeAlongY(whole)));
+ return wings;
+ }
+
+ // Filled cells before (x, y), so a rectangle is checked in one step.
+ var sum = new int[width + 1, height + 1];
+ var set = region as ISet<(int X, int Y)> ?? new HashSet<(int X, int Y)>(region);
+ for (int x = 0; x < width; ++x)
+ {
+ for (int y = 0; y < height; ++y)
+ {
+ sum[x + 1, y + 1] = sum[x, y + 1] + sum[x + 1, y] - sum[x, y] + (set.Contains((minX + x, minY + y)) ? 1 : 0);
+ }
+ }
+
+ bool Full(int x0, int y0, int x1, int y1)
+ {
+ return x0 >= 0 && y0 >= 0 && x1 < width && y1 < height &&
+ sum[x1 + 1, y1 + 1] - sum[x0, y1 + 1] - sum[x1 + 1, y0] + sum[x0, y0] == (x1 - x0 + 1) * (y1 - y0 + 1);
+ }
+
+ var found = new List<(int X0, int Y0, int X1, int Y1)>();
+ for (int x0 = 0; x0 < width; ++x0)
+ {
+ for (int y0 = 0; y0 < height; ++y0)
+ {
+ for (int x1 = x0 + _minWing - 1; x1 < width && Full(x0, y0, x1, y0); ++x1)
+ {
+ for (int y1 = y0 + _minWing - 1; y1 < height && Full(x0, y0, x1, y1); ++y1)
+ {
+ if (!Full(x0 - 1, y0, x0 - 1, y1) && !Full(x1 + 1, y0, x1 + 1, y1) &&
+ !Full(x0, y0 - 1, x1, y0 - 1) && !Full(x0, y1 + 1, x1, y1 + 1))
+ {
+ found.Add((minX + x0, minY + y0, minX + x1, minY + y1));
+ }
+ }
+ }
+ }
+ }
+
+ found.Sort((a, b) => ((b.X1 - b.X0 + 1) * (b.Y1 - b.Y0 + 1)).CompareTo((a.X1 - a.X0 + 1) * (a.Y1 - a.Y0 + 1)));
+ if (found.Count == 0 || found.Count > 6)
+ {
+ wings.Add((whole, RidgeAlongY(whole)));
+ return wings;
+ }
+
+ foreach ((int X0, int Y0, int X1, int Y1) rect in found)
+ {
+ var box = rect;
+ bool alongY = box.Y1 - box.Y0 != box.X1 - box.X0 ? box.Y1 - box.Y0 > box.X1 - box.X0 : RidgeAlongY(box);
+ foreach (((int X0, int Y0, int X1, int Y1) other, bool otherAlongY) in wings)
+ {
+ bool overlap = box.X0 <= other.X1 && box.X1 >= other.X0 && box.Y0 <= other.Y1 && box.Y1 >= other.Y0;
+ if (!overlap || otherAlongY == alongY)
+ {
+ continue;
+ }
+
+ if (alongY)
+ {
+ // The other ridge runs along X: stop at its row when sticking out one way only.
+ bool south = box.Y1 > other.Y1, north = box.Y0 < other.Y0;
+ if (south && !north)
+ {
+ box.Y0 = Math.Max(box.Y0, (other.Y0 + other.Y1 + 1) / 2);
+ }
+ else if (north && !south)
+ {
+ box.Y1 = Math.Min(box.Y1, (other.Y0 + other.Y1) / 2);
+ }
+ }
+ else
+ {
+ bool east = box.X1 > other.X1, west = box.X0 < other.X0;
+ if (east && !west)
+ {
+ box.X0 = Math.Max(box.X0, (other.X0 + other.X1 + 1) / 2);
+ }
+ else if (west && !east)
+ {
+ box.X1 = Math.Min(box.X1, (other.X0 + other.X1) / 2);
+ }
+ }
+ }
+
+ wings.Add((box, alongY));
+ }
+
+ return wings;
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/RoofRidge.cs b/UoFiddler.Plugin.MultiEditor/House/RoofRidge.cs
new file mode 100644
index 00000000..5c8217f0
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/RoofRidge.cs
@@ -0,0 +1,22 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ /// Which way a gable roof's ridge runs.
+ internal enum RoofRidge
+ {
+ /// As the official houses: along the longer side, or so the ridge gets its crosspiece.
+ Auto,
+ AlongX,
+ AlongY
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/RoofShape.cs b/UoFiddler.Plugin.MultiEditor/House/RoofShape.cs
new file mode 100644
index 00000000..6d63ff2e
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/RoofShape.cs
@@ -0,0 +1,29 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ /// The shape of one roof wing.
+ internal enum RoofShape
+ {
+ /// Two slopes meeting in a ridge.
+ Gable,
+
+ /// Four slopes: the ends slope too, instead of standing as gables.
+ Hip,
+
+ ///
+ /// No slopes: a floor on top of the walls, as the towers have. Only a house wing can have
+ /// it; the house draft lays it, not this planner.
+ ///
+ Flat
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/RoofWing.cs b/UoFiddler.Plugin.MultiEditor/House/RoofWing.cs
new file mode 100644
index 00000000..583ecd99
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/RoofWing.cs
@@ -0,0 +1,101 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ ///
+ /// One rectangle of a roof or a house being shaped. For a roof the box is the cells the roof
+ /// covers and the height of its eaves; for a house the box is the wall
+ /// cells and the Z its ground floor stands on.
+ ///
+ internal sealed class RoofWing
+ {
+ public int X0 { get; set; }
+
+ public int Y0 { get; set; }
+
+ public int X1 { get; set; }
+
+ public int Y1 { get; set; }
+
+ public int EaveZ { get; set; }
+
+ /// Storeys of a house wing.
+ public int Storeys { get; set; } = 1;
+
+ /// A house wing left without a roof.
+ public bool NoRoof { get; set; }
+
+ ///
+ /// Rooms a house wing is divided into on each of its storeys: partitions across its longer
+ /// side, each with a doorway left in the middle. 1 leaves the wing undivided.
+ ///
+ public int Rooms { get; set; } = 1;
+
+ /// How the rooms of a house wing are laid out.
+ public RoomLayout Layout { get; set; }
+
+ ///
+ /// True for a house wing that keeps its walls where it meets other wings, with a doorway
+ /// in each stretch of wall they share: a tower at a keep's corner, a hall in a castle's
+ /// yard. Wings without it run into each other as one open space.
+ ///
+ public bool Walled { get; set; }
+
+ ///
+ /// Rooms and layout of the storeys above the ground floor that have their own; a storey
+ /// without takes those of the storey below it. Index 0 is not used.
+ ///
+ public (int Rooms, RoomLayout Layout)?[] RoomsAbove { get; private set; } = new (int, RoomLayout)?[HouseDraft.MaxStoreys];
+
+ /// Rooms and layout of a storey.
+ public (int Rooms, RoomLayout Layout) RoomsOn(int storey)
+ {
+ for (int k = Math.Min(storey, HouseDraft.MaxStoreys - 1); k >= 1; --k)
+ {
+ if (RoomsAbove[k] is { } own)
+ {
+ return own;
+ }
+ }
+
+ return (Rooms, Layout);
+ }
+
+ public RoofShape Shape { get; set; }
+
+ public bool RidgeAlongY { get; set; }
+
+ /// True while the ridge follows the box's proportions as it is resized.
+ public bool RidgeAuto { get; set; }
+
+ public (int X0, int Y0, int X1, int Y1) Box => (X0, Y0, X1, Y1);
+
+ public RoofWing Clone()
+ {
+ var copy = (RoofWing)MemberwiseClone();
+ copy.RoomsAbove = ((int, RoomLayout)?[])RoomsAbove.Clone();
+ return copy;
+ }
+
+ public void CopyFrom(RoofWing other)
+ {
+ (X0, Y0, X1, Y1, EaveZ) = (other.X0, other.Y0, other.X1, other.Y1, other.EaveZ);
+ (Shape, RidgeAlongY, RidgeAuto, Storeys, NoRoof) = (other.Shape, other.RidgeAlongY, other.RidgeAuto, other.Storeys, other.NoRoof);
+ Rooms = other.Rooms;
+ Layout = other.Layout;
+ Walled = other.Walled;
+ RoomsAbove = ((int, RoomLayout)?[])other.RoomsAbove.Clone();
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/RoomLayout.cs b/UoFiddler.Plugin.MultiEditor/House/RoomLayout.cs
new file mode 100644
index 00000000..72220479
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/RoomLayout.cs
@@ -0,0 +1,29 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ /// How the rooms of a house wing are laid out.
+ internal enum RoomLayout
+ {
+ /// Side by side along the wing's longer side.
+ Row,
+
+ /// Two rows of rooms.
+ Grid,
+
+ /// A corridor along the wing's longer side with rooms on both sides of it.
+ Corridor,
+
+ /// One large room, and the others in a row across the wing's end.
+ Hall
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/RoomPlan.cs b/UoFiddler.Plugin.MultiEditor/House/RoomPlan.cs
new file mode 100644
index 00000000..87d69fb0
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/RoomPlan.cs
@@ -0,0 +1,28 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System.Collections.Generic;
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ /// The rooms of a wing on one storey: their cells, and which of them a doorway joins.
+ internal sealed class RoomPlan
+ {
+ /// The rooms as cell rectangles, both ends included.
+ public List<(int X0, int Y0, int X1, int Y1)> Rooms { get; } = new List<(int, int, int, int)>();
+
+ /// Pairs of rooms with a doorway between them. Every room is reached through them.
+ public List<(int A, int B)> Links { get; } = new List<(int, int)>();
+
+ /// The room the others open to (the corridor, the hall), or -1 when there is none.
+ public int Main { get; set; } = -1;
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/House/RoomPlanner.cs b/UoFiddler.Plugin.MultiEditor/House/RoomPlanner.cs
new file mode 100644
index 00000000..d87e14ed
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/House/RoomPlanner.cs
@@ -0,0 +1,239 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace UoFiddler.Plugin.MultiEditor.House
+{
+ ///
+ /// Divides the inside of a house wing into rooms. It only says where the rooms are and which
+ /// are joined: the draft makes the walls, doorways, doors and windows from that.
+ ///
+ internal static class RoomPlanner
+ {
+ /// Narrowest a room may be, in cells.
+ public const int MinRoom = 2;
+
+ ///
+ /// The rooms of the cells .. by
+ /// ... A layout the wing is too small for falls
+ /// back to a row of rooms, and that to fewer rooms, down to the wing undivided.
+ ///
+ public static RoomPlan Plan(int x0, int y0, int x1, int y1, RoomLayout layout, int rooms)
+ {
+ int width = x1 - x0 + 1, depth = y1 - y0 + 1;
+ bool alongX = width >= depth;
+ int length = alongX ? width : depth, cross = alongX ? depth : width;
+ rooms = Math.Max(1, rooms);
+
+ // A rectangle given along the wing's longer side (a) and across it (b), as cells.
+ (int, int, int, int) Rect((int From, int To) a, (int From, int To) b) => alongX
+ ? (x0 + a.From, y0 + b.From, x0 + a.To, y0 + b.To)
+ : (x0 + b.From, y0 + a.From, x0 + b.To, y0 + a.To);
+
+ var plan = new RoomPlan();
+ switch (layout)
+ {
+ case RoomLayout.Grid when rooms >= 3 && cross >= 2 * MinRoom:
+ {
+ List<(int From, int To)> halves = Split(0, cross, 2);
+ List<(int From, int To)> first = Split(0, length, (rooms + 1) / 2), second = Split(0, length, rooms / 2);
+ foreach ((int From, int To) part in first)
+ {
+ plan.Rooms.Add(Rect(part, halves[0]));
+ }
+
+ foreach ((int From, int To) part in second)
+ {
+ plan.Rooms.Add(Rect(part, halves[1]));
+ }
+
+ for (int i = 1; i < first.Count; ++i)
+ {
+ plan.Links.Add((i - 1, i));
+ }
+
+ // Each room of the second row opens to the room of the first it shares most wall with.
+ for (int j = 0; j < second.Count; ++j)
+ {
+ int best = 0, most = -1;
+ for (int i = 0; i < first.Count; ++i)
+ {
+ int shared = Math.Min(first[i].To, second[j].To) - Math.Max(first[i].From, second[j].From) + 1;
+ if (shared > most)
+ {
+ (best, most) = (i, shared);
+ }
+ }
+
+ plan.Links.Add((best, first.Count + j));
+ }
+
+ return plan;
+ }
+
+ case RoomLayout.Corridor when rooms >= 2 && cross >= (2 * MinRoom) + 1:
+ {
+ int corridor = cross >= 8 ? 2 : 1;
+ int side = (cross - corridor) / 2;
+ plan.Main = 0;
+ plan.Rooms.Add(Rect((0, length - 1), (side, side + corridor - 1)));
+ foreach ((int From, int To) part in Split(0, length, (rooms + 1) / 2))
+ {
+ plan.Links.Add((0, plan.Rooms.Count));
+ plan.Rooms.Add(Rect(part, (0, side - 1)));
+ }
+
+ foreach ((int From, int To) part in Split(0, length, rooms / 2))
+ {
+ plan.Links.Add((0, plan.Rooms.Count));
+ plan.Rooms.Add(Rect(part, (side + corridor, cross - 1)));
+ }
+
+ return plan;
+ }
+
+ case RoomLayout.Hall when rooms >= 2 && length >= 3 + MinRoom:
+ {
+ int hall = Math.Clamp((int)Math.Round(length * 0.6), 3, length - MinRoom);
+ plan.Main = 0;
+ plan.Rooms.Add(Rect((0, hall - 1), (0, cross - 1)));
+ foreach ((int From, int To) part in Split(0, cross, rooms - 1))
+ {
+ plan.Links.Add((0, plan.Rooms.Count));
+ plan.Rooms.Add(Rect((hall, length - 1), part));
+ }
+
+ return plan;
+ }
+ }
+
+ foreach ((int From, int To) part in Split(0, length, Math.Min(rooms, HouseDraft.MaxRooms)))
+ {
+ if (plan.Rooms.Count > 0)
+ {
+ plan.Links.Add((plan.Rooms.Count - 1, plan.Rooms.Count));
+ }
+
+ plan.Rooms.Add(Rect(part, (0, cross - 1)));
+ }
+
+ return plan;
+ }
+
+ ///
+ /// Moves the walls between rooms off stairs: a wall that would run between two stair
+ /// cells steps one or two cells aside, where the rooms on both sides stay wide enough.
+ /// A wall that cannot is left where it is (the draft then leaves it open at the stairs).
+ ///
+ public static void Avoid(RoomPlan plan, ICollection<(int X, int Y)> stairs)
+ {
+ if (stairs.Count == 0 || plan.Rooms.Count < 2)
+ {
+ return;
+ }
+
+ foreach (bool alongY in new[] { true, false })
+ {
+ // A wall along Y stands after column c: between the rooms that end at c and those that start at c + 1.
+ int End((int X0, int Y0, int X1, int Y1) r) => alongY ? r.X1 : r.Y1;
+ int Start((int X0, int Y0, int X1, int Y1) r) => alongY ? r.X0 : r.Y0;
+ (int From, int To) Side((int X0, int Y0, int X1, int Y1) r) => alongY ? (r.Y0, r.Y1) : (r.X0, r.X1);
+ bool Cut(int c, List before)
+ {
+ foreach (int i in before)
+ {
+ (int from, int to) = Side(plan.Rooms[i]);
+ for (int at = from; at <= to; ++at)
+ {
+ if (alongY ? stairs.Contains((c, at)) && stairs.Contains((c + 1, at)) : stairs.Contains((at, c)) && stairs.Contains((at, c + 1)))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ foreach (int c in plan.Rooms.Select(End).Distinct().ToList())
+ {
+ var before = new List();
+ var after = new List();
+ for (int i = 0; i < plan.Rooms.Count; ++i)
+ {
+ if (End(plan.Rooms[i]) == c)
+ {
+ before.Add(i);
+ }
+ else if (Start(plan.Rooms[i]) == c + 1)
+ {
+ after.Add(i);
+ }
+ }
+
+ // Only a wall with the same rooms' length on both sides can move as one.
+ if (after.Count == 0 || before.Sum(i => Side(plan.Rooms[i]).To - Side(plan.Rooms[i]).From + 1) != after.Sum(i => Side(plan.Rooms[i]).To - Side(plan.Rooms[i]).From + 1) ||
+ !Cut(c, before))
+ {
+ continue;
+ }
+
+ foreach (int by in new[] { 1, -1, 2, -2 })
+ {
+ // A room keeps the least width; one already narrower (a corridor) keeps its own.
+ int least(int i) => Math.Min(MinRoom, End(plan.Rooms[i]) - Start(plan.Rooms[i]) + 1);
+ bool fits = before.All(i => c + by - Start(plan.Rooms[i]) + 1 >= least(i)) && after.All(i => End(plan.Rooms[i]) - (c + by + 1) + 1 >= least(i));
+ if (!fits || Cut(c + by, before))
+ {
+ continue;
+ }
+
+ foreach (int i in before)
+ {
+ (int x0, int y0, int x1, int y1) = plan.Rooms[i];
+ plan.Rooms[i] = alongY ? (x0, y0, c + by, y1) : (x0, y0, x1, c + by);
+ }
+
+ foreach (int i in after)
+ {
+ (int x0, int y0, int x1, int y1) = plan.Rooms[i];
+ plan.Rooms[i] = alongY ? (c + by + 1, y0, x1, y1) : (x0, c + by + 1, x1, y1);
+ }
+
+ break;
+ }
+ }
+ }
+ }
+
+ ///
+ /// Cuts a span of cells into parts of about the same size, each at least
+ /// long: fewer parts when the span is too short for that many.
+ ///
+ private static List<(int From, int To)> Split(int from, int length, int parts)
+ {
+ parts = Math.Max(1, Math.Min(parts, length / MinRoom));
+ var result = new List<(int, int)>();
+ int start = 0;
+ for (int i = 1; i <= parts; ++i)
+ {
+ int end = i == parts ? length : (int)Math.Round(i * length / (double)parts);
+ result.Add((from + start, from + end - 1));
+ start = end;
+ }
+
+ return result;
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/WallPlanner.cs b/UoFiddler.Plugin.MultiEditor/House/WallPlanner.cs
similarity index 79%
rename from UoFiddler.Plugin.MultiEditor/Classes/WallPlanner.cs
rename to UoFiddler.Plugin.MultiEditor/House/WallPlanner.cs
index 6dacbc84..9aa3214b 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/WallPlanner.cs
+++ b/UoFiddler.Plugin.MultiEditor/House/WallPlanner.cs
@@ -1,4 +1,4 @@
-/***************************************************************************
+/***************************************************************************
*
* $Author: Turley
*
@@ -11,8 +11,10 @@
using System;
using System.Collections.Generic;
+using UoFiddler.Plugin.MultiEditor.Model;
+using UoFiddler.Plugin.MultiEditor.Styles;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.House
{
///
/// Builds walls from cell edges. A wall piece sits on the +Y edge of its cell (a "South" piece,
@@ -173,7 +175,7 @@ void Edit(HashSet<(int, int)> set, (int X, int Y) cell)
continue;
}
- string column = PieceFor(cell.X, cell.Y);
+ string column = PieceFor(_style, _south, _east, cell.X, cell.Y);
ushort want = column != null ? _style.Get(column) : (ushort)0;
_pieces.TryGetValue(cell, out MultiTile have);
@@ -207,6 +209,53 @@ void Edit(HashSet<(int, int)> set, (int X, int Y) cell)
///
public string PieceFor(int x, int y) => PieceFor(_south, _east, x, y);
+ ///
+ /// The column of a style's piece for a cell. As ,
+ /// except in a paired style (): there the straight pieces of
+ /// a run alternate between the two halves of the ornament, counted from the run's start,
+ /// and the last piece of a run of odd length is the plain one.
+ ///
+ public static string PieceFor(HouseStyle style, HashSet<(int X, int Y)> southEdges, HashSet<(int X, int Y)> eastEdges, int x, int y)
+ {
+ string column = PieceFor(southEdges, eastEdges, x, y);
+ bool cycles = style != null && style.CycleSouth > 0 && style.CycleEast > 0;
+ if (style == null || (!style.Paired && !cycles) || column == null || column is "Corner" or "Post")
+ {
+ return column;
+ }
+
+ bool alongX = column.StartsWith("South", StringComparison.Ordinal);
+ bool Straight(int cx, int cy) => alongX
+ ? southEdges.Contains((cx, cy)) && !eastEdges.Contains((cx, cy))
+ : eastEdges.Contains((cx, cy)) && !southEdges.Contains((cx, cy));
+
+ int before = 0, after = 0;
+ while (Straight(alongX ? x - before - 1 : x, alongX ? y : y - before - 1))
+ {
+ ++before;
+ }
+
+ while (Straight(alongX ? x + after + 1 : x, alongX ? y : y + after + 1))
+ {
+ ++after;
+ }
+
+ // A set of panels: one after the other along the run.
+ if (cycles)
+ {
+ return alongX ? $"CycleSouth{(before % style.CycleSouth) + 1}" : $"CycleEast{(before % style.CycleEast) + 1}";
+ }
+
+ int length = before + after + 1;
+ if (length % 2 == 1 && after == 0)
+ {
+ return alongX ? "South2" : "East2";
+ }
+
+ bool firstHalf = before % 2 == 0;
+ return alongX ? (firstHalf ? "South1" : "South3") : (firstHalf ? "East3" : "East1");
+ }
+
///
/// The walls.txt column for a cell given the +Y edges () and
/// +X edges () of a wall layer.
diff --git a/UoFiddler.Plugin.MultiEditor/Model/ClipboardTile.cs b/UoFiddler.Plugin.MultiEditor/Model/ClipboardTile.cs
new file mode 100644
index 00000000..f025db11
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Model/ClipboardTile.cs
@@ -0,0 +1,97 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+
+namespace UoFiddler.Plugin.MultiEditor.Model
+{
+ ///
+ /// A copied group of tiles, relative to its lowest X, Y and Z. The Dynamic flag and extra field
+ /// travel with each tile, so a paste matches what was copied.
+ ///
+ internal sealed record ClipboardTile(ushort Id, int Dx, int Dy, int Dz, bool Invisible, int Extra)
+ {
+ ///
+ /// Multi text lines (0xID x y z flag, as the TXT export writes them) with the extra
+ /// field appended, which the TXT import ignores.
+ ///
+ public static string Format(IEnumerable tiles)
+ {
+ var text = new StringBuilder();
+ foreach (ClipboardTile t in tiles)
+ {
+ text.Append(CultureInfo.InvariantCulture, $"0x{t.Id:X4} {t.Dx} {t.Dy} {t.Dz} {(t.Invisible ? 0 : 1)} {t.Extra}").Append("\r\n");
+ }
+
+ return text.ToString();
+ }
+
+ ///
+ /// Reads multi text lines back, moved so the lowest X, Y and Z are 0. Returns null when any
+ /// non-empty line is not a tile line, so ordinary text on the clipboard is left alone.
+ ///
+ public static List Parse(string text)
+ {
+ if (string.IsNullOrWhiteSpace(text))
+ {
+ return null;
+ }
+
+ var tiles = new List();
+ foreach (string raw in text.Split('\n'))
+ {
+ string line = raw.Trim();
+ if (line.Length == 0)
+ {
+ continue;
+ }
+
+ string[] parts = line.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
+ if (parts.Length < 5 || parts.Length > 6)
+ {
+ return null;
+ }
+
+ string idText = parts[0].StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? parts[0][2..] : parts[0];
+ if (!ushort.TryParse(idText, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ushort id) ||
+ !int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int x) ||
+ !int.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out int y) ||
+ !int.TryParse(parts[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out int z) ||
+ !int.TryParse(parts[4], NumberStyles.Integer, CultureInfo.InvariantCulture, out int flag))
+ {
+ return null;
+ }
+
+ int extra = 0;
+ if (parts.Length == 6 && !int.TryParse(parts[5], NumberStyles.Integer, CultureInfo.InvariantCulture, out extra))
+ {
+ return null;
+ }
+
+ tiles.Add(new ClipboardTile(id, x, y, z, flag == 0, extra));
+ }
+
+ if (tiles.Count == 0)
+ {
+ return null;
+ }
+
+ int minX = tiles.Min(t => t.Dx);
+ int minY = tiles.Min(t => t.Dy);
+ int minZ = tiles.Min(t => t.Dz);
+ return tiles.Select(t => t with { Dx = t.Dx - minX, Dy = t.Dy - minY, Dz = t.Dz - minZ }).ToList();
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/EditCommand.cs b/UoFiddler.Plugin.MultiEditor/Model/EditCommand.cs
similarity index 79%
rename from UoFiddler.Plugin.MultiEditor/Classes/EditCommand.cs
rename to UoFiddler.Plugin.MultiEditor/Model/EditCommand.cs
index 3c787b4c..543a8db6 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/EditCommand.cs
+++ b/UoFiddler.Plugin.MultiEditor/Model/EditCommand.cs
@@ -1,4 +1,4 @@
-/***************************************************************************
+/***************************************************************************
*
* $Author: Turley
*
@@ -11,26 +11,8 @@
using System.Collections.Generic;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Model
{
- ///
- /// The saved fields of a tile, used to put a changed tile back.
- ///
- internal readonly record struct TileState(ushort Id, int X, int Y, int Z, bool Invisible, TileLayer Layer)
- {
- public static TileState Of(MultiTile tile) => new(tile.Id, tile.X, tile.Y, tile.Z, tile.Invisible, tile.Layer);
-
- public void ApplyTo(MultiTile tile)
- {
- tile.Id = Id;
- tile.Invisible = Invisible;
- tile.Layer = Layer;
- tile.X = X;
- tile.Y = Y;
- tile.Z = Z;
- }
- }
-
///
/// One undo step: the tiles an edit added, removed and changed, and the multi size before and
/// after. Tiles are kept as the same objects, so references to them survive undo and redo.
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs b/UoFiddler.Plugin.MultiEditor/Model/GroupTransform.cs
similarity index 93%
rename from UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs
rename to UoFiddler.Plugin.MultiEditor/Model/GroupTransform.cs
index e7f60b81..14a85882 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs
+++ b/UoFiddler.Plugin.MultiEditor/Model/GroupTransform.cs
@@ -1,4 +1,4 @@
-/***************************************************************************
+/***************************************************************************
*
* $Author: Turley
*
@@ -12,17 +12,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using UoFiddler.Plugin.MultiEditor.House;
+using UoFiddler.Plugin.MultiEditor.Rendering;
+using UoFiddler.Plugin.MultiEditor.Styles;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Model
{
- internal enum GroupTransformKind
- {
- RotateLeft,
- RotateRight,
- MirrorX,
- MirrorY
- }
-
///
/// Rotates or mirrors a group of tiles. Graphics in UO never turn, so a piece that faces a way
/// (a stair, roof slope, door) is swapped for the piece that faces the new way.
@@ -469,8 +464,31 @@ private static string TurnSlot(string slot, Func mapDirection, b
}
}
+ // Eave + side, Hip + corner and HipEave + corner (ceramic, crystal and shadow sets).
+ if (slot.StartsWith("Eave", StringComparison.Ordinal) && _directions.ContainsKey(slot.Substring(4)))
+ {
+ return "Eave" + mapDirection(slot.Substring(4));
+ }
+
+ foreach (string prefix in new[] { "HipEave", "Hip" })
+ {
+ if (slot.Length == prefix.Length + 2 && slot.StartsWith(prefix, StringComparison.Ordinal))
+ {
+ // A corner is two sides: both turn, and north or south is named first.
+ string first = mapDirection(_directions.Keys.First(d => d[0] == slot[^2]));
+ string second = mapDirection(_directions.Keys.First(d => d[0] == slot[^1]));
+ (string ns, string ew) = first[0] is 'N' or 'S' ? (first, second) : (second, first);
+ return prefix + ns[0] + ew[0];
+ }
+ }
+
if (swapsAxes)
{
+ if (slot is "NSEnd" or "EWEnd")
+ {
+ return slot == "NSEnd" ? "EWEnd" : "NSEnd";
+ }
+
if (slot == "NSCrosspiece")
{
return "EWCrosspiece";
diff --git a/UoFiddler.Plugin.MultiEditor/Model/GroupTransformKind.cs b/UoFiddler.Plugin.MultiEditor/Model/GroupTransformKind.cs
new file mode 100644
index 00000000..66a93b5b
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Model/GroupTransformKind.cs
@@ -0,0 +1,21 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Plugin.MultiEditor.Model
+{
+ internal enum GroupTransformKind
+ {
+ RotateLeft,
+ RotateRight,
+ MirrorX,
+ MirrorY
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/IMultiViewSettings.cs b/UoFiddler.Plugin.MultiEditor/Model/IMultiViewSettings.cs
similarity index 84%
rename from UoFiddler.Plugin.MultiEditor/Classes/IMultiViewSettings.cs
rename to UoFiddler.Plugin.MultiEditor/Model/IMultiViewSettings.cs
index 599b017a..17a0c796 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/IMultiViewSettings.cs
+++ b/UoFiddler.Plugin.MultiEditor/Model/IMultiViewSettings.cs
@@ -1,4 +1,4 @@
-/***************************************************************************
+/***************************************************************************
*
* $Author: MuadDib & Turley
*
@@ -10,7 +10,7 @@
***************************************************************************/
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Model
{
///
/// The view options the edited multi depends on.
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs b/UoFiddler.Plugin.MultiEditor/Model/MultiEditorComponentList.Layers.cs
similarity index 88%
rename from UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs
rename to UoFiddler.Plugin.MultiEditor/Model/MultiEditorComponentList.Layers.cs
index 07cece0e..f5b37194 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs
+++ b/UoFiddler.Plugin.MultiEditor/Model/MultiEditorComponentList.Layers.cs
@@ -11,7 +11,7 @@
using System.Collections.Generic;
using System.Linq;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Model
{
// The layers of the design: the list, the active one, and the edits on them. Changes to the
// list and to which layer a tile is on are undo steps; a layer's visibility is not.
@@ -111,6 +111,62 @@ public TileLayer LayerAdd(string name)
return layer;
}
+ ///
+ /// Removes some tiles and adds others in one undo step, each new one on the layer it
+ /// names, or on when it names none. Layers the multi does
+ /// not have yet are made on top of the others, in the order they are first named; the
+ /// active layer stays as it is. The multi grows to hold tiles added past its +X/+Y end.
+ ///
+ public void ReplaceTilesOnLayers(IEnumerable remove, IEnumerable<(ushort Id, int X, int Y, int Z, string Layer)> add,
+ string action, string defaultLayer)
+ {
+ var added = new List<(ushort Id, int X, int Y, int Z, string Layer)>(add);
+ BeginEdit(action);
+ foreach (MultiTile tile in new List(remove))
+ {
+ RecordRemove(tile);
+ }
+
+ int width = Width, height = Height;
+ foreach (var (_, x, y, _, _) in added)
+ {
+ if (x >= 0 && y >= 0)
+ {
+ width = Math.Max(width, x + 1);
+ height = Math.Max(height, y + 1);
+ }
+ }
+
+ if (width != Width || height != Height)
+ {
+ RebuildGrid(width, height, new List(RealTiles));
+ }
+
+ var byName = new Dictionary();
+ foreach (var (id, x, y, z, name) in added)
+ {
+ string wanted = name ?? defaultLayer;
+ if (!byName.TryGetValue(wanted, out TileLayer layer))
+ {
+ layer = _layers.FirstOrDefault(l => l.Name == wanted);
+ if (layer == null)
+ {
+ RecordLayers();
+ TileLayer active = ActiveLayer;
+ layer = new TileLayer(wanted);
+ _layers.Add(layer);
+ ActiveLayer = active;
+ }
+
+ byName[wanted] = layer;
+ }
+
+ RecordNew(id, x, y, z, false, 0, layer: layer);
+ }
+
+ EndEdit();
+ }
+
/// Removes a layer with its tiles. The last layer stays.
public bool LayerRemove(TileLayer layer)
{
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs b/UoFiddler.Plugin.MultiEditor/Model/MultiEditorComponentList.cs
similarity index 96%
rename from UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs
rename to UoFiddler.Plugin.MultiEditor/Model/MultiEditorComponentList.cs
index b11941e1..65e2b8aa 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs
+++ b/UoFiddler.Plugin.MultiEditor/Model/MultiEditorComponentList.cs
@@ -1,4 +1,4 @@
-/***************************************************************************
+/***************************************************************************
*
* $Author: MuadDib & Turley
*
@@ -13,8 +13,9 @@
using System.Collections.Generic;
using Ultima;
using UoFiddler.Controls.Classes;
+using UoFiddler.Plugin.MultiEditor.Rendering;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Model
{
///
/// The edited multi. Tiles are kept per cell, each cell sorted in draw order with its virtual
@@ -528,16 +529,37 @@ public void TileSetIds(IEnumerable<(MultiTile Tile, ushort Id)> changes, string
}
///
- /// Removes some tiles and adds others in one undo step (wall and house part tools).
+ /// Removes some tiles and adds others in one undo step (wall and house part tools). With
+ /// the multi is made bigger, in the same step, to hold tiles added
+ /// past its +X/+Y end; otherwise those are dropped.
///
- public void ReplaceTiles(IEnumerable remove, IEnumerable<(ushort Id, int X, int Y, int Z)> add, string action)
+ public void ReplaceTiles(IEnumerable remove, IEnumerable<(ushort Id, int X, int Y, int Z)> add, string action, bool grow = false)
{
+ add = new List<(ushort Id, int X, int Y, int Z)>(add);
BeginEdit(action);
foreach (MultiTile tile in new List(remove))
{
RecordRemove(tile);
}
+ if (grow)
+ {
+ int width = Width, height = Height;
+ foreach (var (_, x, y, _) in add)
+ {
+ if (x >= 0 && y >= 0)
+ {
+ width = Math.Max(width, x + 1);
+ height = Math.Max(height, y + 1);
+ }
+ }
+
+ if (width != Width || height != Height)
+ {
+ RebuildGrid(width, height, new List(RealTiles));
+ }
+ }
+
foreach (var (id, x, y, z) in add)
{
RecordNew(id, x, y, z, false, 0);
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/MultiTile.cs b/UoFiddler.Plugin.MultiEditor/Model/MultiTile.cs
similarity index 97%
rename from UoFiddler.Plugin.MultiEditor/Classes/MultiTile.cs
rename to UoFiddler.Plugin.MultiEditor/Model/MultiTile.cs
index b424e4fd..b4bfe357 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/MultiTile.cs
+++ b/UoFiddler.Plugin.MultiEditor/Model/MultiTile.cs
@@ -1,4 +1,4 @@
-/***************************************************************************
+/***************************************************************************
*
* $Author: MuadDib & Turley
*
@@ -12,10 +12,11 @@
using System;
using System.Collections.Generic;
using Ultima;
+using UoFiddler.Plugin.MultiEditor.Rendering;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Model
{
- public partial class MultiTile : IComparable
+ public class MultiTile : IComparable
{
private int _x;
private int _y;
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/RotationTable.cs b/UoFiddler.Plugin.MultiEditor/Model/RotationTable.cs
similarity index 96%
rename from UoFiddler.Plugin.MultiEditor/Classes/RotationTable.cs
rename to UoFiddler.Plugin.MultiEditor/Model/RotationTable.cs
index c32c8280..c70e6613 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/RotationTable.cs
+++ b/UoFiddler.Plugin.MultiEditor/Model/RotationTable.cs
@@ -1,4 +1,4 @@
-/***************************************************************************
+/***************************************************************************
*
* $Author: Turley
*
@@ -16,7 +16,7 @@
using System.Xml;
using UoFiddler.Controls.Classes;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Model
{
///
/// Facing table for tiles the client's house tables do not list (classic stairs, signs,
diff --git a/UoFiddler.Plugin.MultiEditor/Model/SavedLayer.cs b/UoFiddler.Plugin.MultiEditor/Model/SavedLayer.cs
new file mode 100644
index 00000000..875a45f4
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Model/SavedLayer.cs
@@ -0,0 +1,20 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System.Collections.Generic;
+
+namespace UoFiddler.Plugin.MultiEditor.Model
+{
+ ///
+ /// A layer as the layers file keeps it. is false for a layer that was
+ /// left out of the saved multi, so its tiles exist only here.
+ ///
+ internal sealed record SavedLayer(string Name, bool Visible, bool InFile,
+ List<(ushort Id, int X, int Y, int Z, bool Invisible, int Extra)> Tiles);
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/TileLayer.cs b/UoFiddler.Plugin.MultiEditor/Model/TileLayer.cs
similarity index 69%
rename from UoFiddler.Plugin.MultiEditor/Classes/TileLayer.cs
rename to UoFiddler.Plugin.MultiEditor/Model/TileLayer.cs
index 98c0dc11..75fb28d7 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/TileLayer.cs
+++ b/UoFiddler.Plugin.MultiEditor/Model/TileLayer.cs
@@ -7,9 +7,7 @@
*
***************************************************************************/
-using System.Collections.Generic;
-
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Model
{
///
/// A named group of tiles in a design. Every tile is on exactly one layer and new tiles go on
@@ -29,11 +27,4 @@ public TileLayer(string name)
public override string ToString() => Name;
}
-
- ///
- /// A layer as the layers file keeps it. is false for a layer that was
- /// left out of the saved multi, so its tiles exist only here.
- ///
- internal sealed record SavedLayer(string Name, bool Visible, bool InFile,
- List<(ushort Id, int X, int Y, int Z, bool Invisible, int Extra)> Tiles);
}
diff --git a/UoFiddler.Plugin.MultiEditor/Model/TileState.cs b/UoFiddler.Plugin.MultiEditor/Model/TileState.cs
new file mode 100644
index 00000000..1ad882a3
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Model/TileState.cs
@@ -0,0 +1,31 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Plugin.MultiEditor.Model
+{
+ ///
+ /// The saved fields of a tile, used to put a changed tile back.
+ ///
+ internal readonly record struct TileState(ushort Id, int X, int Y, int Z, bool Invisible, TileLayer Layer)
+ {
+ public static TileState Of(MultiTile tile) => new(tile.Id, tile.X, tile.Y, tile.Z, tile.Invisible, tile.Layer);
+
+ public void ApplyTo(MultiTile tile)
+ {
+ tile.Id = Id;
+ tile.Invisible = Invisible;
+ tile.Layer = Layer;
+ tile.X = X;
+ tile.Y = Y;
+ tile.Z = Z;
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/MultiEditorHouseStyles.xml b/UoFiddler.Plugin.MultiEditor/MultiEditorHouseStyles.xml
new file mode 100644
index 00000000..50c9b8f1
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/MultiEditorHouseStyles.xml
@@ -0,0 +1,870 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/ArtFacing.cs b/UoFiddler.Plugin.MultiEditor/Rendering/ArtFacing.cs
similarity index 94%
rename from UoFiddler.Plugin.MultiEditor/Classes/ArtFacing.cs
rename to UoFiddler.Plugin.MultiEditor/Rendering/ArtFacing.cs
index 4d3b5019..795badf9 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/ArtFacing.cs
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/ArtFacing.cs
@@ -12,33 +12,9 @@
using System;
using System.Collections.Generic;
using Ultima;
-using UoFiddler.Plugin.MultiEditor.Rendering;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Rendering
{
- /// Where a tile sits in its cell, which decides how it moves when a group is turned.
- internal enum TilePlacement
- {
- /// Fills or stands in the cell (floors, roofs, furniture).
- Cell,
-
- /// A wall along the cell's +Y edge.
- SouthEdge,
-
- /// A wall along the cell's +X edge.
- EastEdge,
-
- /// A post at the cell's +X/+Y corner.
- Vertex,
-
- ///
- /// A roof piece. Its art is drawn half a cell up the screen, so it covers the area around
- /// the cell's -X/-Y corner: the official houses put their roofs one cell further +X/+Y
- /// than the walls for that reason.
- ///
- Lifted
- }
-
///
/// What the art itself says about a tile's facing. Swapping the world's X and Y axes mirrors
/// the screen left to right, so the tile that shows the same piece along the other axis is the
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/ArtMasks.cs b/UoFiddler.Plugin.MultiEditor/Rendering/ArtMasks.cs
new file mode 100644
index 00000000..724f3f6a
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/ArtMasks.cs
@@ -0,0 +1,56 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System.Collections.Generic;
+
+namespace UoFiddler.Plugin.MultiEditor.Rendering
+{
+ ///
+ /// Which pixels of a static are drawn, for picking the tile under the cursor.
+ ///
+ internal sealed class ArtMasks
+ {
+ private sealed class Mask
+ {
+ public int Width;
+ public int Height;
+ public bool[] Opaque;
+ }
+
+ private readonly Dictionary _masks = new Dictionary();
+
+ /// True when the art has a drawn pixel at the given offset from its top left.
+ public bool Hit(ushort id, int x, int y)
+ {
+ if (x < 0 || y < 0)
+ {
+ return false;
+ }
+
+ if (!_masks.TryGetValue(id, out Mask mask))
+ {
+ byte[] rgba = ArtPixels.LoadStatic(id, out int width, out int height);
+ mask = new Mask { Width = width, Height = height, Opaque = new bool[width * height] };
+ for (int i = 0; rgba != null && i < mask.Opaque.Length; i++)
+ {
+ mask.Opaque[i] = rgba[(i * 4) + 3] != 0;
+ }
+
+ _masks[id] = mask;
+ }
+
+ return x < mask.Width && y < mask.Height && mask.Opaque[(y * mask.Width) + x];
+ }
+
+ public void Clear()
+ {
+ _masks.Clear();
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/ArtMetrics.cs b/UoFiddler.Plugin.MultiEditor/Rendering/ArtMetrics.cs
similarity index 87%
rename from UoFiddler.Plugin.MultiEditor/Classes/ArtMetrics.cs
rename to UoFiddler.Plugin.MultiEditor/Rendering/ArtMetrics.cs
index d49a4689..82d95010 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/ArtMetrics.cs
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/ArtMetrics.cs
@@ -1,4 +1,4 @@
-/***************************************************************************
+/***************************************************************************
*
* $Author: MuadDib & Turley
*
@@ -9,11 +9,10 @@
*
***************************************************************************/
-
using System.Drawing;
using Ultima;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Rendering
{
///
/// Size of a static's art, which places a tile on the canvas.
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/ArtPixels.cs b/UoFiddler.Plugin.MultiEditor/Rendering/ArtPixels.cs
index 147270c6..bcf4c56e 100644
--- a/UoFiddler.Plugin.MultiEditor/Rendering/ArtPixels.cs
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/ArtPixels.cs
@@ -7,7 +7,6 @@
*
***************************************************************************/
-using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using Ultima;
@@ -106,47 +105,4 @@ private static byte Expand5(int value)
return (byte)((value << 3) | (value >> 2));
}
}
-
- ///
- /// Which pixels of a static are drawn, for picking the tile under the cursor.
- ///
- internal sealed class ArtMasks
- {
- private sealed class Mask
- {
- public int Width;
- public int Height;
- public bool[] Opaque;
- }
-
- private readonly Dictionary _masks = new Dictionary();
-
- /// True when the art has a drawn pixel at the given offset from its top left.
- public bool Hit(ushort id, int x, int y)
- {
- if (x < 0 || y < 0)
- {
- return false;
- }
-
- if (!_masks.TryGetValue(id, out Mask mask))
- {
- byte[] rgba = ArtPixels.LoadStatic(id, out int width, out int height);
- mask = new Mask { Width = width, Height = height, Opaque = new bool[width * height] };
- for (int i = 0; rgba != null && i < mask.Opaque.Length; i++)
- {
- mask.Opaque[i] = rgba[(i * 4) + 3] != 0;
- }
-
- _masks[id] = mask;
- }
-
- return x < mask.Width && y < mask.Height && mask.Opaque[(y * mask.Width) + x];
- }
-
- public void Clear()
- {
- _masks.Clear();
- }
- }
}
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/GlCanvas.cs b/UoFiddler.Plugin.MultiEditor/Rendering/GlCanvas.cs
index b6c2742b..f841db65 100644
--- a/UoFiddler.Plugin.MultiEditor/Rendering/GlCanvas.cs
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/GlCanvas.cs
@@ -232,7 +232,7 @@ private RectangleF SceneBounds()
var list = _session.CompList;
if (_session.PlanMode)
{
- Size plan = MultiEditor.Classes.PlanView.ContentSize(list.Width, list.Height);
+ Size plan = MultiEditor.Rendering.PlanView.ContentSize(list.Width, list.Height);
return new RectangleF(0, 0, plan.Width, plan.Height);
}
@@ -243,7 +243,7 @@ private RectangleF SceneBounds()
float bottom = EditorSession.CellCorner(list.Width, list.Height, 0).Y;
foreach (var tile in list.RealTiles)
{
- if (!MultiEditor.Classes.ArtMetrics.TryGetSize(tile.Id, out int width, out int height))
+ if (!MultiEditor.Rendering.ArtMetrics.TryGetSize(tile.Id, out int width, out int height))
{
continue;
}
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/LineBatch.cs b/UoFiddler.Plugin.MultiEditor/Rendering/LineBatch.cs
new file mode 100644
index 00000000..ba3d8949
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/LineBatch.cs
@@ -0,0 +1,133 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Drawing;
+using OpenTK.Graphics.OpenGL4;
+
+namespace UoFiddler.Plugin.MultiEditor.Rendering
+{
+ ///
+ /// Draws one pixel wide lines in world space (grid, outlines, selection box).
+ ///
+ internal sealed class LineBatch : IDisposable
+ {
+ private const int FloatsPerVertex = 6;
+
+ private const string VertexSource = @"#version 330 core
+layout(location = 0) in vec2 aPos;
+layout(location = 1) in vec4 aColor;
+uniform vec2 uViewport;
+uniform vec2 uOrigin;
+uniform float uZoom;
+out vec4 vColor;
+void main()
+{
+ vec2 screen = floor((aPos - uOrigin) * uZoom + 0.5) + 0.5;
+ vec2 ndc = screen / uViewport * 2.0 - 1.0;
+ gl_Position = vec4(ndc.x, -ndc.y, 0.0, 1.0);
+ vColor = aColor;
+}";
+
+ private const string FragmentSource = @"#version 330 core
+in vec4 vColor;
+out vec4 color;
+void main()
+{
+ color = vColor;
+}";
+
+ private readonly ShaderProgram _shader;
+ private readonly int _vao;
+ private readonly int _vbo;
+ private float[] _data = new float[FloatsPerVertex * 1024];
+ private int _vertices;
+ private int _gpuCapacity;
+
+ public LineBatch()
+ {
+ _shader = new ShaderProgram(VertexSource, FragmentSource);
+ _vao = GL.GenVertexArray();
+ GL.BindVertexArray(_vao);
+ _vbo = GL.GenBuffer();
+ GL.BindBuffer(BufferTarget.ArrayBuffer, _vbo);
+ const int stride = FloatsPerVertex * sizeof(float);
+ GL.EnableVertexAttribArray(0);
+ GL.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, stride, 0);
+ GL.EnableVertexAttribArray(1);
+ GL.VertexAttribPointer(1, 4, VertexAttribPointerType.Float, false, stride, 2 * sizeof(float));
+ GL.BindVertexArray(0);
+ }
+
+ public void Add(float x0, float y0, float x1, float y1, Color color)
+ {
+ if ((_vertices + 2) * FloatsPerVertex > _data.Length)
+ {
+ Array.Resize(ref _data, _data.Length * 2);
+ }
+
+ Vertex(x0, y0, color);
+ Vertex(x1, y1, color);
+ }
+
+ public void Rectangle(RectangleF rect, Color color)
+ {
+ Add(rect.Left, rect.Top, rect.Right, rect.Top, color);
+ Add(rect.Right, rect.Top, rect.Right, rect.Bottom, color);
+ Add(rect.Right, rect.Bottom, rect.Left, rect.Bottom, color);
+ Add(rect.Left, rect.Bottom, rect.Left, rect.Top, color);
+ }
+
+ public void Flush(Camera2D camera, Size viewport)
+ {
+ if (_vertices == 0)
+ {
+ return;
+ }
+
+ _shader.Use();
+ GL.Uniform2(_shader.Uniform("uViewport"), (float)viewport.Width, viewport.Height);
+ GL.Uniform2(_shader.Uniform("uOrigin"), camera.OriginX, camera.OriginY);
+ GL.Uniform1(_shader.Uniform("uZoom"), camera.Zoom);
+
+ GL.BindVertexArray(_vao);
+ GL.BindBuffer(BufferTarget.ArrayBuffer, _vbo);
+ int bytes = _vertices * FloatsPerVertex * sizeof(float);
+ if (bytes > _gpuCapacity)
+ {
+ _gpuCapacity = _data.Length * sizeof(float);
+ GL.BufferData(BufferTarget.ArrayBuffer, _gpuCapacity, IntPtr.Zero, BufferUsageHint.StreamDraw);
+ }
+
+ GL.BufferSubData(BufferTarget.ArrayBuffer, IntPtr.Zero, bytes, _data);
+ GL.DrawArrays(PrimitiveType.Lines, 0, _vertices);
+ GL.BindVertexArray(0);
+ _vertices = 0;
+ }
+
+ public void Dispose()
+ {
+ _shader.Dispose();
+ GL.DeleteBuffer(_vbo);
+ GL.DeleteVertexArray(_vao);
+ }
+
+ private void Vertex(float x, float y, Color color)
+ {
+ int i = _vertices * FloatsPerVertex;
+ _data[i] = x;
+ _data[i + 1] = y;
+ _data[i + 2] = color.R / 255f;
+ _data[i + 3] = color.G / 255f;
+ _data[i + 4] = color.B / 255f;
+ _data[i + 5] = color.A / 255f;
+ ++_vertices;
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/PlanShape.cs b/UoFiddler.Plugin.MultiEditor/Rendering/PlanShape.cs
new file mode 100644
index 00000000..e9a65358
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/PlanShape.cs
@@ -0,0 +1,29 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+
+namespace UoFiddler.Plugin.MultiEditor.Rendering
+{
+ ///
+ /// How a tile shows in the plan view: as a wall on the cell's +Y (South) or +X (East) edge,
+ /// a post at the +X/+Y corner, a door in an edge, or none of these (the cell's fill).
+ ///
+ [Flags]
+ internal enum PlanShape
+ {
+ Fill = 0,
+ South = 1,
+ East = 2,
+ Post = 4,
+ Door = 8
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/PlanView.cs b/UoFiddler.Plugin.MultiEditor/Rendering/PlanView.cs
similarity index 95%
rename from UoFiddler.Plugin.MultiEditor/Classes/PlanView.cs
rename to UoFiddler.Plugin.MultiEditor/Rendering/PlanView.cs
index c08c45b7..fbcf3a9f 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/PlanView.cs
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/PlanView.cs
@@ -1,4 +1,4 @@
-/***************************************************************************
+/***************************************************************************
*
* $Author: Turley
*
@@ -14,23 +14,10 @@
using System.Drawing;
using Ultima;
using Ultima.Helpers;
+using UoFiddler.Plugin.MultiEditor.Model;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Rendering
{
- ///
- /// How a tile shows in the plan view: as a wall on the cell's +Y (South) or +X (East) edge,
- /// a post at the +X/+Y corner, a door in an edge, or none of these (the cell's fill).
- ///
- [Flags]
- internal enum PlanShape
- {
- Fill = 0,
- South = 1,
- East = 2,
- Post = 4,
- Door = 8
- }
-
///
/// The top-down plan view: every cell a square in the radar colour of its top tile, walls as
/// lines on the edges they stand on. Uses the same filters as the isometric view (height
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs b/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs
index 0b725215..6f2e5a7e 100644
--- a/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs
@@ -10,9 +10,9 @@
using System;
using System.Drawing;
using Ultima;
-using UoFiddler.Plugin.MultiEditor.Classes;
using UoFiddler.Plugin.MultiEditor.Tools;
using UoFiddler.Plugin.MultiEditor.Editing;
+using UoFiddler.Plugin.MultiEditor.Model;
namespace UoFiddler.Plugin.MultiEditor.Rendering
{
@@ -29,7 +29,8 @@ internal sealed class SceneRenderer : IDisposable, IToolOverlay
private static readonly SpriteTint _belowLevel = new SpriteTint(0.55f, 0.55f, 0.55f, 1f, 0f, 0f, 0f);
private static readonly SpriteTint _transparent = SpriteTint.Alpha(0.3f);
private static readonly SpriteTint _standable = new SpriteTint(0.6f, 1f, 0.6f, 1f, 0f, 0.3f, 0f);
- private static readonly SpriteTint _toolGhost = new SpriteTint(1f, 1f, 1f, 0.6f, 0f, 0.08f, 0.16f);
+ // Tiles a tool is about to place: see-through by the setting, with a little blue so they differ from placed ones.
+ private SpriteTint _toolGhost = new SpriteTint(1f, 1f, 1f, 0.8f, 0f, 0.08f, 0.16f);
private static readonly SpriteTint _removeMark = new SpriteTint(1f, 0.3f, 0.3f, 0.85f, 0.45f, 0f, 0f);
private static readonly SpriteTint _reference = new SpriteTint(0.7f, 0.8f, 1f, 0.4f, 0f, 0.05f, 0.15f);
@@ -81,6 +82,7 @@ public void Draw(EditorSession session, Camera2D camera, Size viewport)
_marqueeLine = settings.SelectionBox;
_marqueeFill = Color.FromArgb(40, settings.SelectionBox);
_workPlane = SpriteTint.Solid(settings.WorkPlane);
+ _toolGhost = new SpriteTint(1f, 1f, 1f, settings.PreviewOpacity / 100f, 0f, 0.08f, 0.16f);
if (!session.HasDocument)
{
@@ -126,6 +128,7 @@ public void Draw(EditorSession session, Camera2D camera, Size viewport)
if (!session.PickingWithAlt)
{
session.ActiveTool.PaintOverlay(this);
+ session.PaintIdleDraft(this);
}
LastSpriteCount += _sprites.Count;
_sprites.Flush(_atlas, camera, viewport);
@@ -566,7 +569,8 @@ void IToolOverlay.Ghost(ushort id, int x, int y, int z)
return;
}
- if (!_session.CompList.InBounds(x, y) || !_atlas.TryGet(id, out AtlasSprite sprite))
+ // A ghost may lie past the multi's end: tools that grow the multi show what they add.
+ if (x < 0 || y < 0 || !_atlas.TryGet(id, out AtlasSprite sprite))
{
return;
}
@@ -604,6 +608,51 @@ void IToolOverlay.Polyline(System.Collections.Generic.IReadOnlyList point
}
}
+ private static Color ToneColor(OverlayTone tone) => tone switch
+ {
+ OverlayTone.Selected => Color.FromArgb(255, 255, 214, 64),
+ OverlayTone.Hover => Color.FromArgb(255, 255, 255, 255),
+ OverlayTone.Remove => Color.FromArgb(255, 255, 80, 80),
+ _ => Color.FromArgb(200, 120, 190, 255)
+ };
+
+ void IToolOverlay.Outline(System.Collections.Generic.IReadOnlyList points, OverlayTone tone)
+ {
+ // Lines are a pixel wide: a strong outline is the same line drawn side by side.
+ Color color = ToneColor(tone);
+ int width = tone == OverlayTone.Selected ? 3 : tone == OverlayTone.Plain ? 1 : 2;
+ for (int pass = 0; pass < width; ++pass)
+ {
+ int shift = pass == 0 ? 0 : pass == 1 ? 1 : -1;
+ for (int i = 0; i < points.Count; i++)
+ {
+ Point a = points[i], b = points[(i + 1) % points.Count];
+ _lines.Add(a.X, a.Y + shift, b.X, b.Y + shift, color);
+ if (shift != 0)
+ {
+ _lines.Add(a.X + shift, a.Y, b.X + shift, b.Y, color);
+ }
+ }
+ }
+ }
+
+ void IToolOverlay.CellMark(int x, int y, int z, OverlayTone tone)
+ {
+ Color color = Color.FromArgb(tone == OverlayTone.Plain ? 40 : tone == OverlayTone.Selected ? 70 : 110, ToneColor(tone));
+ if (_session.PlanMode)
+ {
+ Point o = PlanView.CellOrigin(x, y);
+ Fill(o.X, o.Y, PlanView.Cell, PlanView.Cell, color);
+ return;
+ }
+
+ if (_atlas.TryGet(ArtAtlas.FloorKey, out AtlasSprite diamond))
+ {
+ PointF corner = EditorSession.CellCorner(x, y, z);
+ _sprites.Add(diamond, corner.X - 22, corner.Y, SpriteTint.Solid(color));
+ }
+ }
+
void IToolOverlay.Marquee(Rectangle rect)
{
if (_atlas.TryGet(ArtAtlas.WhiteKey, out AtlasSprite white))
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/SpriteBatch.cs b/UoFiddler.Plugin.MultiEditor/Rendering/SpriteBatch.cs
index fba6317f..f7c2bf42 100644
--- a/UoFiddler.Plugin.MultiEditor/Rendering/SpriteBatch.cs
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/SpriteBatch.cs
@@ -13,24 +13,6 @@
namespace UoFiddler.Plugin.MultiEditor.Rendering
{
- ///
- /// Colour change of a sprite: rgb * Mul + Add, alpha * MulA.
- ///
- internal readonly record struct SpriteTint(float MulR, float MulG, float MulB, float MulA, float AddR, float AddG, float AddB)
- {
- public static readonly SpriteTint None = new SpriteTint(1f, 1f, 1f, 1f, 0f, 0f, 0f);
-
- public static SpriteTint Solid(Color color)
- {
- return new SpriteTint(color.R / 255f, color.G / 255f, color.B / 255f, color.A / 255f, 0f, 0f, 0f);
- }
-
- public static SpriteTint Alpha(float alpha)
- {
- return new SpriteTint(1f, 1f, 1f, alpha, 0f, 0f, 0f);
- }
- }
-
///
/// Draws atlas sprites as instanced quads, in the order they were added.
///
@@ -190,122 +172,4 @@ private static void Attribute(int index, int size, int stride, int offsetFloats)
GL.VertexAttribDivisor(index, 1);
}
}
-
- ///
- /// Draws one pixel wide lines in world space (grid, outlines, selection box).
- ///
- internal sealed class LineBatch : IDisposable
- {
- private const int FloatsPerVertex = 6;
-
- private const string VertexSource = @"#version 330 core
-layout(location = 0) in vec2 aPos;
-layout(location = 1) in vec4 aColor;
-uniform vec2 uViewport;
-uniform vec2 uOrigin;
-uniform float uZoom;
-out vec4 vColor;
-void main()
-{
- vec2 screen = floor((aPos - uOrigin) * uZoom + 0.5) + 0.5;
- vec2 ndc = screen / uViewport * 2.0 - 1.0;
- gl_Position = vec4(ndc.x, -ndc.y, 0.0, 1.0);
- vColor = aColor;
-}";
-
- private const string FragmentSource = @"#version 330 core
-in vec4 vColor;
-out vec4 color;
-void main()
-{
- color = vColor;
-}";
-
- private readonly ShaderProgram _shader;
- private readonly int _vao;
- private readonly int _vbo;
- private float[] _data = new float[FloatsPerVertex * 1024];
- private int _vertices;
- private int _gpuCapacity;
-
- public LineBatch()
- {
- _shader = new ShaderProgram(VertexSource, FragmentSource);
- _vao = GL.GenVertexArray();
- GL.BindVertexArray(_vao);
- _vbo = GL.GenBuffer();
- GL.BindBuffer(BufferTarget.ArrayBuffer, _vbo);
- const int stride = FloatsPerVertex * sizeof(float);
- GL.EnableVertexAttribArray(0);
- GL.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, stride, 0);
- GL.EnableVertexAttribArray(1);
- GL.VertexAttribPointer(1, 4, VertexAttribPointerType.Float, false, stride, 2 * sizeof(float));
- GL.BindVertexArray(0);
- }
-
- public void Add(float x0, float y0, float x1, float y1, Color color)
- {
- if ((_vertices + 2) * FloatsPerVertex > _data.Length)
- {
- Array.Resize(ref _data, _data.Length * 2);
- }
-
- Vertex(x0, y0, color);
- Vertex(x1, y1, color);
- }
-
- public void Rectangle(RectangleF rect, Color color)
- {
- Add(rect.Left, rect.Top, rect.Right, rect.Top, color);
- Add(rect.Right, rect.Top, rect.Right, rect.Bottom, color);
- Add(rect.Right, rect.Bottom, rect.Left, rect.Bottom, color);
- Add(rect.Left, rect.Bottom, rect.Left, rect.Top, color);
- }
-
- public void Flush(Camera2D camera, Size viewport)
- {
- if (_vertices == 0)
- {
- return;
- }
-
- _shader.Use();
- GL.Uniform2(_shader.Uniform("uViewport"), (float)viewport.Width, viewport.Height);
- GL.Uniform2(_shader.Uniform("uOrigin"), camera.OriginX, camera.OriginY);
- GL.Uniform1(_shader.Uniform("uZoom"), camera.Zoom);
-
- GL.BindVertexArray(_vao);
- GL.BindBuffer(BufferTarget.ArrayBuffer, _vbo);
- int bytes = _vertices * FloatsPerVertex * sizeof(float);
- if (bytes > _gpuCapacity)
- {
- _gpuCapacity = _data.Length * sizeof(float);
- GL.BufferData(BufferTarget.ArrayBuffer, _gpuCapacity, IntPtr.Zero, BufferUsageHint.StreamDraw);
- }
-
- GL.BufferSubData(BufferTarget.ArrayBuffer, IntPtr.Zero, bytes, _data);
- GL.DrawArrays(PrimitiveType.Lines, 0, _vertices);
- GL.BindVertexArray(0);
- _vertices = 0;
- }
-
- public void Dispose()
- {
- _shader.Dispose();
- GL.DeleteBuffer(_vbo);
- GL.DeleteVertexArray(_vao);
- }
-
- private void Vertex(float x, float y, Color color)
- {
- int i = _vertices * FloatsPerVertex;
- _data[i] = x;
- _data[i + 1] = y;
- _data[i + 2] = color.R / 255f;
- _data[i + 3] = color.G / 255f;
- _data[i + 4] = color.B / 255f;
- _data[i + 5] = color.A / 255f;
- ++_vertices;
- }
- }
}
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/SpriteTint.cs b/UoFiddler.Plugin.MultiEditor/Rendering/SpriteTint.cs
new file mode 100644
index 00000000..2508288b
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/SpriteTint.cs
@@ -0,0 +1,31 @@
+/***************************************************************************
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System.Drawing;
+
+namespace UoFiddler.Plugin.MultiEditor.Rendering
+{
+ ///
+ /// Colour change of a sprite: rgb * Mul + Add, alpha * MulA.
+ ///
+ internal readonly record struct SpriteTint(float MulR, float MulG, float MulB, float MulA, float AddR, float AddG, float AddB)
+ {
+ public static readonly SpriteTint None = new SpriteTint(1f, 1f, 1f, 1f, 0f, 0f, 0f);
+
+ public static SpriteTint Solid(Color color)
+ {
+ return new SpriteTint(color.R / 255f, color.G / 255f, color.B / 255f, color.A / 255f, 0f, 0f, 0f);
+ }
+
+ public static SpriteTint Alpha(float alpha)
+ {
+ return new SpriteTint(1f, 1f, 1f, alpha, 0f, 0f, 0f);
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/TilePlacement.cs b/UoFiddler.Plugin.MultiEditor/Rendering/TilePlacement.cs
new file mode 100644
index 00000000..65a9f9c8
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Rendering/TilePlacement.cs
@@ -0,0 +1,36 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Plugin.MultiEditor.Rendering
+{
+ /// Where a tile sits in its cell, which decides how it moves when a group is turned.
+ internal enum TilePlacement
+ {
+ /// Fills or stands in the cell (floors, roofs, furniture).
+ Cell,
+
+ /// A wall along the cell's +Y edge.
+ SouthEdge,
+
+ /// A wall along the cell's +X edge.
+ EastEdge,
+
+ /// A post at the cell's +X/+Y corner.
+ Vertex,
+
+ ///
+ /// A roof piece. Its art is drawn half a cell up the screen, so it covers the area around
+ /// the cell's -X/-Y corner: the official houses put their roofs one cell further +X/+Y
+ /// than the walls for that reason.
+ ///
+ Lifted
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/Blueprints.cs b/UoFiddler.Plugin.MultiEditor/Storage/Blueprints.cs
similarity index 98%
rename from UoFiddler.Plugin.MultiEditor/Classes/Blueprints.cs
rename to UoFiddler.Plugin.MultiEditor/Storage/Blueprints.cs
index 87318e03..8cd2f1ab 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/Blueprints.cs
+++ b/UoFiddler.Plugin.MultiEditor/Storage/Blueprints.cs
@@ -1,4 +1,4 @@
-/***************************************************************************
+/***************************************************************************
*
* $Author: Turley
*
@@ -18,9 +18,9 @@
using System.Text;
using Ultima;
using UoFiddler.Controls.Classes;
-using UoFiddler.Plugin.MultiEditor.Tools;
+using UoFiddler.Plugin.MultiEditor.Model;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Storage
{
///
/// A blueprint to write: its name, how many tiles it has (as far as known before reading it,
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/DesignFile.cs b/UoFiddler.Plugin.MultiEditor/Storage/DesignFile.cs
similarity index 90%
rename from UoFiddler.Plugin.MultiEditor/Classes/DesignFile.cs
rename to UoFiddler.Plugin.MultiEditor/Storage/DesignFile.cs
index 12bcb59b..4c16927a 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/DesignFile.cs
+++ b/UoFiddler.Plugin.MultiEditor/Storage/DesignFile.cs
@@ -9,14 +9,14 @@
using System;
using System.Collections.Generic;
-using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using UoFiddler.Plugin.MultiEditor.Editing;
+using UoFiddler.Plugin.MultiEditor.Model;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Storage
{
///
/// What a design file holds: the design as the editor has it, which the client's multi and
@@ -29,8 +29,9 @@ namespace UoFiddler.Plugin.MultiEditor.Classes
/// The floors when they were set by hand, else null.
/// The layers, bottom first, each with all its tiles by cell.
/// Index of the active layer.
+ /// The houses placed with the House tool, each as a house draft, so they can be opened as drafts again; or null.
internal sealed record DesignData(string Name, int Width, int Height, int FirstFloorZ,
- List Levels, List Layers, int ActiveLayer);
+ List Levels, List Layers, int ActiveLayer, List Houses = null);
///
/// The editor's own design file (*.uomd): XML with the size, the floors and one element per
@@ -79,6 +80,14 @@ public static void Save(string path, DesignData design)
}
root.Add(layers);
+
+ // Read by this editor from the first format version on: an editor that does not know
+ // the element skips it, so it needs no new version.
+ if (design.Houses is { Count: > 0 })
+ {
+ root.Add(new XElement("Houses", design.Houses.Select(h => new XElement(h))));
+ }
+
new XDocument(root).Save(path);
}
@@ -131,7 +140,8 @@ public static DesignData Load(string path)
return new DesignData((string)root.Attribute("name") ?? string.Empty, width, height,
(int?)root.Attribute("firstFloorZ") ?? 0, levels is { Count: > 0 } ? levels : null,
- layers, (int?)layersElement?.Attribute("active") ?? 0);
+ layers, (int?)layersElement?.Attribute("active") ?? 0,
+ root.Element("Houses")?.Elements("House").Select(h => new XElement(h)).ToList());
}
catch (Exception ex) when (ex is XmlException or FormatException or OverflowException or IndexOutOfRangeException or ArgumentNullException)
{
diff --git a/UoFiddler.Plugin.MultiEditor/Storage/FavoritePage.cs b/UoFiddler.Plugin.MultiEditor/Storage/FavoritePage.cs
new file mode 100644
index 00000000..657dd0d2
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Storage/FavoritePage.cs
@@ -0,0 +1,29 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System.Collections.Generic;
+
+namespace UoFiddler.Plugin.MultiEditor.Storage
+{
+ /// A named page of favorite tiles.
+ internal sealed class FavoritePage
+ {
+ public FavoritePage(string name)
+ {
+ Name = name;
+ }
+
+ public string Name { get; set; }
+
+ /// Tile ids in the order they were added. The tile grid shows this list.
+ public List Tiles { get; } = new List();
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Storage/HouseDraftFile.cs b/UoFiddler.Plugin.MultiEditor/Storage/HouseDraftFile.cs
new file mode 100644
index 00000000..9cd3028c
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Storage/HouseDraftFile.cs
@@ -0,0 +1,361 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Xml;
+using System.Xml.Linq;
+using UoFiddler.Plugin.MultiEditor.House;
+using UoFiddler.Plugin.MultiEditor.Styles;
+
+namespace UoFiddler.Plugin.MultiEditor.Storage
+{
+ ///
+ /// A house draft as XML: one House element with its wings, the materials of each storey
+ /// and everything changed by hand. It is what a house draft file (*.uohouse) holds, and what
+ /// a design file and the layers file keep of each house placed in a multi, so the house can
+ /// be opened as a draft again. Styles are kept by kind, by a piece that tells them apart
+ /// () and by name; one the client does not have is left to
+ /// the draft's defaults.
+ ///
+ internal static class HouseDraftFile
+ {
+ public const string Extension = "uohouse";
+
+ public const string Filter = "House draft (*.uohouse)|*.uohouse|All files (*.*)|*.*";
+
+ private const string _root = "House";
+
+ /// Format version of the element: raise it when an older editor would misread the content.
+ private const int _version = 1;
+
+ public static XElement ToXml(IReadOnlyList wings, HouseDraft draft, string name)
+ {
+ var root = new XElement(_root,
+ new XAttribute("version", _version),
+ new XAttribute("name", LayerStore.XmlSafe(name ?? string.Empty, "House")),
+ new XAttribute("baseZ", wings.Count > 0 ? wings[0].EaveZ : draft.BaseZ),
+ new XAttribute("foundation", draft.Foundation));
+ if (draft.Gables != RoofGables.Front)
+ {
+ root.Add(new XAttribute("gables", draft.Gables));
+ }
+
+ if (draft.GableFill != RoofGableFill.Caps)
+ {
+ root.Add(new XAttribute("gableFill", draft.GableFill));
+ }
+
+ if (draft.Parapet)
+ {
+ root.Add(new XAttribute("battlements", true));
+ }
+
+ if (draft.AutoDoors)
+ {
+ root.Add(new XAttribute("roomDoors", true));
+ }
+
+ if (draft.FrontDoor != FrontDoorSide.None)
+ {
+ root.Add(new XAttribute("frontDoor", draft.FrontDoor));
+ }
+
+ if (draft.WindowSpacing > 0)
+ {
+ root.Add(new XAttribute("windowSpacing", draft.WindowSpacing));
+ }
+
+ AddStyle(root, "roof", draft.RoofStyle);
+ AddStyle(root, "flatRoof", draft.FlatRoofStyle);
+ AddStyle(root, "door", draft.DoorStyle);
+ AddStyle(root, "stairs", draft.StairStyle);
+ AddStyle(root, "foundationStyle", draft.FoundationStyle);
+ if (draft.FoundationTiers != 1)
+ {
+ root.Add(new XAttribute("foundationTiers", draft.FoundationTiers));
+ }
+
+ if (draft.FoundationHeight != HouseDraft.UsualFoundationHeight)
+ {
+ root.Add(new XAttribute("foundationHeight", draft.FoundationHeight));
+ }
+
+ foreach (RoofWing wing in wings)
+ {
+ var element = new XElement("Wing",
+ new XAttribute("x0", wing.X0), new XAttribute("y0", wing.Y0), new XAttribute("x1", wing.X1), new XAttribute("y1", wing.Y1),
+ new XAttribute("storeys", wing.Storeys),
+ new XAttribute("rooms", wing.Rooms),
+ new XAttribute("roof", wing.NoRoof ? "None" : wing.Shape.ToString()),
+ new XAttribute("ridge", wing.RidgeAuto ? "Auto" : wing.RidgeAlongY ? "Y" : "X"));
+ if (wing.Layout != RoomLayout.Row)
+ {
+ element.Add(new XAttribute("layout", wing.Layout));
+ }
+
+ if (wing.Walled)
+ {
+ element.Add(new XAttribute("walled", true));
+ }
+
+ // Storeys with rooms of their own, as "storey:rooms:layout".
+ string above = string.Join(" ", Enumerable.Range(1, HouseDraft.MaxStoreys - 1).Where(k => wing.RoomsAbove[k] != null)
+ .Select(k => $"{k.ToString(CultureInfo.InvariantCulture)}:{wing.RoomsAbove[k].Value.Rooms.ToString(CultureInfo.InvariantCulture)}:{wing.RoomsAbove[k].Value.Layout}"));
+ if (above.Length > 0)
+ {
+ element.Add(new XAttribute("roomsAbove", above));
+ }
+
+ root.Add(element);
+ }
+
+ for (int k = 0; k < HouseDraft.MaxStoreys; ++k)
+ {
+ var storey = new XElement("Storey", new XAttribute("index", k));
+ AddStyle(storey, "walls", draft.WallStyles[k]);
+ AddStyle(storey, "floor", draft.FloorStyles[k]);
+
+ AddCells(storey, "addedSouth", draft.AddedSouth[k]);
+ AddCells(storey, "addedEast", draft.AddedEast[k]);
+ AddCells(storey, "erasedSouth", draft.ErasedSouth[k]);
+ AddCells(storey, "erasedEast", draft.ErasedEast[k]);
+ AddCells(storey, "windows", draft.Windows.Where(w => w.Storey == k).Select(w => (w.X, w.Y)));
+ AddCells(storey, "setBack", draft.Suppressed.Where(w => w.Storey == k).Select(w => (w.X, w.Y)));
+ root.Add(storey);
+ }
+
+ foreach (var door in draft.Doors)
+ {
+ var element = new XElement("Door", new XAttribute("storey", door.Key.Storey), new XAttribute("x", door.Key.X), new XAttribute("y", door.Key.Y));
+ AddStyle(element, "style", door.Value.Style);
+ element.Add(new XAttribute("piece", door.Value.Piece));
+ root.Add(element);
+ }
+
+ foreach ((int storey, int x0, int y0, int x1, int y1, HouseStyle style) in draft.FloorAreas)
+ {
+ var element = new XElement("FloorArea", new XAttribute("storey", storey), new XAttribute("x0", x0), new XAttribute("y0", y0),
+ new XAttribute("x1", x1), new XAttribute("y1", y1));
+ AddStyle(element, "style", style);
+ root.Add(element);
+ }
+
+ foreach ((int storey, int x, int y, string column, HouseStyle style) in draft.Stairs)
+ {
+ var element = new XElement("Stairs", new XAttribute("storey", storey), new XAttribute("x", x), new XAttribute("y", y),
+ new XAttribute("column", column));
+ AddStyle(element, "style", style);
+ root.Add(element);
+ }
+
+ return root;
+ }
+
+ /// Names a style by its name and, in a second attribute (name + "Id"), by its anchor piece.
+ private static void AddStyle(XElement element, string name, HouseStyle style)
+ {
+ if (style == null)
+ {
+ return;
+ }
+
+ element.Add(new XAttribute(name, style.Name));
+ if (style.Anchor != 0)
+ {
+ element.Add(new XAttribute(name + "Id", HouseStyleConfig.FormatId(style.Anchor)));
+ }
+ }
+
+ private static void AddCells(XElement element, string name, IEnumerable<(int X, int Y)> cells)
+ {
+ string text = string.Join(" ", cells.Select(c => $"{c.X.ToString(CultureInfo.InvariantCulture)},{c.Y.ToString(CultureInfo.InvariantCulture)}"));
+ if (text.Length > 0)
+ {
+ element.Add(new XAttribute(name, text));
+ }
+ }
+
+ private static IEnumerable<(int X, int Y)> Cells(XElement element, string name)
+ {
+ foreach (string cell in ((string)element.Attribute(name) ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries))
+ {
+ string[] parts = cell.Split(',');
+ yield return (int.Parse(parts[0], CultureInfo.InvariantCulture), int.Parse(parts[1], CultureInfo.InvariantCulture));
+ }
+ }
+
+ ///
+ /// Reads a house back. gives the styles for anything the
+ /// element does not name or the client no longer has. Throws
+ /// when the element is not a house or is damaged.
+ ///
+ public static (List Wings, HouseDraft Draft, string Name) FromXml(XElement root, HouseStyles styles, HouseDraft materials)
+ {
+ try
+ {
+ if (root == null || root.Name.LocalName != _root)
+ {
+ throw new InvalidDataException("This is not a house draft.");
+ }
+
+ if (((int?)root.Attribute("version") ?? 0) > _version)
+ {
+ throw new InvalidDataException("This house draft was saved by a newer multi editor.");
+ }
+
+ // By its anchor piece first: that still finds a style the style file has since renamed.
+ HouseStyle Style(HousePartKind kind, XElement element, string attribute)
+ {
+ if (HouseStyleConfig.TryParseId((string)element.Attribute(attribute + "Id"), out ushort anchor) &&
+ styles.Styles.FirstOrDefault(s => s.Kind == kind && s.Anchor == anchor) is { } found)
+ {
+ return found;
+ }
+
+ string name = (string)element.Attribute(attribute);
+ return name == null ? null : styles.Styles.FirstOrDefault(s => s.Kind == kind && string.Equals(s.Name, name, StringComparison.Ordinal));
+ }
+
+ HouseDraft draft = materials.Fresh();
+ int baseZ = (int?)root.Attribute("baseZ") ?? 0;
+ draft.BaseZ = baseZ;
+ draft.Foundation = (bool?)root.Attribute("foundation") ?? false;
+ draft.Gables = Enum.TryParse((string)root.Attribute("gables"), out RoofGables gables) ? gables : RoofGables.Front;
+ draft.GableFill = Enum.TryParse((string)root.Attribute("gableFill"), out RoofGableFill gableFill) ? gableFill : RoofGableFill.Caps;
+ draft.Parapet = (bool?)root.Attribute("battlements") ?? false;
+ draft.AutoDoors = (bool?)root.Attribute("roomDoors") ?? false;
+ draft.FrontDoor = Enum.TryParse((string)root.Attribute("frontDoor"), out FrontDoorSide side) ? side : FrontDoorSide.None;
+ draft.WindowSpacing = Math.Clamp((int?)root.Attribute("windowSpacing") ?? 0, 0, 12);
+ // A draft saved before rooms were set per wing names one count for the house.
+ int houseRooms = (int?)root.Attribute("rooms") ?? 1;
+ draft.RoofStyle = Style(HousePartKind.Roof, root, "roof") ?? draft.RoofStyle;
+ draft.FlatRoofStyle = Style(HousePartKind.Floor, root, "flatRoof") ?? draft.FlatRoofStyle;
+ draft.DoorStyle = Style(HousePartKind.Door, root, "door") ?? draft.DoorStyle;
+ draft.StairStyle = Style(HousePartKind.Stair, root, "stairs") ?? draft.StairStyle;
+ draft.FoundationStyle = Style(HousePartKind.Wall, root, "foundationStyle");
+ draft.FoundationTiers = Math.Clamp((int?)root.Attribute("foundationTiers") ?? 1, 1, 3);
+ draft.FoundationHeight = Math.Clamp((int?)root.Attribute("foundationHeight") ?? HouseDraft.UsualFoundationHeight, 1, 20);
+
+ var wings = new List();
+ foreach (XElement element in root.Elements("Wing"))
+ {
+ string roof = (string)element.Attribute("roof") ?? "Gable";
+ string ridge = (string)element.Attribute("ridge") ?? "Auto";
+ var wing = new RoofWing
+ {
+ X0 = (int)element.Attribute("x0"), Y0 = (int)element.Attribute("y0"),
+ X1 = (int)element.Attribute("x1"), Y1 = (int)element.Attribute("y1"),
+ EaveZ = baseZ,
+ Storeys = Math.Clamp((int?)element.Attribute("storeys") ?? 1, 1, HouseDraft.MaxStoreys),
+ Rooms = Math.Clamp((int?)element.Attribute("rooms") ?? houseRooms, 1, HouseDraft.MaxRooms),
+ Layout = Enum.TryParse((string)element.Attribute("layout"), out RoomLayout layout) ? layout : RoomLayout.Row,
+ Walled = (bool?)element.Attribute("walled") ?? false,
+ NoRoof = roof == "None",
+ Shape = Enum.TryParse(roof, out RoofShape shape) ? shape : RoofShape.Gable,
+ RidgeAuto = ridge == "Auto"
+ };
+ wing.RidgeAlongY = wing.RidgeAuto
+ ? RoofPlanner.RidgeAlongY((wing.X0 + 1, wing.Y0 + 1, wing.X1 + 1, wing.Y1 + 1))
+ : ridge == "Y";
+ foreach (string part in ((string)element.Attribute("roomsAbove") ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries))
+ {
+ string[] fields = part.Split(':');
+ if (fields.Length == 3 && int.TryParse(fields[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out int k) &&
+ k >= 1 && k < HouseDraft.MaxStoreys &&
+ int.TryParse(fields[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int count) &&
+ Enum.TryParse(fields[2], out RoomLayout own))
+ {
+ wing.RoomsAbove[k] = (Math.Clamp(count, 1, HouseDraft.MaxRooms), own);
+ }
+ }
+
+ if (wing.X1 - wing.X0 >= 2 && wing.Y1 - wing.Y0 >= 2)
+ {
+ wings.Add(wing);
+ }
+ }
+
+ foreach (XElement element in root.Elements("Storey"))
+ {
+ int k = (int?)element.Attribute("index") ?? -1;
+ if (k < 0 || k >= HouseDraft.MaxStoreys)
+ {
+ continue;
+ }
+
+ draft.WallStyles[k] = Style(HousePartKind.Wall, element, "walls") ?? draft.WallStyles[k];
+ draft.FloorStyles[k] = Style(HousePartKind.Floor, element, "floor") ?? draft.FloorStyles[k];
+ draft.AddedSouth[k].UnionWith(Cells(element, "addedSouth"));
+ draft.AddedEast[k].UnionWith(Cells(element, "addedEast"));
+ draft.ErasedSouth[k].UnionWith(Cells(element, "erasedSouth"));
+ draft.ErasedEast[k].UnionWith(Cells(element, "erasedEast"));
+ foreach ((int x, int y) in Cells(element, "windows"))
+ {
+ draft.Windows.Add((k, x, y));
+ }
+
+ foreach ((int x, int y) in Cells(element, "setBack"))
+ {
+ draft.Suppressed.Add((k, x, y));
+ }
+ }
+
+ foreach (XElement element in root.Elements("Door"))
+ {
+ if (Style(HousePartKind.Door, element, "style") is { } style && (string)element.Attribute("piece") is { } piece)
+ {
+ draft.Doors[((int)element.Attribute("storey"), (int)element.Attribute("x"), (int)element.Attribute("y"))] = (style, piece);
+ }
+ }
+
+ foreach (XElement element in root.Elements("FloorArea"))
+ {
+ if (Style(HousePartKind.Floor, element, "style") is { } style)
+ {
+ draft.FloorAreas.Add(((int)element.Attribute("storey"), (int)element.Attribute("x0"), (int)element.Attribute("y0"),
+ (int)element.Attribute("x1"), (int)element.Attribute("y1"), style));
+ }
+ }
+
+ foreach (XElement element in root.Elements("Stairs"))
+ {
+ if (Style(HousePartKind.Stair, element, "style") is { } style && (string)element.Attribute("column") is { } column)
+ {
+ draft.Stairs.Add(((int)element.Attribute("storey"), (int)element.Attribute("x"), (int)element.Attribute("y"), column, style));
+ }
+ }
+
+ return (wings, draft, (string)root.Attribute("name") ?? "House");
+ }
+ catch (Exception ex) when (ex is XmlException or FormatException or OverflowException or IndexOutOfRangeException or ArgumentNullException)
+ {
+ throw new InvalidDataException("The house draft is damaged: " + ex.Message, ex);
+ }
+ }
+
+ /// The same house moved by a number of cells.
+ public static XElement Shifted(XElement house, int dx, int dy, HouseStyles styles)
+ {
+ var (wings, draft, name) = FromXml(house, styles, new HouseDraft());
+ foreach (RoofWing wing in wings)
+ {
+ (wing.X0, wing.X1, wing.Y0, wing.Y1) = (wing.X0 + dx, wing.X1 + dx, wing.Y0 + dy, wing.Y1 + dy);
+ }
+
+ draft.Shift(dx, dy);
+ return ToXml(wings, draft, name);
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/LayerStore.cs b/UoFiddler.Plugin.MultiEditor/Storage/LayerStore.cs
similarity index 91%
rename from UoFiddler.Plugin.MultiEditor/Classes/LayerStore.cs
rename to UoFiddler.Plugin.MultiEditor/Storage/LayerStore.cs
index 126f0d43..97e5404b 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/LayerStore.cs
+++ b/UoFiddler.Plugin.MultiEditor/Storage/LayerStore.cs
@@ -18,8 +18,9 @@
using System.Xml.Linq;
using Ultima;
using UoFiddler.Controls.Classes;
+using UoFiddler.Plugin.MultiEditor.Model;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Storage
{
///
/// The layers file: the client's multi cannot hold layers, so they are kept beside the
@@ -46,7 +47,8 @@ public static string FilePath(int clientId)
/// Keeps the layers of a multi saved to the client. A design with only the one plain layer
/// every design starts with has nothing to keep, and an older set for the same tiles goes.
///
- public static void Save(int clientId, List layers, int activeIndex, long fingerprint)
+ /// The houses placed with the House tool, as house drafts with cells counted from the save origin.
+ public static void Save(int clientId, List layers, int activeIndex, long fingerprint, IReadOnlyList houses = null)
{
string path = FilePath(clientId);
string multi = fingerprint.ToString(CultureInfo.InvariantCulture);
@@ -66,6 +68,11 @@ public static void Save(int clientId, List layers, int activeIndex,
TilesText(layer.Tiles)));
}
+ foreach (XElement house in houses ?? Array.Empty())
+ {
+ set.Add(new XElement(house));
+ }
+
sets.Insert(0, set);
}
@@ -87,7 +94,7 @@ public static void Save(int clientId, List layers, int activeIndex,
/// Reads the layers kept for a client multi with these tiles. Null when there are none or
/// the file cannot be read.
///
- public static (List Layers, int Active)? Load(int clientId, long fingerprint)
+ public static (List Layers, int Active, List Houses)? Load(int clientId, long fingerprint)
{
try
{
@@ -105,7 +112,7 @@ public static (List Layers, int Active)? Load(int clientId, long fin
(bool?)element.Attribute("visible") ?? true, (bool?)element.Attribute("inFile") ?? true, ParseTiles(element.Value)));
}
- return layers.Count == 0 ? null : (layers, (int?)set.Attribute("active") ?? 0);
+ return layers.Count == 0 ? null : (layers, (int?)set.Attribute("active") ?? 0, set.Elements("House").Select(h => new XElement(h)).ToList());
}
catch (Exception ex) when (ex is FormatException or IndexOutOfRangeException or OverflowException)
{
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/MapExtract.cs b/UoFiddler.Plugin.MultiEditor/Storage/MapExtract.cs
similarity index 94%
rename from UoFiddler.Plugin.MultiEditor/Classes/MapExtract.cs
rename to UoFiddler.Plugin.MultiEditor/Storage/MapExtract.cs
index 2b8a4257..10249566 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/MapExtract.cs
+++ b/UoFiddler.Plugin.MultiEditor/Storage/MapExtract.cs
@@ -1,4 +1,4 @@
-/***************************************************************************
+/***************************************************************************
*
* $Author: Turley
*
@@ -13,10 +13,10 @@
using System.Collections.Generic;
using System.Windows.Forms;
using Ultima;
-using UoFiddler.Plugin.MultiEditor.Tools;
+using UoFiddler.Plugin.MultiEditor.Model;
using UoFiddler.Plugin.MultiEditor.UI;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Storage
{
/// An area of a facet to copy statics from.
internal sealed record MapArea(Map Map, int X, int Y, int Width, int Height, int MinZ, int MaxZ, bool NewDesign);
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/TileFavorites.cs b/UoFiddler.Plugin.MultiEditor/Storage/TileFavorites.cs
similarity index 90%
rename from UoFiddler.Plugin.MultiEditor/Classes/TileFavorites.cs
rename to UoFiddler.Plugin.MultiEditor/Storage/TileFavorites.cs
index f6ffd7f3..845e3976 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/TileFavorites.cs
+++ b/UoFiddler.Plugin.MultiEditor/Storage/TileFavorites.cs
@@ -1,4 +1,4 @@
-/***************************************************************************
+/***************************************************************************
*
* $Author: Turley
*
@@ -17,22 +17,8 @@
using System.Xml;
using UoFiddler.Controls.Classes;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Storage
{
- /// A named page of favorite tiles.
- internal sealed class FavoritePage
- {
- public FavoritePage(string name)
- {
- Name = name;
- }
-
- public string Name { get; set; }
-
- /// Tile ids in the order they were added. The tile grid shows this list.
- public List Tiles { get; } = new List();
- }
-
///
/// Favorite tiles on named pages, saved in the profile folder (MultiEditorFavorites.xml).
/// UOHE bookmark files (an [Page] header, then $hex ids one per line) can be imported.
diff --git a/UoFiddler.Plugin.MultiEditor/Classes/TileRecentlyUsed.cs b/UoFiddler.Plugin.MultiEditor/Storage/TileRecentlyUsed.cs
similarity index 97%
rename from UoFiddler.Plugin.MultiEditor/Classes/TileRecentlyUsed.cs
rename to UoFiddler.Plugin.MultiEditor/Storage/TileRecentlyUsed.cs
index 52a5ff46..6436f6cc 100644
--- a/UoFiddler.Plugin.MultiEditor/Classes/TileRecentlyUsed.cs
+++ b/UoFiddler.Plugin.MultiEditor/Storage/TileRecentlyUsed.cs
@@ -4,7 +4,7 @@
using System.Xml.Linq;
using UoFiddler.Controls.Classes;
-namespace UoFiddler.Plugin.MultiEditor.Classes
+namespace UoFiddler.Plugin.MultiEditor.Storage
{
public static class TileRecentlyUsed
{
diff --git a/UoFiddler.Plugin.MultiEditor/Styles/HousePartKind.cs b/UoFiddler.Plugin.MultiEditor/Styles/HousePartKind.cs
new file mode 100644
index 00000000..ff3bbf33
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Styles/HousePartKind.cs
@@ -0,0 +1,24 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+namespace UoFiddler.Plugin.MultiEditor.Styles
+{
+ internal enum HousePartKind
+ {
+ Wall,
+ Floor,
+ Door,
+ Stair,
+ Roof,
+ Misc,
+ Teleporter
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Styles/HouseStyle.cs b/UoFiddler.Plugin.MultiEditor/Styles/HouseStyle.cs
new file mode 100644
index 00000000..bc09aefa
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Styles/HouseStyle.cs
@@ -0,0 +1,106 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+
+namespace UoFiddler.Plugin.MultiEditor.Styles
+{
+ ///
+ /// One row of a client house design table (walls.txt, floors.txt ...): a named set of pieces,
+ /// each under the column label the client uses (South1, Corner, F3, MultiNorth ...).
+ ///
+ internal sealed class HouseStyle
+ {
+ private readonly Dictionary _slots = new Dictionary();
+
+ public HouseStyle(HousePartKind kind, string group, string name)
+ {
+ Kind = kind;
+ Group = group;
+ Name = name;
+ }
+
+ public HousePartKind Kind { get; }
+
+ /// The category name (the first style's comment), grouping a material's styles.
+ public string Group { get; internal set; }
+
+ public string Name { get; internal set; }
+
+ /// The material, shared by the styles of every kind made of it. From the style file; may be empty.
+ public string Family { get; internal set; } = string.Empty;
+
+ /// True for a style the style file keeps out of the lists.
+ public bool Hidden { get; internal set; }
+
+ /// A piece that tells the style from every other of its kind: how files refer to it. 0 when it has none.
+ public ushort Anchor { get; internal set; }
+
+ /// False for a wall style that takes no post or corner from the other rows of its category.
+ internal bool Borrows { get; set; } = true;
+
+ /// The table category the style was read from, counted over all tables.
+ internal int Category { get; set; } = -1;
+
+ /// True for a wall style of a category sorted by its art.
+ internal bool ByArt { get; set; }
+
+ public IReadOnlyDictionary Slots => _slots;
+
+ ///
+ /// True for a wall style whose run pieces are the two halves of an ornament (the shadow
+ /// banner): South1 and South3 along X, East3 and East1 along Y, with South2 and East2 the
+ /// plain wall. A run is then laid as pairs, not as start, middle and end.
+ ///
+ public bool Paired { get; internal set; }
+
+ ///
+ /// For a wall style that is a set of different panels (the carved red marble): how many
+ /// it has along X (CycleSouth1 ...) and along Y (CycleEast1 ...). A run is laid as one
+ /// panel after another, starting again after the last. 0 for an ordinary style.
+ ///
+ public int CycleSouth { get; internal set; }
+
+ public int CycleEast { get; internal set; }
+
+ /// A piece to show for the style in lists.
+ public ushort IconId { get; private set; }
+
+ /// The piece under a column label, or 0 when the style has none.
+ ///
+ /// The tile of a piece, or 0 when the style has none. A tile past the client's tiledata (a
+ /// style read from another client) counts as none; the Multi columns hold multi ids.
+ ///
+ public ushort Get(string label) =>
+ _slots.TryGetValue(label, out ushort id) && (InTileData(id) || label.StartsWith("Multi", StringComparison.Ordinal)) ? id : (ushort)0;
+
+ /// True when the client's tiledata has the item.
+ public static bool InTileData(int id) => Ultima.TileData.ItemTable is { } items && id >= 0 && id < items.Length;
+
+ internal void Add(string label, ushort id)
+ {
+ _slots[label] = id;
+ if (IconId == 0)
+ {
+ IconId = id;
+ }
+ }
+
+ internal void Clear()
+ {
+ _slots.Clear();
+ IconId = 0;
+ }
+
+ public override string ToString() => Name;
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Styles/HouseStyleConfig.cs b/UoFiddler.Plugin.MultiEditor/Styles/HouseStyleConfig.cs
new file mode 100644
index 00000000..2cbb2846
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Styles/HouseStyleConfig.cs
@@ -0,0 +1,427 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Xml;
+using System.Xml.Linq;
+using UoFiddler.Controls.Classes;
+using UoFiddler.Plugin.MultiEditor.House;
+
+namespace UoFiddler.Plugin.MultiEditor.Styles
+{
+ ///
+ /// The style file (MultiEditorHouseStyles.xml): names, groups, order and corrected pieces for
+ /// the house styles read from the client's tables. One ships beside the plugin; a file of the
+ /// same name in the profile's plugins folder holds the user's changes, entry by entry, on
+ /// top of it.
+ ///
+ internal sealed class HouseStyleConfig
+ {
+ public const string FileName = "MultiEditorHouseStyles.xml";
+
+ private const string _root = "HouseStyles";
+ private const int _version = 1;
+
+ public List Styles { get; } = new List();
+
+ public List Themes { get; } = new List();
+
+ public List Foundations { get; } = new List();
+
+ /// The order of the styles of a kind, as anchors, where it is other than the order of the Style elements.
+ public Dictionary> Order { get; } = new Dictionary>();
+
+ public List Errors { get; } = new List();
+
+ public static string ShippedPath
+ {
+ get
+ {
+ string folder = Path.GetDirectoryName(typeof(HouseStyleConfig).Assembly.Location);
+ return string.IsNullOrEmpty(folder) ? null : Path.Combine(folder, FileName);
+ }
+ }
+
+ public static string UserPath => string.IsNullOrEmpty(Options.AppDataPath) ? null : Path.Combine(Options.AppDataPath, "plugins", FileName);
+
+ /// The shipped file with the user's file on top. A file that is missing or cannot be read counts as empty.
+ public static HouseStyleConfig Load()
+ {
+ HouseStyleConfig config = LoadFile(ShippedPath);
+ HouseStyleConfig user = LoadFile(UserPath);
+ foreach (HouseTheme theme in user.Themes)
+ {
+ theme.IsUser = true;
+ }
+
+ config.Merge(user);
+ return config;
+ }
+
+ public static HouseStyleConfig LoadFile(string path)
+ {
+ var config = new HouseStyleConfig();
+ if (string.IsNullOrEmpty(path) || !File.Exists(path))
+ {
+ return config;
+ }
+
+ try
+ {
+ XElement root = XDocument.Load(path).Root;
+ if (root == null || root.Name.LocalName != _root)
+ {
+ config.Errors.Add($"{Path.GetFileName(path)}: not a house style file");
+ return config;
+ }
+
+ if (ParseInt((string)root.Attribute("version")) > _version)
+ {
+ config.Errors.Add($"{Path.GetFileName(path)}: written by a newer version of the editor");
+ return config;
+ }
+
+ foreach (XElement element in root.Elements("Style"))
+ {
+ HouseStyleEntry entry = ReadStyle(element);
+ if (entry != null)
+ {
+ config.Styles.Add(entry);
+ }
+ else
+ {
+ config.Errors.Add($"{Path.GetFileName(path)}: a Style without a kind or an anchor (line {((IXmlLineInfo)element).LineNumber})");
+ }
+ }
+
+ foreach (XElement element in root.Elements("Order"))
+ {
+ if (!Enum.TryParse((string)element.Attribute("kind"), out HousePartKind kind))
+ {
+ continue;
+ }
+
+ var anchors = new List();
+ foreach (string text in element.Value.Split(new[] { ' ', '\r', '\n', '\t' }, StringSplitOptions.RemoveEmptyEntries))
+ {
+ if (TryParseId(text, out ushort id))
+ {
+ anchors.Add(id);
+ }
+ }
+
+ config.Order[kind] = anchors;
+ }
+
+ foreach (XElement element in root.Elements("Theme"))
+ {
+ string name = ((string)element.Attribute("name"))?.Trim();
+ if (string.IsNullOrEmpty(name))
+ {
+ continue;
+ }
+
+ ushort Id(string attribute) => TryParseId((string)element.Attribute(attribute), out ushort id) ? id : (ushort)0;
+ config.Themes.Add(new HouseTheme
+ {
+ Name = name,
+ Walls = Id("walls"),
+ Floor = Id("floor"),
+ Roof = Id("roof"),
+ FlatRoof = Id("flatRoof"),
+ Door = Id("door"),
+ Stairs = Id("stairs"),
+ Foundation = Id("foundation"),
+ FoundationTiers = Math.Clamp(ParseInt((string)element.Attribute("foundationTiers") ?? "1"), 1, 3),
+ FoundationHeight = Math.Clamp(ParseInt((string)element.Attribute("foundationHeight") ?? "7"), 1, 20)
+ });
+ }
+
+ foreach (XElement element in root.Elements("Foundation"))
+ {
+ string name = ((string)element.Attribute("name"))?.Trim();
+ if (string.IsNullOrEmpty(name))
+ {
+ continue;
+ }
+
+ config.Foundations.Add(new HouseFoundation
+ {
+ Name = name,
+ Style = TryParseId((string)element.Attribute("style"), out ushort style) ? style : (ushort)0,
+ Tiers = Math.Clamp(ParseInt((string)element.Attribute("tiers") ?? "1"), 1, 3),
+ Height = Math.Clamp(ParseInt((string)element.Attribute("height") ?? "7"), 1, 20)
+ });
+ }
+ }
+ catch (Exception ex) when (ex is IOException or XmlException or UnauthorizedAccessException)
+ {
+ config.Errors.Add($"{Path.GetFileName(path)}: {ex.Message}");
+ }
+
+ return config;
+ }
+
+ ///
+ /// Lays another file's entries over these. An entry for a style both name takes the other
+ /// file's values where it gives any; its other entries are added at the end. A theme of
+ /// the other file takes the place of one of the same name.
+ ///
+ public void Merge(HouseStyleConfig other)
+ {
+ Dictionary<(HousePartKind, ushort, bool), HouseStyleEntry> mine = Styles
+ .GroupBy(entry => entry.Key)
+ .ToDictionary(group => group.Key, group => group.First());
+ foreach (HouseStyleEntry theirs in other.Styles)
+ {
+ if (!mine.TryGetValue(theirs.Key, out HouseStyleEntry entry))
+ {
+ Styles.Add(theirs);
+ mine[theirs.Key] = theirs;
+ continue;
+ }
+
+ entry.Name = theirs.Name ?? entry.Name;
+ entry.Group = theirs.Group ?? entry.Group;
+ entry.Family = theirs.Family ?? entry.Family;
+ entry.Hidden = theirs.Hidden ?? entry.Hidden;
+ entry.Layout = theirs.Layout ?? entry.Layout;
+ entry.Borrows = theirs.Borrows ?? entry.Borrows;
+ entry.Pieces = theirs.Pieces ?? entry.Pieces;
+ if (theirs.Replaces.Count > 0)
+ {
+ entry.Replaces.Clear();
+ entry.Replaces.AddRange(theirs.Replaces);
+ }
+ }
+
+ foreach (KeyValuePair> order in other.Order)
+ {
+ Order[order.Key] = order.Value;
+ }
+
+ foreach (HouseFoundation foundation in other.Foundations)
+ {
+ Foundations.RemoveAll(mine => string.Equals(mine.Name, foundation.Name, StringComparison.OrdinalIgnoreCase));
+ Foundations.Add(foundation);
+ }
+
+ foreach (HouseTheme theme in other.Themes)
+ {
+ int index = Themes.FindIndex(mine => string.Equals(mine.Name, theme.Name, StringComparison.OrdinalIgnoreCase));
+ if (index >= 0)
+ {
+ Themes[index] = theme;
+ }
+ else
+ {
+ Themes.Add(theme);
+ }
+ }
+
+ Errors.AddRange(other.Errors);
+ }
+
+ /// Adds a theme to the user's copy of the style file, in place of one of the same name.
+ public static void SaveUserTheme(HouseTheme theme)
+ {
+ HouseStyleConfig user = LoadFile(UserPath);
+ user.Themes.RemoveAll(other => string.Equals(other.Name, theme.Name, StringComparison.OrdinalIgnoreCase));
+ user.Themes.Add(theme);
+ user.Save(UserPath);
+ }
+
+ /// Takes a theme out of the user's copy of the style file.
+ public static void DeleteUserTheme(string name)
+ {
+ HouseStyleConfig user = LoadFile(UserPath);
+ if (user.Themes.RemoveAll(other => string.Equals(other.Name, name, StringComparison.OrdinalIgnoreCase)) > 0)
+ {
+ user.Save(UserPath);
+ }
+ }
+
+ public void Save(string path)
+ {
+ var root = new XElement(_root, new XAttribute("version", _version));
+ foreach (HouseStyleEntry entry in Styles)
+ {
+ root.Add(WriteStyle(entry));
+ }
+
+ foreach (KeyValuePair> order in Order)
+ {
+ root.Add(new XElement("Order", new XAttribute("kind", order.Key), string.Join(" ", order.Value.Select(FormatId))));
+ }
+
+ foreach (HouseTheme theme in Themes)
+ {
+ var element = new XElement("Theme", new XAttribute("name", theme.Name));
+ void Id(string attribute, ushort id)
+ {
+ if (id != 0)
+ {
+ element.Add(new XAttribute(attribute, FormatId(id)));
+ }
+ }
+
+ Id("walls", theme.Walls);
+ Id("floor", theme.Floor);
+ Id("roof", theme.Roof);
+ Id("flatRoof", theme.FlatRoof);
+ Id("door", theme.Door);
+ Id("stairs", theme.Stairs);
+ Id("foundation", theme.Foundation);
+ if (theme.FoundationTiers != 1)
+ {
+ element.Add(new XAttribute("foundationTiers", theme.FoundationTiers));
+ }
+
+ if (theme.FoundationHeight != HouseDraft.UsualFoundationHeight)
+ {
+ element.Add(new XAttribute("foundationHeight", theme.FoundationHeight));
+ }
+
+ root.Add(element);
+ }
+
+ foreach (HouseFoundation foundation in Foundations)
+ {
+ var element = new XElement("Foundation", new XAttribute("name", foundation.Name));
+ if (foundation.Style != 0)
+ {
+ element.Add(new XAttribute("style", FormatId(foundation.Style)));
+ }
+
+ element.Add(new XAttribute("tiers", foundation.Tiers), new XAttribute("height", foundation.Height));
+ root.Add(element);
+ }
+
+ Directory.CreateDirectory(Path.GetDirectoryName(path) ?? string.Empty);
+ new XDocument(root).Save(path);
+ }
+
+ private static HouseStyleEntry ReadStyle(XElement element)
+ {
+ if (!Enum.TryParse((string)element.Attribute("kind"), out HousePartKind kind) ||
+ !TryParseId((string)element.Attribute("anchor"), out ushort anchor) || anchor == 0)
+ {
+ return null;
+ }
+
+ var entry = new HouseStyleEntry
+ {
+ Kind = kind,
+ Anchor = anchor,
+ IsNew = (bool?)element.Attribute("new") ?? false,
+ Name = (string)element.Attribute("name"),
+ Group = (string)element.Attribute("group"),
+ Family = (string)element.Attribute("family"),
+ Hidden = (bool?)element.Attribute("hidden"),
+ Layout = (string)element.Attribute("layout"),
+ Borrows = (bool?)element.Attribute("borrows")
+ };
+ foreach (string text in ((string)element.Attribute("replaces") ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries))
+ {
+ if (TryParseId(text, out ushort id))
+ {
+ entry.Replaces.Add(id);
+ }
+ }
+
+ List pieces = element.Elements("Piece").ToList();
+ if (pieces.Count > 0)
+ {
+ entry.Pieces = new List<(string, ushort)>();
+ foreach (XElement piece in pieces)
+ {
+ string role = (string)piece.Attribute("role");
+ if (!string.IsNullOrEmpty(role) && TryParseId((string)piece.Attribute("id"), out ushort id))
+ {
+ entry.Pieces.Add((role, id));
+ }
+ }
+ }
+
+ return entry;
+ }
+
+ private static XElement WriteStyle(HouseStyleEntry entry)
+ {
+ var element = new XElement("Style",
+ new XAttribute("kind", entry.Kind),
+ new XAttribute("anchor", FormatId(entry.Anchor)));
+ if (entry.IsNew)
+ {
+ element.Add(new XAttribute("new", true));
+ }
+
+ if (entry.Replaces.Count > 0)
+ {
+ element.Add(new XAttribute("replaces", string.Join(" ", entry.Replaces.Select(FormatId))));
+ }
+
+ AddText(element, "name", entry.Name);
+ AddText(element, "group", entry.Group);
+ AddText(element, "family", entry.Family);
+ AddText(element, "layout", entry.Layout);
+ if (entry.Hidden.HasValue)
+ {
+ element.Add(new XAttribute("hidden", entry.Hidden.Value));
+ }
+
+ if (entry.Borrows.HasValue)
+ {
+ element.Add(new XAttribute("borrows", entry.Borrows.Value));
+ }
+
+ if (entry.Pieces != null)
+ {
+ foreach ((string role, ushort id) in entry.Pieces)
+ {
+ element.Add(new XElement("Piece", new XAttribute("role", role), new XAttribute("id", FormatId(id))));
+ }
+ }
+
+ return element;
+ }
+
+ private static void AddText(XElement element, string name, string value)
+ {
+ if (value != null)
+ {
+ element.Add(new XAttribute(name, value));
+ }
+ }
+
+ public static string FormatId(ushort id) => "0x" + id.ToString("X4", CultureInfo.InvariantCulture);
+
+ public static bool TryParseId(string text, out ushort id)
+ {
+ id = 0;
+ if (string.IsNullOrWhiteSpace(text))
+ {
+ return false;
+ }
+
+ text = text.Trim();
+ return text.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
+ ? ushort.TryParse(text.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id)
+ : ushort.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out id);
+ }
+
+ private static int ParseInt(string text) => int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value) ? value : 0;
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Styles/HouseStyleEntry.cs b/UoFiddler.Plugin.MultiEditor/Styles/HouseStyleEntry.cs
new file mode 100644
index 00000000..342db1d4
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Styles/HouseStyleEntry.cs
@@ -0,0 +1,52 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System.Collections.Generic;
+
+namespace UoFiddler.Plugin.MultiEditor.Styles
+{
+ /// One Style element of the style file: what it says about one house style.
+ internal sealed class HouseStyleEntry
+ {
+ public const string LayoutRun = "Run";
+ public const string LayoutPaired = "Paired";
+ public const string LayoutCycle = "Cycle";
+
+ public HousePartKind Kind { get; set; }
+
+ /// A piece of the style: the entry is about the first style of its kind that lists it.
+ public ushort Anchor { get; set; }
+
+ /// True for a style the tables do not have: it is made from the entry's pieces.
+ public bool IsNew { get; set; }
+
+ /// Pieces of further styles this one takes the place of.
+ public List Replaces { get; } = new List();
+
+ public string Name { get; set; }
+
+ public string Group { get; set; }
+
+ public string Family { get; set; }
+
+ public bool? Hidden { get; set; }
+
+ /// How a wall run is laid: , or . Null leaves it.
+ public string Layout { get; set; }
+
+ public bool? Borrows { get; set; }
+
+ /// The style's pieces by column label, in place of the table's. Null keeps the table's.
+ public List<(string Role, ushort Id)> Pieces { get; set; }
+
+ public (HousePartKind Kind, ushort Anchor, bool IsNew) Key => (Kind, Anchor, IsNew);
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Styles/HouseStyles.Build.cs b/UoFiddler.Plugin.MultiEditor/Styles/HouseStyles.Build.cs
new file mode 100644
index 00000000..24983858
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Styles/HouseStyles.Build.cs
@@ -0,0 +1,434 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using UoFiddler.Controls.Classes.TilesInfo;
+using UoFiddler.Plugin.MultiEditor.Rendering;
+
+namespace UoFiddler.Plugin.MultiEditor.Styles
+{
+ internal sealed partial class HouseStyles
+ {
+ internal static HouseStyles Load(bool splitFloorsByColour, HouseStyleConfig config)
+ {
+ // New tables mean the client files may have changed: measure the art again.
+ ArtFacing.Clear();
+
+ var result = new HouseStyles { _splitFloors = splitFloorsByColour };
+ var wallNamesUsed = new HashSet(System.StringComparer.OrdinalIgnoreCase);
+ List files = TileGroupRegistry.LoadAll(out List errors);
+ int categoryNumber = 0;
+ foreach (TileGroupFile file in files)
+ {
+ if (!_kinds.TryGetValue(file.DisplayName, out HousePartKind kind))
+ {
+ continue;
+ }
+
+ foreach (TileCategory category in file.Categories)
+ {
+ int number = categoryNumber++;
+
+ // A roof set with more pieces than a row of roof.txt holds runs on into a second
+ // row of its category: the rows are one style.
+ if (kind == HousePartKind.Roof)
+ {
+ HouseStyle roof = RoofStyle(category);
+ if (roof.Slots.Count > 0)
+ {
+ roof.Category = number;
+ result.Styles.Add(roof);
+ }
+
+ continue;
+ }
+
+ // A category whose pieces are mostly not what their headings say is sorted by its art.
+ bool byArt = kind == HousePartKind.Wall && HeadingsAreOff(category);
+
+ // Wall rows are named so that each row of a category can be told from the others.
+ (string wallGroup, List wallNames) = kind == HousePartKind.Wall ? WallNames(category, wallNamesUsed, byArt) : (null, null);
+ for (int row = 0; row < category.Styles.Count; ++row)
+ {
+ TileStyle tileStyle = category.Styles[row];
+ var style = new HouseStyle(kind, wallGroup ?? category.Name, wallNames != null ? wallNames[row] : tileStyle.Name);
+ if (byArt)
+ {
+ SortByArt(style, PiecesOf(tileStyle), WindowPieces(tileStyle));
+ }
+ else
+ {
+ foreach (TileSlot slot in tileStyle.Slots)
+ {
+ // Stairs list stair multis; they are multi ids, not art.
+ bool multiColumn = IsMultiColumn(slot.Label);
+ if (slot.IsEmpty || slot.TileId > ushort.MaxValue || (!multiColumn && (!slot.IsValid || !HouseStyle.InTileData(slot.TileId))))
+ {
+ continue;
+ }
+
+ style.Add(slot.Label, (ushort)slot.TileId);
+ }
+ }
+
+ if (style.Slots.Count == 0)
+ {
+ continue;
+ }
+
+ IEnumerable parts = splitFloorsByColour && kind == HousePartKind.Floor
+ ? SplitByColour(style)
+ : new[] { style };
+ foreach (HouseStyle part in parts)
+ {
+ part.Category = number;
+ part.ByArt = byArt;
+ result.Styles.Add(part);
+ }
+ }
+ }
+ }
+
+ result.Apply(config);
+ result.BuildRoles();
+ result.FinishWalls();
+ result.Order();
+ result.SetThemes(config);
+ foreach (HouseStyle style in result.Styles)
+ {
+ if (string.IsNullOrEmpty(style.Family))
+ {
+ style.Family = style.Group ?? string.Empty;
+ }
+ }
+
+ result.Errors.AddRange(errors);
+ if (config != null)
+ {
+ result.Errors.AddRange(config.Errors);
+ }
+
+ return result;
+ }
+
+ /// Stairs list stair multis under "Multi" columns: multi ids, not art.
+ private static bool IsMultiColumn(string label) => label.StartsWith("Multi", System.StringComparison.Ordinal);
+
+ // Where each style named by the style file comes in the lists.
+ private readonly Dictionary _rank = new Dictionary();
+
+ ///
+ /// Applies the style file to the styles read from the tables. An entry finds its style by
+ /// a piece (its anchor): the first style of the kind that lists it. It can rename and
+ /// regroup the style, give it other pieces, and take the place of further styles (a set
+ /// the table spreads over several rows). An entry whose pieces this client has no art for
+ /// is left out, so one file serves every client.
+ ///
+ private void Apply(HouseStyleConfig config)
+ {
+ var owners = new Dictionary<(HousePartKind Kind, ushort Id), HouseStyle>();
+ foreach (HouseStyle style in Styles)
+ {
+ foreach (KeyValuePair piece in style.Slots)
+ {
+ if (!IsMultiColumn(piece.Key))
+ {
+ owners.TryAdd((style.Kind, piece.Value), style);
+ }
+ }
+ }
+
+ foreach (HouseStyle style in Styles)
+ {
+ foreach (KeyValuePair piece in style.Slots)
+ {
+ if (!IsMultiColumn(piece.Key) && owners[(style.Kind, piece.Value)] == style)
+ {
+ style.Anchor = piece.Value;
+ break;
+ }
+ }
+ }
+
+ if (config == null)
+ {
+ return;
+ }
+
+ var removed = new HashSet();
+ foreach (HouseStyleEntry entry in config.Styles)
+ {
+ List<(string Role, ushort Id)> pieces = entry.Pieces?
+ .Where(piece => IsMultiColumn(piece.Role) || (piece.Id < Ultima.TileData.ItemTable.Length && Ultima.Art.IsValidStatic(piece.Id)))
+ .ToList();
+ if (pieces != null && !pieces.Any(piece => !IsMultiColumn(piece.Role)))
+ {
+ continue;
+ }
+
+ HouseStyle target = null;
+ if (!entry.IsNew)
+ {
+ owners.TryGetValue((entry.Kind, entry.Anchor), out target);
+ }
+
+ if (target == null)
+ {
+ // A style of the file's own. It stands where the first style it replaces stood.
+ if (pieces == null)
+ {
+ continue;
+ }
+
+ HouseStyle first = null;
+ foreach (ushort id in entry.Replaces)
+ {
+ if (owners.TryGetValue((entry.Kind, id), out first))
+ {
+ break;
+ }
+ }
+
+ target = new HouseStyle(entry.Kind, entry.Group ?? entry.Name ?? string.Empty, entry.Name ?? string.Empty)
+ {
+ Category = first?.Category ?? -1,
+ ByArt = first?.ByArt ?? false
+ };
+ int at = first != null ? Styles.IndexOf(first) : -1;
+ Styles.Insert(at >= 0 ? at : Styles.Count, target);
+ }
+
+ if (pieces != null)
+ {
+ target.Clear();
+ foreach ((string role, ushort id) in pieces)
+ {
+ target.Add(role, id);
+ }
+ }
+
+ foreach (ushort id in entry.Replaces)
+ {
+ if (owners.TryGetValue((entry.Kind, id), out HouseStyle other) && other != target)
+ {
+ removed.Add(other);
+ }
+ }
+
+ target.Anchor = entry.Anchor != 0 ? entry.Anchor : target.IconId;
+ target.Name = entry.Name ?? target.Name;
+ target.Group = entry.Group ?? target.Group;
+ target.Family = entry.Family ?? target.Family;
+ target.Hidden = entry.Hidden ?? target.Hidden;
+ target.Borrows = entry.Borrows ?? target.Borrows;
+ if (entry.Layout != null)
+ {
+ target.Paired = entry.Layout == HouseStyleEntry.LayoutPaired;
+ bool cycle = entry.Layout == HouseStyleEntry.LayoutCycle;
+ target.CycleSouth = cycle ? target.Slots.Keys.Count(label => label.StartsWith("CycleSouth", System.StringComparison.Ordinal)) : 0;
+ target.CycleEast = cycle ? target.Slots.Keys.Count(label => label.StartsWith("CycleEast", System.StringComparison.Ordinal)) : 0;
+ }
+
+ _rank[target] = _rank.Count;
+ }
+
+ Styles.RemoveAll(removed.Contains);
+
+ // An order of the user's for a kind goes over the order of the entries.
+ foreach (KeyValuePair> order in config.Order)
+ {
+ var placed = new HashSet();
+ int next = _rank.Count == 0 ? 0 : _rank.Values.Max() + 1;
+ foreach (ushort anchor in order.Value)
+ {
+ HouseStyle style = Styles.FirstOrDefault(s => s.Kind == order.Key && s.Anchor == anchor);
+ if (style != null && placed.Add(style))
+ {
+ _rank[style] = next++;
+ }
+ }
+
+ // The styles of the kind the order does not name keep their place among themselves, behind it.
+ foreach (HouseStyle style in Styles.Where(s => s.Kind == order.Key && !placed.Contains(s) && _rank.ContainsKey(s)).OrderBy(s => _rank[s]).ToList())
+ {
+ _rank[style] = next++;
+ }
+ }
+ }
+
+ ///
+ /// The lookup from a tile to its style and column: the first style that lists it. A panel
+ /// of a style that goes through its panels in turn counts as a plain run piece for
+ /// everything that asks what a tile is (redrawing, turning).
+ ///
+ private void BuildRoles()
+ {
+ foreach (HouseStyle style in Styles)
+ {
+ foreach (KeyValuePair piece in style.Slots)
+ {
+ if (IsMultiColumn(piece.Key))
+ {
+ continue;
+ }
+
+ string label = piece.Key.StartsWith("CycleSouth", System.StringComparison.Ordinal) ? "South2"
+ : piece.Key.StartsWith("CycleEast", System.StringComparison.Ordinal) ? "East2"
+ : piece.Key;
+ _roles.TryAdd(piece.Value, (style, label));
+ }
+ }
+ }
+
+ ///
+ /// Makes every wall style build whole walls: empty run columns are filled, a row without a
+ /// post borrows one from its category, and in a category sorted by its art corners and
+ /// posts are lent between the rows. A style the file marks as not borrowing is two or
+ /// three pieces on their own and stays as it is.
+ ///
+ private void FinishWalls()
+ {
+ var posts = new Dictionary>();
+ var sorted = new Dictionary>();
+ foreach (HouseStyle style in Styles)
+ {
+ if (style.Kind != HousePartKind.Wall)
+ {
+ continue;
+ }
+
+ if (style.ByArt && style.Borrows)
+ {
+ if (!sorted.TryGetValue(style.Category, out List rows))
+ {
+ sorted[style.Category] = rows = new List();
+ }
+
+ rows.Add(style);
+ }
+
+ FillWallRuns(style, style.Get("CycleSouth1"), style.Get("CycleEast1"));
+
+ // A row without a post (Celtic Walls 2) borrows the one of an earlier row
+ // of its category that is as high: the same wall, differently decorated.
+ if (!posts.TryGetValue(style.Category, out List categoryPosts))
+ {
+ posts[style.Category] = categoryPosts = new List();
+ }
+
+ ushort post = style.Get("Post"), straight = style.Get("South1");
+ if (post != 0)
+ {
+ categoryPosts.Add(post);
+ }
+ else if (straight != 0 && style.Borrows)
+ {
+ foreach (ushort other in categoryPosts)
+ {
+ if (Ultima.TileData.ItemTable[other].Height == Ultima.TileData.ItemTable[straight].Height)
+ {
+ style.Add("Post", other);
+ break;
+ }
+ }
+ }
+ }
+
+ foreach (List rows in sorted.Values)
+ {
+ LendCornersAndPosts(rows);
+ }
+ }
+
+ ///
+ /// Puts the styles in the style file's order. A style the file does not name (one only
+ /// another client version has) stays behind the style it follows in the tables.
+ ///
+ private void Order()
+ {
+ if (_rank.Count == 0)
+ {
+ return;
+ }
+
+ var last = new Dictionary();
+ var keys = new Dictionary();
+ for (int i = 0; i < Styles.Count; ++i)
+ {
+ HouseStyle style = Styles[i];
+ if (_rank.TryGetValue(style, out int rank))
+ {
+ last[style.Kind] = rank;
+ }
+ else if (!last.TryGetValue(style.Kind, out rank))
+ {
+ rank = -1;
+ }
+
+ keys[style] = (rank, _rank.ContainsKey(style) ? -1 : i);
+ }
+
+ List ordered = Styles.OrderBy(style => keys[style].Rank).ThenBy(style => keys[style].Index).ToList();
+ Styles.Clear();
+ Styles.AddRange(ordered);
+ }
+
+ ///
+ /// In a category sorted by its art, a row often has walls but no corner or post of its
+ /// own: the set's corners and posts sit in another row. Such a style takes the first
+ /// piece of the category that is a corner (or post) of its walls' height.
+ ///
+ private static void LendCornersAndPosts(List styles)
+ {
+ static int Class(ushort id) => Ultima.TileData.ItemTable[id].Height >= 15 ? 2 : Ultima.TileData.ItemTable[id].Height >= 8 ? 1 : 0;
+ var pieces = new List();
+ foreach (HouseStyle style in styles)
+ {
+ foreach (ushort id in style.Slots.Values)
+ {
+ if (!pieces.Contains(id))
+ {
+ pieces.Add(id);
+ }
+ }
+ }
+
+ foreach (HouseStyle style in styles)
+ {
+ ushort wall = style.Get("South1") != 0 ? style.Get("South1") : style.Get("East1");
+ if (wall == 0)
+ {
+ continue;
+ }
+
+ foreach ((string column, TilePlacement placement) in new[] { ("Corner", TilePlacement.Cell), ("Post", TilePlacement.Vertex) })
+ {
+ if (style.Get(column) != 0)
+ {
+ continue;
+ }
+
+ foreach (ushort id in pieces)
+ {
+ if (Class(id) == Class(wall) && ArtFacing.Placement(id) == placement &&
+ (Ultima.TileData.ItemTable[id].Flags & Ultima.TileFlag.Window) == 0)
+ {
+ style.Add(column, id);
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/UoFiddler.Plugin.MultiEditor/Styles/HouseStyles.Classify.cs b/UoFiddler.Plugin.MultiEditor/Styles/HouseStyles.Classify.cs
new file mode 100644
index 00000000..88bff708
--- /dev/null
+++ b/UoFiddler.Plugin.MultiEditor/Styles/HouseStyles.Classify.cs
@@ -0,0 +1,411 @@
+/***************************************************************************
+ *
+ * $Author: Turley
+ *
+ * "THE BEER-WARE LICENSE"
+ * As long as you retain this notice you can do whatever you want with
+ * this stuff. If we meet some day, and you think this stuff is worth it,
+ * you can buy me a beer in return.
+ *
+ ***************************************************************************/
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using UoFiddler.Controls.Classes.TilesInfo;
+using UoFiddler.Plugin.MultiEditor.Rendering;
+
+namespace UoFiddler.Plugin.MultiEditor.Styles
+{
+ internal sealed partial class HouseStyles
+ {
+ /// The pieces a row lists under its window headings.
+ private static HashSet WindowPieces(TileStyle row)
+ {
+ var ids = new HashSet();
+ foreach (TileSlot slot in row.Slots)
+ {
+ if (!slot.IsEmpty && slot.IsValid && slot.TileId <= ushort.MaxValue && slot.Label.Contains("Window", System.StringComparison.Ordinal))
+ {
+ ids.Add((ushort)slot.TileId);
+ }
+ }
+
+ return ids;
+ }
+
+ /// The pieces a row lists, each once, in the row's order.
+ private static List PiecesOf(TileStyle row)
+ {
+ var ids = new List();
+ foreach (TileSlot slot in row.Slots)
+ {
+ if (!slot.IsEmpty && slot.IsValid && HouseStyle.InTileData(slot.TileId) && !ids.Contains((ushort)slot.TileId))
+ {
+ ids.Add((ushort)slot.TileId);
+ }
+ }
+
+ return ids;
+ }
+
+ private static readonly string[] _southWindows = { "WindowS", "AltWindowS", "SecondAltWindowS" };
+ private static readonly string[] _eastWindows = { "WindowE", "AltWindowE", "SecondAltWindowE" };
+
+ /// What a wall column's heading says its piece is.
+ private static TilePlacement HeadingPlacement(string label)
+ {
+ return label == "Corner" ? TilePlacement.Cell
+ : label == "Post" ? TilePlacement.Vertex
+ : label.StartsWith("South", System.StringComparison.Ordinal) || label.EndsWith("S", System.StringComparison.Ordinal) ? TilePlacement.SouthEdge
+ : TilePlacement.EastEdge;
+ }
+
+ ///
+ /// True for a walls.txt category where at least three pieces in ten are not what their
+ /// column heading says, going by the art: a piece under "South" that runs along Y, a
+ /// "Corner" that is a straight wall. All the gargish sets and the gothic one are like
+ /// that; in the other categories it is at most a spare window under "Corner".
+ ///
+ private static bool HeadingsAreOff(TileCategory category)
+ {
+ int pieces = 0, off = 0;
+ foreach (TileStyle row in category.Styles)
+ {
+ foreach (TileSlot slot in row.Slots)
+ {
+ if (slot.IsEmpty || !slot.IsValid || slot.TileId > ushort.MaxValue)
+ {
+ continue;
+ }
+
+ ++pieces;
+ if (ArtFacing.Placement((ushort)slot.TileId) != HeadingPlacement(slot.Label))
+ {
+ ++off;
+ }
+ }
+ }
+
+ return pieces > 0 && off * 10 >= pieces * 3;
+ }
+
+ ///
+ /// Fills a wall style from a row whose headings cannot be trusted. Each piece goes where
+ /// its art says: a wall along X to the South columns, one along Y to the East columns, a
+ /// piece that fills its cell's corner to Corner, a column to Post, windows to the window
+ /// columns. The pieces keep the row's order. What does not fit (a fourth wall along X, a
+ /// second corner, a piece of another height than most of the row) stays with the style as
+ /// a "More" piece, to place by hand.
+ ///
+ private static void SortByArt(HouseStyle style, List ids, HashSet listedAsWindows)
+ {
+ if (ids.Count == 0)
+ {
+ return;
+ }
+
+ // The row's usual height: full, half or low walls.
+ static int Class(ushort id) => Ultima.TileData.ItemTable[id].Height >= 15 ? 2 : Ultima.TileData.ItemTable[id].Height >= 8 ? 1 : 0;
+ int usual = ids.GroupBy(Class).OrderByDescending(g => g.Count()).ThenByDescending(g => g.Key).First().Key;
+
+ int more = 0;
+ void Put(string[] columns, ushort id)
+ {
+ foreach (string column in columns)
+ {
+ if (style.Get(column) == 0)
+ {
+ style.Add(column, id);
+ return;
+ }
+ }
+
+ style.Add($"More{++more}", id);
+ }
+
+ foreach (ushort id in ids)
+ {
+ // An arch or opening the table lists under a window heading is one, flagged or not.
+ bool window = (Ultima.TileData.ItemTable[id].Flags & Ultima.TileFlag.Window) != 0 || listedAsWindows.Contains(id);
+ if (Class(id) != usual)
+ {
+ style.Add($"More{++more}", id);
+ continue;
+ }
+
+ switch (ArtFacing.Placement(id))
+ {
+ case TilePlacement.SouthEdge:
+ Put(window ? _southWindows : _southRun, id);
+ break;
+ case TilePlacement.EastEdge:
+ Put(window ? _eastWindows : _eastRun, id);
+ break;
+ case TilePlacement.Vertex:
+ Put(new[] { "Post" }, id);
+ break;
+ default:
+ Put(new[] { "Corner" }, id);
+ break;
+ }
+ }
+ }
+
+ private static readonly string[] _southRun = { "South1", "South2", "South3" };
+ private static readonly string[] _eastRun = { "East1", "East2", "East3" };
+
+ ///
+ /// Many wall rows list one piece per direction where the table has three columns (the
+ /// start, middle and end of a run): the later sets, and most half and quarter walls. A
+ /// run built from such a row had holes. The columns a row leaves empty take the piece of
+ /// the nearest one it has, so every row builds whole walls. (The piece keeps the one role
+ /// it is listed under.)
+ ///
+ private static void FillWallRuns(HouseStyle style, ushort south = 0, ushort east = 0)
+ {
+ foreach (string[] run in new[] { _southRun, _eastRun })
+ {
+ // The middle piece first: it stands in best for a missing end, and an end for a missing middle.
+ ushort have = style.Get(run[1]) != 0 ? style.Get(run[1]) : style.Get(run[0]) != 0 ? style.Get(run[0]) : style.Get(run[2]);
+ if (have == 0)
+ {
+ have = run == _southRun ? south : east;
+ }
+ if (have == 0)
+ {
+ continue;
+ }
+
+ foreach (string column in run)
+ {
+ if (style.Get(column) == 0)
+ {
+ style.Add(column, have);
+ }
+ }
+ }
+ }
+
+ private static readonly string[] _wallFillerWords = { "Standard", "Walls", "Wall", "Set", "Style", "-" };
+
+ ///
+ /// The group and the row names of a walls.txt category. The table's comments name many
+ /// rows alike ("Carved Wood 1" four times: full, windowed, half and quarter walls) or only
+ /// by number ("Crystal Walls 2"). The group is the material: what the rows' names share,
+ /// without filler words and numbers. A row whose name is used twice, or is only numbered,
+ /// is named by what it holds instead: material + Walls, Window Walls, Half Walls or
+ /// Quarter Walls, by the height of its pieces. Other rows keep their comment.
+ ///
+ private static (string Group, List Names) WallNames(TileCategory category, HashSet used, bool byArt)
+ {
+ var raw = new List();
+ foreach (TileStyle row in category.Styles)
+ {
+ string name = (row.Name ?? string.Empty).Trim().TrimEnd('\\').Trim();
+ raw.Add(name);
+ }
+
+ // The material: the words every row starts with.
+ string[] first = raw.Count > 0 ? raw[0].Split(' ', System.StringSplitOptions.RemoveEmptyEntries) : System.Array.Empty();
+ int shared = first.Length;
+ foreach (string name in raw)
+ {
+ string[] words = name.Split(' ', System.StringSplitOptions.RemoveEmptyEntries);
+ int same = 0;
+ while (same < shared && same < words.Length && string.Equals(words[same], first[same], System.StringComparison.OrdinalIgnoreCase))
+ {
+ ++same;
+ }
+
+ shared = same;
+ }
+
+ // A category of two materials (Weathered Stone and Granite) shares no words: it goes by its first row.
+ bool oneMaterial = shared > 0;
+ var material = new List(first.Take(oneMaterial ? shared : first.Length));
+
+ // "Gargish Wall Set 2": the set's number is part of what it is, as there are three such categories.
+ string set = material.Count >= 3 && material[^2] == "Set" && int.TryParse(material[^1], out _) ? " Set " + material[^1] : string.Empty;
+ while (material.Count > 0 && (System.Array.IndexOf(_wallFillerWords, material[^1]) >= 0 || int.TryParse(material[^1], out _)))
+ {
+ material.RemoveAt(material.Count - 1);
+ }
+
+ string group = material.Count > 0 ? string.Join(" ", material) + set : (category.Name ?? string.Empty).Trim();
+ if (group.Length > 0)
+ {
+ group = char.ToUpperInvariant(group[0]) + group.Substring(1);
+ }
+
+ var names = new List();
+ for (int row = 0; row < raw.Count; ++row)
+ {
+ string name = raw[row];
+ string[] words = name.Split(' ', System.StringSplitOptions.RemoveEmptyEntries);
+ // In a category sorted by its art the comments say little: any numbered row of the material is renamed.
+ bool numbered = words.Length >= 2 && int.TryParse(words[^1], out _) &&
+ (words[^2] is "Walls" or "Wall" or "Set" || raw.Count(n => n == name) > 1 ||
+ (byArt && material.Count > 0 && name.StartsWith(string.Join(" ", material), System.StringComparison.OrdinalIgnoreCase)));
+ bool vague = raw.Count(n => string.Equals(n, name, System.StringComparison.OrdinalIgnoreCase)) > 1 || numbered ||
+ name.Contains(" - Style", System.StringComparison.Ordinal);
+ if (vague && oneMaterial && material.Count > 0)
+ {
+ string kindName = WallKind(category.Styles[row]);
+ name = kindName == "Window Walls" && group.Contains("Window", System.StringComparison.OrdinalIgnoreCase) ? group : group + " " + kindName;
+ }
+
+ // Two rows of one kind: the second and later ones are numbered.
+ string unique = name;
+ for (int n = 2; !used.Add(unique); ++n)
+ {
+ unique = $"{name} {n}";
+ }
+
+ names.Add(unique);
+ }
+
+ return (group, names);
+ }
+
+ /// What a wall row holds, by its pieces: their usual height, and whether most are windows.
+ private static string WallKind(TileStyle row)
+ {
+ var heights = new List();
+ int windows = 0;
+ foreach (TileSlot slot in row.Slots)
+ {
+ if (slot.IsEmpty || slot.TileId > ushort.MaxValue || !slot.IsValid)
+ {
+ continue;
+ }
+
+ heights.Add(Ultima.TileData.ItemTable[slot.TileId].Height);
+ if ((Ultima.TileData.ItemTable[slot.TileId].Flags & Ultima.TileFlag.Window) != 0)
+ {
+ ++windows;
+ }
+ }
+
+ if (heights.Count == 0)
+ {
+ return "Walls";
+ }
+
+ heights.Sort();
+ int height = heights[heights.Count / 2];
+ return height >= 15 ? (windows * 2 > heights.Count ? "Window Walls" : "Walls") : height >= 8 ? "Half Walls" : "Quarter Walls";
+ }
+
+ ///
+ /// One style from the rows of a roof.txt category, named after the category without its
+ /// row number ("Straw Roof 1" and "Straw Roof 2" are "Straw Roof"). The first row's pieces
+ /// keep their column headings; the pieces of a further row are extras of the set, kept
+ /// under "More" + heading so they still count as its roof pieces. Sets whose rows do not
+ /// follow the headings (ceramic, crystal, shadow) get their pieces from the style file,
+ /// which has labels for what the headings have no word for: Eave + side (a slope with
+ /// the roof's edge), Hip + corner (a hip line), HipEave + corner, NSEnd and EWEnd.
+ ///
+ private static HouseStyle RoofStyle(TileCategory category)
+ {
+ string name = category.Name ?? string.Empty;
+ if (name.EndsWith(" 1", System.StringComparison.Ordinal))
+ {
+ name = name.Substring(0, name.Length - 2);
+ }
+
+ var style = new HouseStyle(HousePartKind.Roof, name, name);
+ for (int row = 0; row < category.Styles.Count; ++row)
+ {
+ foreach (TileSlot slot in category.Styles[row].Slots)
+ {
+ if (slot.IsEmpty || slot.TileId > ushort.MaxValue || !slot.IsValid)
+ {
+ continue;
+ }
+
+ string label = row == 0 ? slot.Label : "More" + slot.Label;
+ if (style.Get(label) == 0)
+ {
+ style.Add(label, (ushort)slot.TileId);
+ }
+ }
+ }
+
+ return style;
+ }
+
+ /// How far apart two radar colours may be (RGB distance) and still count as one floor colour.
+ private const int _sameColour = 20;
+
+ ///
+ /// Splits a floor row into styles of one colour each, by the tiles' radar colours. Pieces keep
+ /// their column labels; a tile listed twice counts once. Each part is named after its tiles'
+ /// tiledata name, numbered where a row has several of the same, and grouped under the row's name.
+ ///
+ private static List SplitByColour(HouseStyle style)
+ {
+ var clusters = new List<(System.Drawing.Color Colour, List> Pieces)>();
+ var seen = new HashSet();
+ foreach (KeyValuePair piece in style.Slots)
+ {
+ if (!seen.Add(piece.Value))
+ {
+ continue;
+ }
+
+ System.Drawing.Color colour = Ultima.Helpers.HueHelpers.HueToColor(Ultima.RadarCol.GetItemColor(piece.Value));
+ int index = clusters.FindIndex(c =>
+ {
+ int dr = c.Colour.R - colour.R, dg = c.Colour.G - colour.G, db = c.Colour.B - colour.B;
+ return (dr * dr) + (dg * dg) + (db * db) <= _sameColour * _sameColour;
+ });
+ if (index < 0)
+ {
+ clusters.Add((colour, new List> { piece }));
+ }
+ else
+ {
+ clusters[index].Pieces.Add(piece);
+ }
+ }
+
+ if (clusters.Count <= 1)
+ {
+ return new List { style };
+ }
+
+ var names = new List();
+ foreach (var (_, pieces) in clusters)
+ {
+ string name = Ultima.TileData.ItemTable[pieces[0].Value].Name?.Trim();
+ if (string.IsNullOrEmpty(name) || name.StartsWith("Missing", System.StringComparison.OrdinalIgnoreCase))
+ {
+ name = style.Name;
+ }
+
+ names.Add(char.ToUpperInvariant(name[0]) + name.Substring(1));
+ }
+
+ var result = new List