diff --git a/Ultima/AnimationEdit.cs b/Ultima/AnimationEdit.cs index 227cbede..df87a6ac 100644 --- a/Ultima/AnimationEdit.cs +++ b/Ultima/AnimationEdit.cs @@ -255,27 +255,96 @@ public static bool IsActionDefined(int fileType, int body, int action) return valid && length >= 1; } - public static void LoadFromVD(int fileType, int body, BinaryReader bin) + /// + /// Number of actions in a body .vd of . That is the body's action count when a + /// .vd type exists for it (22, 13 or 35). Otherwise it is the body's whole idx block, so a 9-action sea + /// monster in a 22-action block goes out as a 22-action monster .vd and nothing is lost. + /// + public static int GetVdActionCount(int body, int fileType) { - AnimIdx[] cache = GetCache(fileType); - GetFileIndex(body, fileType, 0, 0, out FileIndex _, out int index); - int animLength = Animations.GetAnimLength(body, fileType) * 5; - var entries = new Entry3D[animLength]; + int animLength = Animations.GetAnimLength(body, fileType); + return GetVdType(animLength) >= 0 ? animLength : Animations.GetActionCapacity(body, fileType); + } - for (int i = 0; i < animLength; ++i) + /// + /// .vd header type for a body with actions: 0 = 22 (monster), + /// 1 = 13 (animal), 2 = 35 (human), or -1 when no type has that many. + /// + public static short GetVdType(int actionCount) + { + switch (actionCount) + { + case 22: return 0; + case 13: return 1; + case 35: return 2; + default: return -1; + } + } + + /// + /// Reads the index entries that follow the .vd header and checks that the + /// file really holds that many: every entry with data must point past the index. + /// + /// The file holds fewer entries than expected. + private static Entry3D[] ReadVdEntries(BinaryReader bin, int count) + { + long dataStart = bin.BaseStream.Position + (12L * count); + long fileLength = bin.BaseStream.Length; + if (dataStart > fileLength) + { + throw new InvalidDataException( + $"The file is too short for {count / 5} actions. It was made for a body with fewer actions. Nothing was imported."); + } + + var entries = new Entry3D[count]; + for (int i = 0; i < count; ++i) { entries[i].Lookup = bin.ReadInt32(); entries[i].Length = bin.ReadInt32(); entries[i].Extra = bin.ReadInt32(); } - for (int i = 0; i < entries.Length; ++i, ++index) + for (int i = 0; i < count; ++i) + { + Entry3D entry = entries[i]; + if (entry.Lookup > 0 && entry.Length > 0 && (entry.Lookup < dataStart || entry.Lookup >= fileLength)) + { + throw new InvalidDataException( + $"The file does not hold {count / 5} actions: action {i / 5}, direction {i % 5} points into the index. " + + "It was made for a body with fewer actions. Nothing was imported."); + } + } + + return entries; + } + + /// + /// Reads a body .vd, positioned after its 4-byte header, into . The file must + /// hold actions. Nothing changes if it can't be read. + /// + /// The file holds fewer entries than the body needs. + public static void LoadFromVD(int fileType, int body, BinaryReader bin) + { + AnimIdx[] cache = GetCache(fileType); + GetFileIndex(body, fileType, 0, 0, out FileIndex _, out int index); + Entry3D[] entries = ReadVdEntries(bin, GetVdActionCount(body, fileType) * 5); + + var loaded = new AnimIdx[entries.Length]; + for (int i = 0; i < entries.Length; ++i) { Entry3D entry = entries[i]; - if ((entry.Lookup > 0) && (entry.Lookup < bin.BaseStream.Length) && (entry.Length > 0)) + if ((entry.Lookup > 0) && (entry.Length > 0)) { bin.BaseStream.Seek(entry.Lookup, SeekOrigin.Begin); - cache[index] = new AnimIdx(bin, entry.Extra); + loaded[i] = new AnimIdx(bin, entry.Extra); + } + } + + for (int i = 0; i < entries.Length; ++i, ++index) + { + if (loaded[i] != null) + { + cache[index] = loaded[i]; } else { @@ -300,38 +369,76 @@ private static void EnsureFramesFit(AnimIdx anim, string where) } } - public static void ExportToVD(int fileType, int body, string file) + /// + /// Writes the body as a .vd file. A other than 1 resizes every frame + /// and its center in the file only; the loaded animation is left as it is. + /// + /// A frame does not fit its run headers. Nothing is written. + public static void ExportToVD(int fileType, int body, string file, double scale = 1.0) { AnimIdx[] cache = GetCache(fileType); GetFileIndex(body, fileType, 0, 0, out FileIndex fileIndex, out int index); - int bodyLength = Animations.GetAnimLength(body, fileType) * 5; - for (int i = 0; i < bodyLength && cache != null && index + i < cache.Length; ++i) + int animLength = GetVdActionCount(body, fileType); + var anims = new AnimIdx[animLength * 5]; + for (int i = 0; i < anims.Length; ++i) { - EnsureFramesFit(cache[index + i], $"Body {body}, action {i / 5}, direction {i % 5}"); + int slot = index + i; + AnimIdx anim = cache[slot] ?? (cache[slot] = new AnimIdx(slot, fileIndex)); + anims[i] = ScaleForExport(anim, scale); + EnsureFramesFit(anims[i], $"Body {body}, action {i / 5}, direction {i % 5}"); } + WriteBodyVD(file, GetVdType(animLength), anims); + } + + /// + /// Writes as a .vd in another body type's action layout. Action + /// t of the file holds action sourceActions[t] of the body, or nothing where that is -1. + /// A sea monster layout (9 actions) is written as a 22-action monster .vd with the rest left empty, + /// the way sea monster bodies are stored. + /// + /// A frame does not fit its run headers. Nothing is written. + public static void ExportRemappedToVD(int fileType, int body, MobType layout, IReadOnlyList sourceActions, string file, double scale = 1.0) + { + int layoutActions = MobTypes.GetActionCount(layout == MobType.Equipment ? MobType.Human : layout); + int vdActions = GetVdType(layoutActions) >= 0 ? layoutActions : 22; + + var anims = new AnimIdx[vdActions * 5]; + for (int target = 0; target < layoutActions && target < sourceActions.Count; ++target) + { + int source = sourceActions[target]; + if (source < 0 || !IsActionInRange(fileType, body, source)) + { + continue; + } + + for (int dir = 0; dir < 5; ++dir) + { + AnimIdx anim = ScaleForExport(GetAnimation(fileType, body, source, dir), scale); + EnsureFramesFit(anim, $"Body {body}, action {source}, direction {dir}"); + anims[(target * 5) + dir] = anim; + } + } + + WriteBodyVD(file, GetVdType(vdActions), anims); + } + + /// + /// Writes a body .vd: the header, one index entry per action and direction, then each animation. + /// A null animation gets an empty entry. + /// + private static void WriteBodyVD(string file, short vdType, AnimIdx[] anims) + { using (var fs = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Write)) using (var bin = new BinaryWriter(fs)) { bin.Write((short)6); - int animLength = Animations.GetAnimLength(body, fileType); - int currType = animLength == 22 ? 0 : animLength == 13 ? 1 : 2; - bin.Write((short)currType); + bin.Write(vdType); long indexPos = bin.BaseStream.Position; - long animPos = bin.BaseStream.Position + (12 * animLength * 5); - for (int i = index; i < index + (animLength * 5); i++) + long animPos = bin.BaseStream.Position + (12 * anims.Length); + foreach (AnimIdx anim in anims) { - AnimIdx anim; - if (cache != null) - { - anim = cache[i] != null ? cache[i] : cache[i] = new AnimIdx(i, fileIndex); - } - else - { - anim = cache[i] = new AnimIdx(i, fileIndex); - } - if (anim == null) { bin.BaseStream.Seek(indexPos, SeekOrigin.Begin); @@ -377,11 +484,14 @@ public static bool IsActionInRange(int fileType, int body, int action) /// /// Writes one action as a .vd file: the body .vd layout with 5 index entries, one per direction. /// - public static void ExportActionToVD(int fileType, int body, int action, string file) + /// A frame does not fit its run headers. Nothing is written. + public static void ExportActionToVD(int fileType, int body, int action, string file, double scale = 1.0) { + var anims = new AnimIdx[5]; for (int dir = 0; dir < 5; ++dir) { - EnsureFramesFit(GetAnimation(fileType, body, action, dir), $"Body {body}, action {action}, direction {dir}"); + anims[dir] = ScaleForExport(GetAnimation(fileType, body, action, dir), scale); + EnsureFramesFit(anims[dir], $"Body {body}, action {action}, direction {dir}"); } using (var fs = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Write)) @@ -393,30 +503,34 @@ public static void ExportActionToVD(int fileType, int body, int action, string f long animPos = bin.BaseStream.Position + (12 * 5); for (int dir = 0; dir < 5; ++dir) { - GetAnimation(fileType, body, action, dir).ExportToVD(bin, ref indexPos, ref animPos); + anims[dir].ExportToVD(bin, ref indexPos, ref animPos); } } } + private static AnimIdx ScaleForExport(AnimIdx anim, double scale) + { + if (anim == null || scale == 1.0) + { + return anim; + } + + return anim.ScaledCopy(scale); + } + /// /// Reads a single-action .vd, positioned after its 4-byte header, into the given action. /// Directions the file leaves empty are cleared. Nothing changes if the file can't be read. /// public static void LoadActionFromVD(int fileType, int body, int action, BinaryReader bin) { - var entries = new Entry3D[5]; - for (int dir = 0; dir < 5; ++dir) - { - entries[dir].Lookup = bin.ReadInt32(); - entries[dir].Length = bin.ReadInt32(); - entries[dir].Extra = bin.ReadInt32(); - } + Entry3D[] entries = ReadVdEntries(bin, 5); var loaded = new AnimIdx[5]; for (int dir = 0; dir < 5; ++dir) { Entry3D entry = entries[dir]; - if ((entry.Lookup > 0) && (entry.Lookup < bin.BaseStream.Length) && (entry.Length > 0)) + if ((entry.Lookup > 0) && (entry.Length > 0)) { bin.BaseStream.Seek(entry.Lookup, SeekOrigin.Begin); loaded[dir] = new AnimIdx(bin, entry.Extra); @@ -544,6 +658,11 @@ public sealed class AnimIdx public ushort[] Palette { get; private set; } public List Frames { get; private set; } + private AnimIdx() + { + Palette = new ushort[PaletteCapacity]; + } + public AnimIdx(int index, FileIndex fileIndex) { Palette = new ushort[PaletteCapacity]; @@ -1037,6 +1156,111 @@ public void CopyFrom(AnimIdx source) _idxExtra = source._idxExtra; } + /// + /// Width or height of a frame resized by , at least 1. + /// + public static int ScaledLength(int length, double scale) + { + return Math.Max(1, (int)Math.Round(length * scale)); + } + + /// + /// Center of a frame pixels high once it is resized by + /// to . The point the center marks, left edge plus X and bottom edge plus Y, + /// moves with the scale, so the feet stay where they were. + /// + public static Point ScaleCenter(Point center, int height, int scaledHeight, double scale) + { + return new Point( + (int)Math.Round(center.X * scale), + (int)Math.Round((center.Y + height) * scale) - scaledHeight); + } + + /// + /// A copy with every frame resized by . Pixels are picked by nearest + /// neighbour, so no colours outside the palette appear. Centers scale with the frame, measured + /// from the frame's bottom so the feet stay on the same point. + /// + public unsafe AnimIdx ScaledCopy(double scale) + { + if (!(scale > 0)) + { + throw new ArgumentOutOfRangeException(nameof(scale), scale, "Scale must be greater than zero."); + } + + var copy = new AnimIdx(); + Array.Copy(Palette, copy.Palette, PaletteCapacity); + copy._idxExtra = _idxExtra; + if (Frames == null) + { + return copy; + } + + copy.Frames = new List(Frames.Count); + Bitmap[] bits = GetFrames(); + try + { + for (int i = 0; i < Frames.Count; ++i) + { + FrameEdit frame = Frames[i]; + Bitmap source = bits?[i]; + if (source == null) + { + copy.Frames.Add(new FrameEdit(frame)); + continue; + } + + int width = ScaledLength(source.Width, scale); + int height = ScaledLength(source.Height, scale); + Point center = ScaleCenter(frame.Center, source.Height, height, scale); + int centerX = center.X; + int centerY = center.Y; + + using (var target = new Bitmap(width, height, PixelFormat.Format16bppArgb1555)) + { + BitmapData sd = source.LockBits(new Rectangle(0, 0, source.Width, source.Height), ImageLockMode.ReadOnly, PixelFormat.Format16bppArgb1555); + BitmapData td = target.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format16bppArgb1555); + try + { + var sp = (ushort*)sd.Scan0; + var tp = (ushort*)td.Scan0; + int sStride = sd.Stride >> 1; + int tStride = td.Stride >> 1; + for (int y = 0; y < height; ++y) + { + int sy = Math.Min(source.Height - 1, (int)(y / scale)); + ushort* sRow = sp + (sy * sStride); + ushort* tRow = tp + (y * tStride); + for (int x = 0; x < width; ++x) + { + tRow[x] = sRow[Math.Min(source.Width - 1, (int)(x / scale))]; + } + } + } + finally + { + target.UnlockBits(td); + source.UnlockBits(sd); + } + + copy.Frames.Add(new FrameEdit(target, copy.Palette, centerX, centerY)); + } + } + } + finally + { + if (bits != null) + { + foreach (Bitmap bit in bits) + { + bit?.Dispose(); + } + } + } + + return copy; + } + public void ExportPalette(string filename, int type) { switch (type) diff --git a/Ultima/MobActionMap.cs b/Ultima/MobActionMap.cs new file mode 100644 index 00000000..dc2598c7 --- /dev/null +++ b/Ultima/MobActionMap.cs @@ -0,0 +1,213 @@ +/*************************************************************************** + * + * $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 Ultima +{ + /// + /// What an action shows, independent of the body type's action layout. + /// + public enum ActionRole + { + None, + Walk, + Run, + Idle, + Fidget, + Alert, + Eat, + LieDown, + CombatIdle, + CombatAdvance, + Attack1, + Attack2, + Attack3, + AttackBow, + AttackCrossbow, + AttackThrow, + Punch, + Pillage, + Stomp, + Cast1, + Cast2, + Block, + GetHit, + GetHitInAir, + Die1, + Die2, + Fly, + TakeOff, + MountWalk, + MountRun, + MountIdle, + MountAttack, + Emote + } + + /// + /// Maps actions between the monster (22), sea monster (9), animal (13) and human (35) action layouts by + /// what each action shows, falling back to the closest action the other layout has (run to walk, a third + /// attack to the first, ...). Equipment uses the human layout. + /// + public static class MobActionMap + { + private static readonly ActionRole[] _monster = + { + ActionRole.Walk, ActionRole.Idle, ActionRole.Die1, ActionRole.Die2, ActionRole.Attack1, ActionRole.Attack2, + ActionRole.Attack3, ActionRole.AttackBow, ActionRole.AttackCrossbow, ActionRole.AttackThrow, ActionRole.GetHit, + ActionRole.Pillage, ActionRole.Stomp, ActionRole.Cast1, ActionRole.Cast2, ActionRole.Block, ActionRole.Block, + ActionRole.Idle, ActionRole.Fidget, ActionRole.Fly, ActionRole.TakeOff, ActionRole.GetHitInAir + }; + + private static readonly ActionRole[] _sea = + { + ActionRole.Walk, ActionRole.Run, ActionRole.Idle, ActionRole.Idle, ActionRole.Fidget, ActionRole.Attack1, + ActionRole.Attack2, ActionRole.GetHit, ActionRole.Die1 + }; + + private static readonly ActionRole[] _animal = + { + ActionRole.Walk, ActionRole.Run, ActionRole.Idle, ActionRole.Eat, ActionRole.Alert, ActionRole.Attack1, + ActionRole.Attack2, ActionRole.GetHit, ActionRole.Die1, ActionRole.Idle, ActionRole.Fidget, ActionRole.LieDown, + ActionRole.Die2 + }; + + private static readonly ActionRole[] _human = + { + ActionRole.Walk, ActionRole.Walk, ActionRole.Run, ActionRole.Run, ActionRole.Idle, ActionRole.Idle, + ActionRole.Fidget, ActionRole.CombatIdle, ActionRole.CombatIdle, ActionRole.Attack1, ActionRole.Attack2, + ActionRole.Attack3, ActionRole.Attack3, ActionRole.Attack1, ActionRole.Attack2, ActionRole.CombatAdvance, + ActionRole.Cast1, ActionRole.Cast2, ActionRole.AttackBow, ActionRole.AttackCrossbow, ActionRole.GetHit, + ActionRole.Die1, ActionRole.Die2, ActionRole.MountWalk, ActionRole.MountRun, ActionRole.MountIdle, + ActionRole.MountAttack, ActionRole.MountAttack, ActionRole.MountAttack, ActionRole.MountAttack, ActionRole.Block, + ActionRole.Punch, ActionRole.Emote, ActionRole.Emote, ActionRole.Eat + }; + + // Roles tried, in order, when a layout has no action with the role itself. A mount action falls back + // to what the mount does under the rider, so a rider's actions map onto the mount's. + private static readonly Dictionary _fallbacks = new() + { + [ActionRole.Run] = new[] { ActionRole.Walk }, + [ActionRole.Fidget] = new[] { ActionRole.Idle }, + [ActionRole.Alert] = new[] { ActionRole.Fidget, ActionRole.Idle }, + [ActionRole.Eat] = new[] { ActionRole.Fidget, ActionRole.Idle }, + [ActionRole.LieDown] = new[] { ActionRole.Idle }, + [ActionRole.CombatIdle] = new[] { ActionRole.Idle }, + [ActionRole.CombatAdvance] = new[] { ActionRole.Walk }, + [ActionRole.Attack2] = new[] { ActionRole.Attack1 }, + [ActionRole.Attack3] = new[] { ActionRole.Attack2, ActionRole.Attack1 }, + [ActionRole.AttackBow] = new[] { ActionRole.AttackThrow, ActionRole.Attack1 }, + [ActionRole.AttackCrossbow] = new[] { ActionRole.AttackBow, ActionRole.AttackThrow, ActionRole.Attack1 }, + [ActionRole.AttackThrow] = new[] { ActionRole.AttackBow, ActionRole.Attack1 }, + [ActionRole.Punch] = new[] { ActionRole.Attack1 }, + [ActionRole.Pillage] = new[] { ActionRole.Attack1 }, + [ActionRole.Stomp] = new[] { ActionRole.Attack2, ActionRole.Attack1 }, + [ActionRole.Cast1] = new[] { ActionRole.Cast2, ActionRole.Attack1 }, + [ActionRole.Cast2] = new[] { ActionRole.Cast1, ActionRole.Attack1 }, + [ActionRole.Block] = new[] { ActionRole.GetHit }, + [ActionRole.GetHitInAir] = new[] { ActionRole.GetHit }, + [ActionRole.Die2] = new[] { ActionRole.Die1 }, + [ActionRole.Fly] = new[] { ActionRole.Walk }, + [ActionRole.TakeOff] = new[] { ActionRole.Fly, ActionRole.Walk }, + [ActionRole.MountWalk] = new[] { ActionRole.Walk }, + [ActionRole.MountRun] = new[] { ActionRole.Run, ActionRole.Walk }, + [ActionRole.MountIdle] = new[] { ActionRole.Idle }, + [ActionRole.MountAttack] = new[] { ActionRole.MountIdle, ActionRole.Idle }, + [ActionRole.Emote] = new[] { ActionRole.Fidget, ActionRole.Idle }, + }; + + /// + /// The action roles of a layout, indexed by action. + /// + public static IReadOnlyList GetRoles(MobType type) + { + return type switch + { + MobType.Monster => _monster, + MobType.Sea => _sea, + MobType.Animal => _animal, + _ => _human + }; + } + + public static ActionRole GetRole(MobType type, int action) + { + IReadOnlyList roles = GetRoles(type); + return action >= 0 && action < roles.Count ? roles[action] : ActionRole.None; + } + + /// + /// The action of layout that best matches of layout + /// , or -1 when the target layout has nothing close. Within one layout an action + /// maps to itself. + /// + public static int MapAction(MobType from, int action, MobType to) + { + from = Normalize(from); + to = Normalize(to); + if (from == to) + { + return action >= 0 && action < GetRoles(to).Count ? action : -1; + } + + return FindAction(to, GetRole(from, action)); + } + + /// + /// The first action of layout with or, failing that, with + /// the nearest fallback role; -1 when there is none. + /// + public static int FindAction(MobType type, ActionRole role) + { + if (role == ActionRole.None) + { + return -1; + } + + IReadOnlyList roles = GetRoles(Normalize(type)); + int found = IndexOf(roles, role); + if (found >= 0 || !_fallbacks.TryGetValue(role, out ActionRole[] fallbacks)) + { + return found; + } + + foreach (ActionRole fallback in fallbacks) + { + found = IndexOf(roles, fallback); + if (found >= 0) + { + return found; + } + } + + return -1; + } + + private static MobType Normalize(MobType type) + { + return type == MobType.Equipment ? MobType.Human : type; + } + + private static int IndexOf(IReadOnlyList roles, ActionRole role) + { + for (int i = 0; i < roles.Count; ++i) + { + if (roles[i] == role) + { + return i; + } + } + + return -1; + } + } +} diff --git a/UoFiddler.Controls/Classes/FramesXml.cs b/UoFiddler.Controls/Classes/FramesXml.cs new file mode 100644 index 00000000..493d36c5 --- /dev/null +++ b/UoFiddler.Controls/Classes/FramesXml.cs @@ -0,0 +1,149 @@ +/*************************************************************************** + * + * $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.Drawing; +using System.Drawing.Imaging; +using System.Globalization; +using System.IO; +using System.Xml; +using System.Xml.Linq; + +namespace UoFiddler.Controls.Classes +{ + /// + /// One frame listed in a frames XML file. + /// + public sealed class FramesXmlFrame + { + public int Direction { get; set; } + public int Index { get; set; } + public Point Center { get; set; } + + /// Image file name, in the XML file's folder or its _frames folder. + public string File { get; set; } + } + + /// + /// Animation frames saved as one PNG per frame plus an XML file listing each frame's direction, index and + /// center. The images go in a {name}_frames folder next to {name}.xml. + /// + public static class FramesXml + { + public static string GetFramesFolder(string xmlFile) + { + return Path.Combine(Path.GetDirectoryName(xmlFile) ?? string.Empty, Path.GetFileNameWithoutExtension(xmlFile) + "_frames"); + } + + /// + /// Saves each frame as {direction}_{index}.png in the frames folder and lists them in . + /// + public static void Write(string xmlFile, IReadOnlyList<(int Direction, int Index, Point Center, Bitmap Image)> frames) + { + string framesFolder = GetFramesFolder(xmlFile); + Directory.CreateDirectory(framesFolder); + + var root = new XElement("Animation"); + foreach (var (direction, index, center, image) in frames) + { + string fileName = $"{direction}_{index:D2}.png"; + image.Save(Path.Combine(framesFolder, fileName), ImageFormat.Png); + root.Add(new XElement("Frame", + new XAttribute("dir", direction), + new XAttribute("index", index), + new XAttribute("centerX", center.X), + new XAttribute("centerY", center.Y), + new XAttribute("file", fileName))); + } + + new XDocument(root).Save(xmlFile); + } + + /// The file is not a frames XML file. + public static List Read(string xmlFile) + { + string name = Path.GetFileName(xmlFile); + XDocument document; + try + { + document = XDocument.Load(xmlFile); + } + catch (XmlException ex) + { + throw new InvalidDataException($"{name} is not a valid frames XML file: {ex.Message}", ex); + } + + if (document.Root?.Name.LocalName != "Animation") + { + throw new InvalidDataException($"{name} is not a frames XML file: the root element is not ."); + } + + var frames = new List(); + foreach (XElement element in document.Root.Elements("Frame")) + { + frames.Add(new FramesXmlFrame + { + Direction = ReadInt(element, "dir", name), + Index = ReadInt(element, "index", name), + Center = new Point(ReadInt(element, "centerX", name), ReadInt(element, "centerY", name)), + File = (string)element.Attribute("file") ?? throw new InvalidDataException($"{name}: a has no file attribute.") + }); + } + + return frames; + } + + /// + /// Path of a frame's image, or null if it is in neither the XML file's folder nor the frames folder. + /// Only the file name is used, so an XML file can't point outside those folders. + /// + public static string FindImage(string xmlFile, FramesXmlFrame frame) + { + string fileName = Path.GetFileName(frame.File); + if (string.IsNullOrEmpty(fileName)) + { + return null; + } + + string beside = Path.Combine(Path.GetDirectoryName(xmlFile) ?? string.Empty, fileName); + if (System.IO.File.Exists(beside)) + { + return beside; + } + + string inFolder = Path.Combine(GetFramesFolder(xmlFile), fileName); + return System.IO.File.Exists(inFolder) ? inFolder : null; + } + + /// + /// Loads an image as 32bpp ARGB without keeping the file locked. + /// + public static Bitmap LoadImage(string file) + { + using (var loaded = new Bitmap(file)) + { + return loaded.Clone(new Rectangle(0, 0, loaded.Width, loaded.Height), PixelFormat.Format32bppArgb); + } + } + + private static int ReadInt(XElement element, string attribute, string name) + { + string value = (string)element.Attribute(attribute); + if (!int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int result)) + { + throw new InvalidDataException($"{name}: a has no valid {attribute} attribute."); + } + + return result; + } + } +} diff --git a/UoFiddler.Controls/Classes/SpriteSheetPacker.cs b/UoFiddler.Controls/Classes/SpriteSheetPacker.cs index 4e8a2975..4dbf3e63 100644 --- a/UoFiddler.Controls/Classes/SpriteSheetPacker.cs +++ b/UoFiddler.Controls/Classes/SpriteSheetPacker.cs @@ -122,6 +122,40 @@ public static Bitmap Compose(int width, int height, IReadOnlyList images return sheet; } + /// + /// A 32bpp ARGB copy of resized by . Pixels are + /// picked by nearest neighbour, so no new colours appear. + /// + public static unsafe Bitmap ScaleNearest(Bitmap source, double scale) + { + int width = Ultima.AnimIdx.ScaledLength(source.Width, scale); + int height = Ultima.AnimIdx.ScaledLength(source.Height, scale); + var target = new Bitmap(width, height, PixelFormat.Format32bppArgb); + + BitmapData src = source.LockBits(new Rectangle(0, 0, source.Width, source.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + BitmapData dst = target.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + try + { + for (int y = 0; y < height; ++y) + { + int sy = Math.Min(source.Height - 1, (int)(y / scale)); + uint* srcLine = (uint*)((byte*)src.Scan0 + (sy * src.Stride)); + uint* dstLine = (uint*)((byte*)dst.Scan0 + (y * dst.Stride)); + for (int x = 0; x < width; ++x) + { + dstLine[x] = srcLine[Math.Min(source.Width - 1, (int)(x / scale))]; + } + } + } + finally + { + source.UnlockBits(src); + target.UnlockBits(dst); + } + + return target; + } + public static PackedMeta CreateMeta(string imageFile, Bitmap sheet) { return new PackedMeta diff --git a/UoFiddler.Controls/Forms/AnimationEditForm.Designer.cs b/UoFiddler.Controls/Forms/AnimationEditForm.Designer.cs index 153d748c..67059d36 100644 --- a/UoFiddler.Controls/Forms/AnimationEditForm.Designer.cs +++ b/UoFiddler.Controls/Forms/AnimationEditForm.Designer.cs @@ -31,7 +31,7 @@ private void InitializeComponent() components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AnimationEditForm)); MainSplitContainer = new System.Windows.Forms.SplitContainer(); - AnimationListTreeView = new System.Windows.Forms.TreeView(); + AnimationListTreeView = new UoFiddler.Controls.UserControls.VirtualTreeView(); ContextMenuStripTreeView = new System.Windows.Forms.ContextMenuStrip(components); removeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); extractImagesToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); @@ -43,6 +43,9 @@ private void InitializeComponent() fromvdToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); actionFromVdToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); actionToVdToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + tovdScaledToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + tovdRemappedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + actionToVdScaledToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); copyActionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); exportToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); tovdToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); @@ -103,6 +106,7 @@ private void InitializeComponent() ZoomLabel = new System.Windows.Forms.ToolStripLabel(); ZoomComboBox = new System.Windows.Forms.ToolStripComboBox(); zoomToolStripSeparator = new System.Windows.Forms.ToolStripSeparator(); + FrameSizeToolStripLabel = new System.Windows.Forms.ToolStripLabel(); toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); DrawFullRectangleToolStripButton = new System.Windows.Forms.ToolStripButton(); toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); @@ -135,6 +139,9 @@ private void InitializeComponent() SameCenterButton = new System.Windows.Forms.Button(); CenterXNumericUpDown = new System.Windows.Forms.NumericUpDown(); CenterYNumericUpDown = new System.Windows.Forms.NumericUpDown(); + RelativeCenterCheckBox = new System.Windows.Forms.CheckBox(); + CenterAllDirectionsCheckBox = new System.Windows.Forms.CheckBox(); + CenterAllActionsCheckBox = new System.Windows.Forms.CheckBox(); ReferencialPointGroupBox = new System.Windows.Forms.GroupBox(); ToolStripLockButton = new System.Windows.Forms.CheckBox(); RefYLabel = new System.Windows.Forms.Label(); @@ -240,6 +247,7 @@ private void InitializeComponent() AnimationListTreeView.Name = "AnimationListTreeView"; AnimationListTreeView.Size = new System.Drawing.Size(232, 796); AnimationListTreeView.TabIndex = 0; + AnimationListTreeView.BeforeExpand += OnBeforeExpandBody; AnimationListTreeView.AfterSelect += AfterSelectTreeView; // // ContextMenuStripTreeView @@ -328,7 +336,7 @@ private void InitializeComponent() // // exportToolStripMenuItem1 // - exportToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { tovdToolStripMenuItem, actionToVdToolStripMenuItem }); + exportToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { tovdToolStripMenuItem, actionToVdToolStripMenuItem, tovdScaledToolStripMenuItem, actionToVdScaledToolStripMenuItem, tovdRemappedToolStripMenuItem }); exportToolStripMenuItem1.Name = "exportToolStripMenuItem1"; exportToolStripMenuItem1.Size = new System.Drawing.Size(157, 22); exportToolStripMenuItem1.Text = "Export.."; @@ -347,6 +355,30 @@ private void InitializeComponent() actionToVdToolStripMenuItem.Text = "Action to .vd"; actionToVdToolStripMenuItem.ToolTipText = "Export the selected action, all directions, as a single-action .vd"; actionToVdToolStripMenuItem.Click += OnClickExportActionToVD; + // + // tovdScaledToolStripMenuItem + // + tovdScaledToolStripMenuItem.Name = "tovdScaledToolStripMenuItem"; + tovdScaledToolStripMenuItem.Size = new System.Drawing.Size(200, 22); + tovdScaledToolStripMenuItem.Text = "Body to .vd, scaled..."; + tovdScaledToolStripMenuItem.ToolTipText = "Export the body as a .vd with every frame and center resized"; + tovdScaledToolStripMenuItem.Click += OnClickExportScaledToVD; + // + // tovdRemappedToolStripMenuItem + // + tovdRemappedToolStripMenuItem.Name = "tovdRemappedToolStripMenuItem"; + tovdRemappedToolStripMenuItem.Size = new System.Drawing.Size(200, 22); + tovdRemappedToolStripMenuItem.Text = "Body to .vd, remapped..."; + tovdRemappedToolStripMenuItem.ToolTipText = "Export the body as a .vd of another body type, choosing which action goes in each slot"; + tovdRemappedToolStripMenuItem.Click += OnClickExportRemappedToVD; + // + // actionToVdScaledToolStripMenuItem + // + actionToVdScaledToolStripMenuItem.Name = "actionToVdScaledToolStripMenuItem"; + actionToVdScaledToolStripMenuItem.Size = new System.Drawing.Size(200, 22); + actionToVdScaledToolStripMenuItem.Text = "Action to .vd, scaled..."; + actionToVdScaledToolStripMenuItem.ToolTipText = "Export the selected action as a single-action .vd with every frame and center resized"; + actionToVdScaledToolStripMenuItem.Click += OnClickExportActionScaledToVD; // // AnimationFileToolStrip // @@ -926,7 +958,7 @@ private void InitializeComponent() AnimationEditToolStrip.Dock = System.Windows.Forms.DockStyle.Bottom; AnimationEditToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; AnimationEditToolStrip.ImageScalingSize = new System.Drawing.Size(20, 20); - AnimationEditToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { ZoomLabel, ZoomComboBox, zoomToolStripSeparator, toolStripSeparator7, DrawFullRectangleToolStripButton, toolStripSeparator5, DrawEmptyRectangleToolStripButton, toolStripSeparator6, DrawReferencialPointToolStripButton, toolStripSeparator10 }); + AnimationEditToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { ZoomLabel, ZoomComboBox, zoomToolStripSeparator, FrameSizeToolStripLabel, toolStripSeparator7, DrawFullRectangleToolStripButton, toolStripSeparator5, DrawEmptyRectangleToolStripButton, toolStripSeparator6, DrawReferencialPointToolStripButton, toolStripSeparator10 }); AnimationEditToolStrip.Location = new System.Drawing.Point(0, 702); AnimationEditToolStrip.Name = "AnimationEditToolStrip"; AnimationEditToolStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; @@ -952,6 +984,12 @@ private void InitializeComponent() // zoomToolStripSeparator.Name = "zoomToolStripSeparator"; zoomToolStripSeparator.Size = new System.Drawing.Size(6, 27); + // + // FrameSizeToolStripLabel + // + FrameSizeToolStripLabel.Name = "FrameSizeToolStripLabel"; + FrameSizeToolStripLabel.Size = new System.Drawing.Size(0, 24); + FrameSizeToolStripLabel.ToolTipText = "Frame size in pixels, shown while a frame rectangle is drawn"; // // toolStripSeparator7 // @@ -1247,12 +1285,15 @@ private void InitializeComponent() LocationCenterGroupBox.Controls.Add(SameCenterButton); LocationCenterGroupBox.Controls.Add(CenterXNumericUpDown); LocationCenterGroupBox.Controls.Add(CenterYNumericUpDown); + LocationCenterGroupBox.Controls.Add(RelativeCenterCheckBox); + LocationCenterGroupBox.Controls.Add(CenterAllDirectionsCheckBox); + LocationCenterGroupBox.Controls.Add(CenterAllActionsCheckBox); LocationCenterGroupBox.Dock = System.Windows.Forms.DockStyle.Top; LocationCenterGroupBox.Location = new System.Drawing.Point(0, 221); LocationCenterGroupBox.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); LocationCenterGroupBox.Name = "LocationCenterGroupBox"; LocationCenterGroupBox.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); - LocationCenterGroupBox.Size = new System.Drawing.Size(190, 89); + LocationCenterGroupBox.Size = new System.Drawing.Size(190, 158); LocationCenterGroupBox.TabIndex = 21; LocationCenterGroupBox.TabStop = false; LocationCenterGroupBox.Text = "Location Center"; @@ -1315,7 +1356,38 @@ private void InitializeComponent() CenterYNumericUpDown.TabIndex = 4; CenterYNumericUpDown.ValueChanged += OnCenterYValueChanged; CenterYNumericUpDown.KeyDown += TxtSendData_KeyDown; - // + // + // RelativeCenterCheckBox + // + RelativeCenterCheckBox.AutoSize = true; + RelativeCenterCheckBox.Location = new System.Drawing.Point(9, 84); + RelativeCenterCheckBox.Name = "RelativeCenterCheckBox"; + RelativeCenterCheckBox.Size = new System.Drawing.Size(68, 19); + RelativeCenterCheckBox.TabIndex = 19; + RelativeCenterCheckBox.Text = "Relative"; + RelativeCenterCheckBox.UseVisualStyleBackColor = true; + RelativeCenterCheckBox.CheckedChanged += RelativeCenterCheckBox_CheckedChanged; + // + // CenterAllDirectionsCheckBox + // + CenterAllDirectionsCheckBox.AutoSize = true; + CenterAllDirectionsCheckBox.Location = new System.Drawing.Point(9, 107); + CenterAllDirectionsCheckBox.Name = "CenterAllDirectionsCheckBox"; + CenterAllDirectionsCheckBox.Size = new System.Drawing.Size(97, 19); + CenterAllDirectionsCheckBox.TabIndex = 20; + CenterAllDirectionsCheckBox.Text = "All directions"; + CenterAllDirectionsCheckBox.UseVisualStyleBackColor = true; + // + // CenterAllActionsCheckBox + // + CenterAllActionsCheckBox.AutoSize = true; + CenterAllActionsCheckBox.Location = new System.Drawing.Point(9, 130); + CenterAllActionsCheckBox.Name = "CenterAllActionsCheckBox"; + CenterAllActionsCheckBox.Size = new System.Drawing.Size(83, 19); + CenterAllActionsCheckBox.TabIndex = 21; + CenterAllActionsCheckBox.Text = "All actions"; + CenterAllActionsCheckBox.UseVisualStyleBackColor = true; + // // ReferencialPointGroupBox // ReferencialPointGroupBox.Controls.Add(ToolStripLockButton); @@ -1702,6 +1774,9 @@ private void InitializeComponent() private System.Windows.Forms.ToolStripMenuItem fromvdToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem actionFromVdToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem actionToVdToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem tovdScaledToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem tovdRemappedToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem actionToVdScaledToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem copyActionToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem importToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem importToolStripMenuItem1; @@ -1741,7 +1816,7 @@ private void InitializeComponent() private System.Windows.Forms.ToolStripComboBox SelectFileToolStripComboBox; private System.Windows.Forms.ToolStripMenuItem tovdToolStripMenuItem; private System.Windows.Forms.TrackBar DirectionTrackBar; - private System.Windows.Forms.TreeView AnimationListTreeView; + private UoFiddler.Controls.UserControls.VirtualTreeView AnimationListTreeView; private System.Windows.Forms.StatusStrip StatusStrip; private System.Windows.Forms.ToolStripDropDownButton MiscToolStripButton; private System.Windows.Forms.ToolStripMenuItem SaveToolStripMenuItem; @@ -1773,6 +1848,9 @@ private void InitializeComponent() private System.Windows.Forms.Button SameCenterButton; private System.Windows.Forms.NumericUpDown CenterXNumericUpDown; private System.Windows.Forms.NumericUpDown CenterYNumericUpDown; + private System.Windows.Forms.CheckBox RelativeCenterCheckBox; + private System.Windows.Forms.CheckBox CenterAllDirectionsCheckBox; + private System.Windows.Forms.CheckBox CenterAllActionsCheckBox; private System.Windows.Forms.ToolStrip AnimationEditToolStrip; private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; private System.Windows.Forms.ToolStripButton DrawFullRectangleToolStripButton; @@ -1796,6 +1874,7 @@ private void InitializeComponent() private System.Windows.Forms.ToolStripLabel ZoomLabel; private System.Windows.Forms.ToolStripComboBox ZoomComboBox; private System.Windows.Forms.ToolStripSeparator zoomToolStripSeparator; + private System.Windows.Forms.ToolStripLabel FrameSizeToolStripLabel; private System.Windows.Forms.GroupBox SecondAnimGroupBox; private System.Windows.Forms.CheckBox SecondAnimCheckBox; private System.Windows.Forms.ComboBox SecondAnimFileComboBox; diff --git a/UoFiddler.Controls/Forms/AnimationEditForm.cs b/UoFiddler.Controls/Forms/AnimationEditForm.cs index 8b90b5b8..74104407 100644 --- a/UoFiddler.Controls/Forms/AnimationEditForm.cs +++ b/UoFiddler.Controls/Forms/AnimationEditForm.cs @@ -19,6 +19,7 @@ using System.Windows.Forms; using Ultima; using UoFiddler.Controls.Classes; +using UoFiddler.Controls.UserControls; namespace UoFiddler.Controls.Forms { @@ -36,9 +37,16 @@ public partial class AnimationEditForm : Form private static bool _drawEmpty; private static bool _drawFull; private static int _lastAddFilterIndex = 1; + private static int _lastExportScale = 100; private float _zoomFactor = 1.0f; + // Center editing: set while the center boxes are filled from code, and the + // box values last applied in relative mode. + private bool _updatingCenterUi; + private int _lastRelativeX; + private int _lastRelativeY; + // Second-animation overlay state private bool _secondAnimActivated; private int _secondAnimId; @@ -334,52 +342,29 @@ private void OnLoad(object sender, EventArgs e) if (_fileType != 0) { int count = Animations.GetAnimCount(_fileType); - TreeNode[] nodes = new TreeNode[count]; + VirtualTreeNode[] nodes = new VirtualTreeNode[count]; for (int i = 0; i < count; ++i) { MobType mobType = Animations.GetBodyMobType(i, _fileType); int animLength = Animations.GetAnimLength(i, _fileType); - string[] names = ResolveActionNames(mobType); - // mobtypes.txt is keyed by server body id; reverse-map for anim2..6. - int serverBody = _fileType == 1 ? i : BodyConverter.GetTrueBody(_fileType, i); - uint mobFlags = MobTypes.IsLoaded && serverBody >= 0 ? MobTypes.GetFlags(serverBody) : 0u; char typeTag = _typeTag[(int)mobType]; - TreeNode node = new TreeNode + VirtualTreeNode node = new VirtualTreeNode { Tag = i, Text = $"{typeTag}: {i} ({BodyConverter.GetTrueBody(_fileType, i)})" }; bool valid = false; - for (int j = 0; j < animLength; ++j) + for (int j = 0; j < animLength && !valid; ++j) { - string name = j < names.Length ? names[j] : $"Action{j}"; - TreeNode treeNode = new TreeNode - { - Tag = j, - Text = string.Format("{0:D2} {1}", j, name) - }; - - if (AnimationEdit.IsActionDefined(_fileType, i, j)) - { - valid = true; - } - else - { - treeNode.ForeColor = _invalidColor; - } - - if (MobTypes.IsLoaded && treeNode.ForeColor != _invalidColor) - { - string missing = GetMissingActionFlag(mobType, mobFlags, j); - if (missing != null) - { - treeNode.ForeColor = Color.Gray; - treeNode.ToolTipText = BuildDimmedTooltip(missing, mobFlags); - } - } + valid = AnimationEdit.IsActionDefined(_fileType, i, j); + } - node.Nodes.Add(treeNode); + // Action nodes are made when the body is first expanded: a native tree item costs + // a fraction of a millisecond to create and to destroy, and every body has 13-35 actions. + if (animLength > 0) + { + node.Nodes.Add(new VirtualTreeNode { Tag = _actionsPlaceholder }); } if (!valid) @@ -442,10 +427,105 @@ private void OnFilePathChangeEvent() OnLoad(null); } - private TreeNode GetNode(int tag) + // Tag of the single child a body node holds until its action nodes are made. + private static readonly object _actionsPlaceholder = new object(); + + private static bool HasActionNodes(VirtualTreeNode body) + { + return body.Nodes.Count > 0 && body.Nodes[0].Tag != _actionsPlaceholder; + } + + private void OnBeforeExpandBody(object sender, VirtualTreeNodeEventArgs e) + { + if (e.Node.Parent == null) + { + EnsureActionNodes(e.Node); + } + } + + /// + /// Replaces a body node's placeholder with its action nodes. + /// + private void EnsureActionNodes(VirtualTreeNode body) + { + if (body.Nodes.Count == 0 || HasActionNodes(body)) + { + return; + } + + int bodyId = (int)body.Tag; + int animLength = Animations.GetAnimLength(bodyId, _fileType); + string[] names = ResolveActionNames(Animations.GetBodyMobType(bodyId, _fileType)); + var actions = new VirtualTreeNode[animLength]; + for (int j = 0; j < animLength; ++j) + { + string name = j < names.Length ? names[j] : $"Action{j}"; + actions[j] = new VirtualTreeNode + { + Tag = j, + Text = string.Format("{0:D2} {1}", j, name) + }; + StyleActionNode(actions[j], bodyId, j); + } + + AnimationListTreeView.BeginUpdate(); + try + { + body.Nodes.Clear(); + body.Nodes.AddRange(actions); + } + finally + { + AnimationListTreeView.EndUpdate(); + } + } + + /// + /// Colours an action node: invalid when it has no frames, grey with a tooltip when mobtypes.txt + /// says the body lacks the action. + /// + private void StyleActionNode(VirtualTreeNode actionNode, int body, int action) + { + actionNode.ToolTipText = string.Empty; + if (!AnimationEdit.IsActionDefined(_fileType, body, action)) + { + actionNode.ForeColor = _invalidColor; + return; + } + + actionNode.ForeColor = Color.Empty; + if (!MobTypes.IsLoaded) + { + return; + } + + // mobtypes.txt is keyed by server body id; reverse-map for anim2..6. + int serverBody = _fileType == 1 ? body : BodyConverter.GetTrueBody(_fileType, body); + uint mobFlags = serverBody >= 0 ? MobTypes.GetFlags(serverBody) : 0u; + string missing = GetMissingActionFlag(Animations.GetBodyMobType(body, _fileType), mobFlags, action); + if (missing != null) + { + actionNode.ForeColor = Color.Gray; + actionNode.ToolTipText = BuildDimmedTooltip(missing, mobFlags); + } + } + + /// + /// Recolours one action node of from the animation data. A body whose actions + /// were never expanded has nothing to recolour; its nodes get the current state when they are made. + /// + private void RefreshActionNode(VirtualTreeNode body, int action) + { + if (HasActionNodes(body) && action >= 0 && action < body.Nodes.Count) + { + StyleActionNode(body.Nodes[action], (int)body.Tag, action); + } + } + + private VirtualTreeNode GetNode(int tag) { return _showOnlyValid - ? AnimationListTreeView.Nodes.Cast().FirstOrDefault(node => (int)node.Tag == tag) + ? AnimationListTreeView.Nodes.Cast().FirstOrDefault(node => (int)node.Tag == tag) : AnimationListTreeView.Nodes[tag]; } @@ -569,7 +649,7 @@ private void GalleryTileViewMouseDoubleClick(object sender, MouseEventArgs e) } int body = _galleryBodies[idx]; - TreeNode target = GetNode(body); + VirtualTreeNode target = GetNode(body); if (target == null) { return; @@ -580,7 +660,7 @@ private void GalleryTileViewMouseDoubleClick(object sender, MouseEventArgs e) AnimationListTreeView.Focus(); } - private void AfterSelectTreeView(object sender, TreeViewEventArgs e) + private void AfterSelectTreeView(object sender, VirtualTreeNodeEventArgs e) { if (AnimationListTreeView.SelectedNode == null) { @@ -647,8 +727,7 @@ private void AfterSelectTreeView(object sender, TreeViewEventArgs e) FramesTrackBar.Value = 0; FramesTrackBar.Invalidate(); - CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X; - CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y; + ShowFrameCenter(edit.Frames[FramesTrackBar.Value]); } //Soulblighter Modification else @@ -742,7 +821,16 @@ private void AnimationPictureBox_OnPaintFrame(object sender, PaintEventArgs e) AnimIdx edit = AnimationEdit.GetAnimation(_fileType, _currentBody, _currentAction, _currentDir); Bitmap[] currentBits = edit?.GetFrames(); - if (edit != null && currentBits?.Length > 0 && FramesTrackBar.Value < currentBits.Length && currentBits[FramesTrackBar.Value] != null) + bool hasFrame = edit != null && currentBits?.Length > 0 && FramesTrackBar.Value < currentBits.Length && currentBits[FramesTrackBar.Value] != null; + string frameSize = hasFrame && (_drawEmpty || _drawFull) + ? $"{currentBits[FramesTrackBar.Value].Width}x{currentBits[FramesTrackBar.Value].Height}" + : string.Empty; + if (FrameSizeToolStripLabel.Text != frameSize) + { + FrameSizeToolStripLabel.Text = frameSize; + } + + if (hasFrame) { int varW; int varH; @@ -840,6 +928,17 @@ private Color GetSecondAnimTintColor() } } + /// + /// The overlay body's action matching the primary body's current action, or -1 if it has none. + /// + private int GetSecondAnimAction() + { + MobType primary = Animations.GetBodyMobType(_currentBody, _fileType); + MobType overlay = Animations.GetBodyMobType(_secondAnimId, _secondAnimFileIndex); + int action = MobActionMap.MapAction(primary, _currentAction, overlay); + return action >= 0 && AnimationEdit.IsActionInRange(_secondAnimFileIndex, _secondAnimId, action) ? action : -1; + } + private void DrawSecondAnimation(Graphics graphics) { if (!_secondAnimActivated || _secondAnimFileIndex < 1 || _secondAnimFileIndex > 5) @@ -847,9 +946,16 @@ private void DrawSecondAnimation(Graphics graphics) return; } - // Action and direction follow the primary selection — equipment shares the human - // action set, so no action remapping is needed for the matching use case. - AnimIdx edit = AnimationEdit.GetAnimation(_secondAnimFileIndex, _secondAnimId, _currentAction, _currentDir); + // The direction follows the primary selection. The action does too when both bodies share an + // action layout (equipment uses the human one); otherwise the overlay plays its closest action, + // so a mount under a rider walks, runs and stands with the rider's horse actions. + int action = GetSecondAnimAction(); + if (action < 0) + { + return; + } + + AnimIdx edit = AnimationEdit.GetAnimation(_secondAnimFileIndex, _secondAnimId, action, _currentDir); Bitmap[] frames = edit?.GetFrames(); if (frames == null || frames.Length == 0) { @@ -938,7 +1044,8 @@ private void UpdateSecondAnimWarning() int primaryCount = FramesTrackBar.Maximum + 1; int overlayCount = 0; - AnimIdx overlay = AnimationEdit.GetAnimation(_secondAnimFileIndex, _secondAnimId, _currentAction, _currentDir); + int action = GetSecondAnimAction(); + AnimIdx overlay = action < 0 ? null : AnimationEdit.GetAnimation(_secondAnimFileIndex, _secondAnimId, action, _currentDir); Bitmap[] frames = overlay?.GetFrames(); if (frames != null) { @@ -1043,92 +1150,206 @@ private void OnFrameCountBarChanged(object sender, EventArgs e) return; } + ShowFrameCenter(GetCurrentFrame()); + + AnimationPictureBox.Invalidate(); + } + //End of Soulblighter Modification + + private FrameEdit GetCurrentFrame() + { + if (_fileType == 0) + { + return null; + } + AnimIdx edit = AnimationEdit.GetAnimation(_fileType, _currentBody, _currentAction, _currentDir); - if (edit != null && edit.Frames.Count > FramesTrackBar.Value) + if (edit?.Frames == null || FramesTrackBar.Value >= edit.Frames.Count) { - CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X; - CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y; + return null; } - AnimationPictureBox.Invalidate(); + return edit.Frames[FramesTrackBar.Value]; } - //End of Soulblighter Modification - private void OnCenterXValueChanged(object sender, EventArgs e) + /// + /// Shows the frame's center in the center boxes. In relative mode the boxes hold the + /// offset applied so far, so they are left alone. + /// + private void ShowFrameCenter(FrameEdit frame) + { + if (frame == null || RelativeCenterCheckBox.Checked) + { + return; + } + + SetCenterBoxes(frame.Center.X, frame.Center.Y); + } + + private void SetCenterBoxes(int x, int y) { + _updatingCenterUi = true; try { - if (_fileType == 0) + CenterXNumericUpDown.Value = x; + CenterYNumericUpDown.Value = y; + } + finally + { + _updatingCenterUi = false; + } + } + + private void OnCenterXValueChanged(object sender, EventArgs e) + { + OnCenterValueChanged(true); + } + + private void OnCenterYValueChanged(object sender, EventArgs e) + { + OnCenterValueChanged(false); + } + + private void OnCenterValueChanged(bool xAxis) + { + if (_updatingCenterUi || _fileType == 0) + { + return; + } + + int value = (int)(xAxis ? CenterXNumericUpDown.Value : CenterYNumericUpDown.Value); + + if (RelativeCenterCheckBox.Checked) + { + int delta = value - (xAxis ? _lastRelativeX : _lastRelativeY); + if (delta == 0) { return; } - AnimIdx edit = AnimationEdit.GetAnimation(_fileType, _currentBody, _currentAction, _currentDir); - if (edit == null || edit.Frames.Count < FramesTrackBar.Value) + bool moved = ApplyCenterChange(center => xAxis + ? new Point(center.X + delta, center.Y) + : new Point(center.X, center.Y + delta)); + + if (!moved) { - return; + SetCenterBoxes(_lastRelativeX, _lastRelativeY); } - - FrameEdit frame = edit.Frames[FramesTrackBar.Value]; - if (CenterXNumericUpDown.Value == frame.Center.X) + else if (xAxis) { - return; + _lastRelativeX = value; } - - if (!frame.CanCenterAt((int)CenterXNumericUpDown.Value, frame.Center.Y)) + else { - ShowCenterOutOfRange((int)CenterXNumericUpDown.Value, frame.Center.Y); - CenterXNumericUpDown.Value = frame.Center.X; - return; + _lastRelativeY = value; } - frame.ChangeCenter((int)CenterXNumericUpDown.Value, frame.Center.Y); - Options.ChangedUltimaClass["Animations"] = true; - AnimationPictureBox.Invalidate(); + return; } - catch (NullReferenceException) + + bool changed = ApplyCenterChange(center => xAxis + ? new Point(value, center.Y) + : new Point(center.X, value)); + + if (!changed) { - // TODO: add logging or fix? - // ignored + ShowFrameCenter(GetCurrentFrame()); } } - private void OnCenterYValueChanged(object sender, EventArgs e) + /// + /// Moves the center of every frame in the chosen scope: the current frame, all frames of + /// the action in all directions, or all frames of every action. Nothing changes if any + /// frame can't take its new center. + /// + private bool ApplyCenterChange(Func move) { - try + var changes = new List<(FrameEdit Frame, Point Center)>(); + foreach (FrameEdit frame in GetCenterTargets()) { - if (_fileType == 0) + Point center = move(frame.Center); + if (center == frame.Center) { - return; + continue; } - AnimIdx edit = AnimationEdit.GetAnimation(_fileType, _currentBody, _currentAction, _currentDir); - if (edit == null || edit.Frames.Count < FramesTrackBar.Value) + if (!frame.CanCenterAt(center.X, center.Y)) { - return; + ShowCenterOutOfRange(center.X, center.Y); + return false; } - FrameEdit frame = edit.Frames[FramesTrackBar.Value]; - if (CenterYNumericUpDown.Value == frame.Center.Y) + changes.Add((frame, center)); + } + + foreach ((FrameEdit frame, Point center) in changes) + { + frame.ChangeCenter(center.X, center.Y); + } + + if (changes.Count > 0) + { + Options.ChangedUltimaClass["Animations"] = true; + } + + AnimationPictureBox.Invalidate(); + return true; + } + + private IEnumerable GetCenterTargets() + { + bool allActions = CenterAllActionsCheckBox.Checked; + if (!allActions && !CenterAllDirectionsCheckBox.Checked) + { + FrameEdit current = GetCurrentFrame(); + if (current != null) { - return; + yield return current; } - if (!frame.CanCenterAt(frame.Center.X, (int)CenterYNumericUpDown.Value)) + yield break; + } + + int firstAction = allActions ? 0 : _currentAction; + int lastAction = allActions ? Animations.GetAnimLength(_currentBody, _fileType) - 1 : _currentAction; + for (int action = firstAction; action <= lastAction; ++action) + { + if (!AnimationEdit.IsActionInRange(_fileType, _currentBody, action)) { - ShowCenterOutOfRange(frame.Center.X, (int)CenterYNumericUpDown.Value); - CenterYNumericUpDown.Value = frame.Center.Y; - return; + continue; } - frame.ChangeCenter(frame.Center.X, (int)CenterYNumericUpDown.Value); - Options.ChangedUltimaClass["Animations"] = true; - AnimationPictureBox.Invalidate(); + for (int dir = 0; dir < 5; ++dir) + { + AnimIdx edit = AnimationEdit.GetAnimation(_fileType, _currentBody, action, dir); + if (edit?.Frames == null) + { + continue; + } + + foreach (FrameEdit frame in edit.Frames) + { + yield return frame; + } + } } - catch (NullReferenceException) + } + + private void RelativeCenterCheckBox_CheckedChanged(object sender, EventArgs e) + { + _lastRelativeX = 0; + _lastRelativeY = 0; + + // Same Center reads absolute values from the boxes, which hold an offset in relative mode. + SameCenterButton.Enabled = !RelativeCenterCheckBox.Checked && !AnimationTimer.Enabled; + + if (RelativeCenterCheckBox.Checked) { - // TODO: add logging or fix? - // ignored + SetCenterBoxes(0, 0); + } + else + { + ShowFrameCenter(GetCurrentFrame()); } } @@ -1272,15 +1493,18 @@ private void OnClickRemoveAction(object sender, EventArgs e) return; } - AnimationListTreeView.SelectedNode.ForeColor = _invalidColor; - for (int i = 0; i < AnimationListTreeView.SelectedNode.Nodes.Count; ++i) + VirtualTreeNode bodyNode = AnimationListTreeView.SelectedNode; + bodyNode.ForeColor = _invalidColor; + int actionCount = Animations.GetAnimLength(_currentBody, _fileType); + for (int i = 0; i < actionCount; ++i) { - AnimationListTreeView.SelectedNode.Nodes[i].ForeColor = _invalidColor; for (int d = 0; d < 5; ++d) { AnimIdx edit = AnimationEdit.GetAnimation(_fileType, _currentBody, i, d); edit?.ClearFrames(); } + + RefreshActionNode(bodyNode, i); } if (_showOnlyValid) @@ -1306,9 +1530,9 @@ private void OnClickRemoveAction(object sender, EventArgs e) edit?.ClearFrames(); } - AnimationListTreeView.SelectedNode.Parent.Nodes[_currentAction].ForeColor = _invalidColor; + RefreshActionNode(AnimationListTreeView.SelectedNode.Parent, _currentAction); bool valid = false; - foreach (TreeNode node in AnimationListTreeView.SelectedNode.Parent.Nodes) + foreach (VirtualTreeNode node in AnimationListTreeView.SelectedNode.Parent.Nodes) { if (node.ForeColor == _invalidColor) { @@ -1490,8 +1714,7 @@ private void OnClickAdd(object sender, EventArgs e) SetPaletteBox(); - CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X; - CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y; + ShowFrameCenter(edit.Frames[FramesTrackBar.Value]); Options.ChangedUltimaClass["Animations"] = true; } @@ -1500,11 +1723,11 @@ private void OnClickAdd(object sender, EventArgs e) { edit.AddFrame(bitmap); - TreeNode node = GetNode(_currentBody); + VirtualTreeNode node = GetNode(_currentBody); if (node != null) { node.ForeColor = Color.Empty; - node.Nodes[_currentAction].ForeColor = Color.Empty; + RefreshActionNode(node, _currentAction); } int i = edit.Frames.Count - 1; @@ -1530,8 +1753,7 @@ private void OnClickAdd(object sender, EventArgs e) FramesListView.TileSize = new Size(width + 5, height + 5); FramesTrackBar.Maximum = i; - CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X; - CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y; + ShowFrameCenter(edit.Frames[FramesTrackBar.Value]); Options.ChangedUltimaClass["Animations"] = true; } @@ -1568,11 +1790,11 @@ private void AddImageAtCertainIndex(int frameCount, Bitmap[] bitBmp, Bitmap bmp, for (int index = 0; index < frameCount; index++) { edit.AddFrame(bitBmp[index], bitBmp[index].Width / 2); - TreeNode node = GetNode(_currentBody); + VirtualTreeNode node = GetNode(_currentBody); if (node != null) { node.ForeColor = Color.Empty; - node.Nodes[_currentAction].ForeColor = Color.Empty; + RefreshActionNode(node, _currentAction); } int i = edit.Frames.Count - 1; @@ -1724,17 +1946,15 @@ private void OnClickImportFromVD(object sender, EventArgs e) int animLength = Animations.GetAnimLength(_currentBody, _fileType); // .vd file format: animType 0 = 22-action (monster), 1 = 13-action (animal), - // 2 = 35-action (human). Other lengths can't be represented; reject. - int currentType; - switch (animLength) - { - case 22: currentType = 0; break; - case 13: currentType = 1; break; - case 35: currentType = 2; break; - default: - MessageBox.Show($"Body action length {animLength} cannot be imported as .vd palette.", - "Import", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); - return; + // 2 = 35-action (human). Bodies with another count (9-action sea monsters) + // use their whole idx block, as the export writes them. + int vdActionCount = AnimationEdit.GetVdActionCount(_currentBody, _fileType); + int currentType = AnimationEdit.GetVdType(vdActionCount); + if (currentType < 0) + { + MessageBox.Show($"A body with {vdActionCount} actions can't be imported from a .vd.", + "Import", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); + return; } using (FileStream fs = new FileStream(dialog.FileName, FileMode.Open, FileAccess.Read, FileShare.Read)) @@ -1763,25 +1983,28 @@ private void OnClickImportFromVD(object sender, EventArgs e) MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); return; } - AnimationEdit.LoadFromVD(_fileType, _currentBody, bin); + + try + { + AnimationEdit.LoadFromVD(_fileType, _currentBody, bin); + } + catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is ArgumentException || ex is OverflowException) + { + MessageBox.Show($"Could not read {Path.GetFileName(dialog.FileName)}: {ex.Message}", "Import", + MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } } } bool valid = false; - TreeNode node = GetNode(_currentBody); + VirtualTreeNode node = GetNode(_currentBody); if (node != null) { for (int j = 0; j < animLength; ++j) { - if (AnimationEdit.IsActionDefined(_fileType, _currentBody, j)) - { - node.Nodes[j].ForeColor = Color.Empty; - valid = true; - } - else - { - node.Nodes[j].ForeColor = _invalidColor; - } + valid |= AnimationEdit.IsActionDefined(_fileType, _currentBody, j); + RefreshActionNode(node, j); } node.ForeColor = valid ? Color.Empty : _invalidColor; } @@ -1795,15 +2018,61 @@ private void OnClickImportFromVD(object sender, EventArgs e) } private void OnClickExportToVD(object sender, EventArgs e) + { + ExportBodyToVD(100); + } + + private void OnClickExportScaledToVD(object sender, EventArgs e) + { + if (_fileType != 0 && TryAskExportScale(out int percent)) + { + ExportBodyToVD(percent); + } + } + + private void ExportBodyToVD(int percent) { if (_fileType == 0) { return; } - string path = Options.OutputPath; - string fileName = Path.Combine(path, $"anim{_fileType}_{Utils.FormatExportId(_currentBody)}.vd"); - if (!TryRunAnimationWrite(() => AnimationEdit.ExportToVD(_fileType, _currentBody, fileName), "Export")) + string fileName = Path.Combine(Options.OutputPath, $"anim{_fileType}_{Utils.FormatExportId(_currentBody)}{ScaleSuffix(percent)}.vd"); + if (!TryRunAnimationWrite(() => AnimationEdit.ExportToVD(_fileType, _currentBody, fileName, percent / 100.0), "Export")) + { + return; + } + + FileSavedDialog.Show(FindForm(), Options.OutputPath, "Animation saved successfully."); + } + + private void OnClickExportRemappedToVD(object sender, EventArgs e) + { + if (_fileType == 0) + { + return; + } + + int body = _currentBody; + MobType sourceType = Animations.GetBodyMobType(body, _fileType); + var hasFrames = new bool[Animations.GetAnimLength(body, _fileType)]; + for (int action = 0; action < hasFrames.Length; ++action) + { + hasFrames[action] = AnimationEdit.IsActionDefined(_fileType, body, action); + } + + using var form = new VdRemapForm(body, sourceType, hasFrames, ResolveActionNames); + if (form.ShowDialog(this) != DialogResult.OK) + { + return; + } + + MobType layout = form.TargetLayout; + int[] sourceActions = form.SourceActions; + int percent = form.ScalePercent; + string fileName = Path.Combine(Options.OutputPath, + $"anim{_fileType}_{Utils.FormatExportId(body)}_as_{layout.ToString().ToLowerInvariant()}{ScaleSuffix(percent)}.vd"); + if (!TryRunAnimationWrite(() => AnimationEdit.ExportRemappedToVD(_fileType, body, layout, sourceActions, fileName, percent / 100.0), "Export")) { return; } @@ -1811,17 +2080,65 @@ private void OnClickExportToVD(object sender, EventArgs e) FileSavedDialog.Show(FindForm(), Options.OutputPath, "Animation saved successfully."); } + private static string ScaleSuffix(int percent) + { + return percent == 100 ? string.Empty : $"_scale{percent}"; + } + + /// + /// Asks for the size of exported frames, in percent of the original. + /// + private bool TryAskExportScale(out int percent) + { + using var dialog = new Form + { + Text = "Export scaled", + ClientSize = new Size(260, 84), + FormBorderStyle = FormBorderStyle.FixedDialog, + StartPosition = FormStartPosition.CenterParent, + MaximizeBox = false, + MinimizeBox = false, + ShowInTaskbar = false, + }; + var label = new Label { Text = "Frame size (%):", AutoSize = true, Location = new Point(12, 16) }; + var scale = new NumericUpDown + { + Minimum = 10, + Maximum = 400, + Increment = 10, + Value = _lastExportScale, + Location = new Point(130, 12), + Width = 70, + }; + var ok = new Button { Text = "Export", DialogResult = DialogResult.OK, Location = new Point(92, 48) }; + var cancel = new Button { Text = "Cancel", DialogResult = DialogResult.Cancel, Location = new Point(173, 48) }; + dialog.Controls.AddRange(new Control[] { label, scale, ok, cancel }); + dialog.AcceptButton = ok; + dialog.CancelButton = cancel; + + percent = 100; + if (dialog.ShowDialog(this) != DialogResult.OK) + { + return false; + } + + percent = (int)scale.Value; + _lastExportScale = percent; + return true; + } + private void OnTreeViewContextMenuOpening(object sender, System.ComponentModel.CancelEventArgs e) { bool actionSelected = _fileType != 0 && TryGetSelectedAction(out _, out _); copyActionToolStripMenuItem.Enabled = actionSelected; actionFromVdToolStripMenuItem.Enabled = actionSelected; actionToVdToolStripMenuItem.Enabled = actionSelected; + actionToVdScaledToolStripMenuItem.Enabled = actionSelected; } private bool TryGetSelectedAction(out int body, out int action) { - TreeNode node = AnimationListTreeView.SelectedNode; + VirtualTreeNode node = AnimationListTreeView.SelectedNode; if (node?.Parent == null) { body = -1; @@ -1835,14 +2152,27 @@ private bool TryGetSelectedAction(out int body, out int action) } private void OnClickExportActionToVD(object sender, EventArgs e) + { + ExportActionToVD(100); + } + + private void OnClickExportActionScaledToVD(object sender, EventArgs e) + { + if (_fileType != 0 && TryGetSelectedAction(out _, out _) && TryAskExportScale(out int percent)) + { + ExportActionToVD(percent); + } + } + + private void ExportActionToVD(int percent) { if (_fileType == 0 || !TryGetSelectedAction(out int body, out int action)) { return; } - string fileName = Path.Combine(Options.OutputPath, $"anim{_fileType}_{Utils.FormatExportId(body)}_action{action}.vd"); - if (!TryRunAnimationWrite(() => AnimationEdit.ExportActionToVD(_fileType, body, action, fileName), "Export")) + string fileName = Path.Combine(Options.OutputPath, $"anim{_fileType}_{Utils.FormatExportId(body)}_action{action}{ScaleSuffix(percent)}.vd"); + if (!TryRunAnimationWrite(() => AnimationEdit.ExportActionToVD(_fileType, body, action, fileName, percent / 100.0), "Export")) { return; } @@ -1897,7 +2227,7 @@ private void OnClickImportActionFromVD(object sender, EventArgs e) { AnimationEdit.LoadActionFromVD(_fileType, body, action, bin); } - catch (Exception ex) when (ex is IOException || ex is ArgumentException || ex is OverflowException) + catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is ArgumentException || ex is OverflowException) { MessageBox.Show($"Could not read {Path.GetFileName(dialog.FileName)}: {ex.Message}", "Import", MessageBoxButtons.OK, MessageBoxIcon.Warning); @@ -1938,8 +2268,8 @@ private void OnClickCopyAction(object sender, EventArgs e) /// private void UpdateBodyNode(int body) { - TreeNode node = _showOnlyValid - ? AnimationListTreeView.Nodes.Cast().FirstOrDefault(n => (int)n.Tag == body) + VirtualTreeNode node = _showOnlyValid + ? AnimationListTreeView.Nodes.Cast().FirstOrDefault(n => (int)n.Tag == body) : body < AnimationListTreeView.Nodes.Count ? AnimationListTreeView.Nodes[body] : null; if (node == null) { @@ -1947,20 +2277,11 @@ private void UpdateBodyNode(int body) } bool valid = false; - foreach (TreeNode child in node.Nodes) + int animLength = Animations.GetAnimLength(body, _fileType); + for (int action = 0; action < animLength; ++action) { - if (AnimationEdit.IsActionDefined(_fileType, body, (int)child.Tag)) - { - valid = true; - if (child.ForeColor == _invalidColor) - { - child.ForeColor = Color.Empty; - } - } - else - { - child.ForeColor = _invalidColor; - } + valid |= AnimationEdit.IsActionDefined(_fileType, body, action); + RefreshActionNode(node, action); } node.ForeColor = valid ? Color.Empty : _invalidColor; @@ -2320,11 +2641,11 @@ private bool ReplaceActionFromImages(string[] files) } } - TreeNode node = GetNode(_currentBody); + VirtualTreeNode node = GetNode(_currentBody); if (node != null) { node.ForeColor = Color.Empty; - node.Nodes[_currentAction].ForeColor = Color.Empty; + RefreshActionNode(node, _currentAction); } Options.ChangedUltimaClass["Animations"] = true; @@ -2370,8 +2691,7 @@ private void AddFilesAllDirections(OpenFileDialog dialog) FramesListView.Invalidate(); - CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X; - CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y; + ShowFrameCenter(edit.Frames[FramesTrackBar.Value]); Options.ChangedUltimaClass["Animations"] = true; } @@ -2428,7 +2748,7 @@ private void ToolStripButtonPlayAnimation_Click(object sender, EventArgs e) { AnimationTimer.Enabled = false; FramesTrackBar.Enabled = true; - SameCenterButton.Enabled = true; + SameCenterButton.Enabled = !RelativeCenterCheckBox.Checked; CenterXNumericUpDown.Enabled = true; CenterYNumericUpDown.Enabled = true; @@ -2921,11 +3241,11 @@ private void AddAnimationX1(Color customConvert, Bitmap bmp) for (int index = 0; index < frameCount; index++) { edit.AddFrame(bitBmp[index], bitBmp[index].Width/2); - TreeNode node = GetNode(_currentBody); + VirtualTreeNode node = GetNode(_currentBody); if (node != null) { node.ForeColor = Color.Empty; - node.Nodes[_currentAction].ForeColor = Color.Empty; + RefreshActionNode(node, _currentAction); } int i = edit.Frames.Count - 1; @@ -2960,8 +3280,7 @@ private void AddAnimationX1(Color customConvert, Bitmap bmp) ProgressBar.Invalidate(); SetPaletteBox(); FramesListView.Invalidate(); - CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X; - CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y; + ShowFrameCenter(edit.Frames[FramesTrackBar.Value]); Options.ChangedUltimaClass["Animations"] = true; } @@ -3352,8 +3671,7 @@ private void AddDirectionsAddWithCanvasUniqueImageToolStripMenuItem_Click(object SetPaletteBox(); FramesListView.Invalidate(); - CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X; - CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y; + ShowFrameCenter(edit.Frames[FramesTrackBar.Value]); Options.ChangedUltimaClass["Animations"] = true; } @@ -3384,11 +3702,11 @@ private AnimIdx Cv5AnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimens for (int index = frameCount / 8 * 4; index < frameCount / 8 * 5; index++) { edit.AddFrame(bitBmp[index], bitBmp[index].Width/2); - TreeNode node = GetNode(_currentBody); + VirtualTreeNode node = GetNode(_currentBody); if (node != null) { node.ForeColor = Color.Empty; - node.Nodes[_currentAction].ForeColor = Color.Empty; + RefreshActionNode(node, _currentAction); } int i = edit.Frames.Count - 1; @@ -3431,11 +3749,11 @@ private AnimIdx Cv5AnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimens for (int index = 0; index < frameCount / 8; index++) { edit.AddFrame(bitBmp[index], bitBmp[index].Width/2); - TreeNode node = GetNode(_currentBody); + VirtualTreeNode node = GetNode(_currentBody); if (node != null) { node.ForeColor = Color.Empty; - node.Nodes[_currentAction].ForeColor = Color.Empty; + RefreshActionNode(node, _currentAction); } int i = edit.Frames.Count - 1; @@ -3478,11 +3796,11 @@ private AnimIdx Cv5AnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimens for (int index = frameCount / 8 * 5; index < frameCount / 8 * 6; index++) { edit.AddFrame(bitBmp[index], bitBmp[index].Width/2); - TreeNode node = GetNode(_currentBody); + VirtualTreeNode node = GetNode(_currentBody); if (node != null) { node.ForeColor = Color.Empty; - node.Nodes[_currentAction].ForeColor = Color.Empty; + RefreshActionNode(node, _currentAction); } int i = edit.Frames.Count - 1; @@ -3525,11 +3843,11 @@ private AnimIdx Cv5AnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimens for (int index = frameCount / 8 * 1; index < frameCount / 8 * 2; index++) { edit.AddFrame(bitBmp[index], bitBmp[index].Width/2); - TreeNode node = GetNode(_currentBody); + VirtualTreeNode node = GetNode(_currentBody); if (node != null) { node.ForeColor = Color.Empty; - node.Nodes[_currentAction].ForeColor = Color.Empty; + RefreshActionNode(node, _currentAction); } int i = edit.Frames.Count - 1; @@ -3572,11 +3890,11 @@ private AnimIdx Cv5AnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimens for (int index = frameCount / 8 * 6; index < frameCount / 8 * 7; index++) { edit.AddFrame(bitBmp[index], bitBmp[index].Width/2); - TreeNode node = GetNode(_currentBody); + VirtualTreeNode node = GetNode(_currentBody); if (node != null) { node.ForeColor = Color.Empty; - node.Nodes[_currentAction].ForeColor = Color.Empty; + RefreshActionNode(node, _currentAction); } int i = edit.Frames.Count - 1; @@ -4038,8 +4356,7 @@ private void AllDirectionsAddWithCanvasKRFrameEditorColorCorrectorToolStripMenuI SetPaletteBox(); FramesListView.Invalidate(); - CenterXNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.X; - CenterYNumericUpDown.Value = edit.Frames[FramesTrackBar.Value].Center.Y; + ShowFrameCenter(edit.Frames[FramesTrackBar.Value]); Options.ChangedUltimaClass["Animations"] = true; } @@ -4070,11 +4387,11 @@ private AnimIdx KrAnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimensi for (int index = frameCount / 5 * 0; index < frameCount / 5 * 1; index++) { edit.AddFrame(bitBmp[index], bitBmp[index].Width/2); - TreeNode node = GetNode(_currentBody); + VirtualTreeNode node = GetNode(_currentBody); if (node != null) { node.ForeColor = Color.Empty; - node.Nodes[_currentAction].ForeColor = Color.Empty; + RefreshActionNode(node, _currentAction); } int i = edit.Frames.Count - 1; @@ -4117,11 +4434,11 @@ private AnimIdx KrAnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimensi for (int index = frameCount / 5 * 1; index < frameCount / 5 * 2; index++) { edit.AddFrame(bitBmp[index], bitBmp[index].Width/2); - TreeNode node = GetNode(_currentBody); + VirtualTreeNode node = GetNode(_currentBody); if (node != null) { node.ForeColor = Color.Empty; - node.Nodes[_currentAction].ForeColor = Color.Empty; + RefreshActionNode(node, _currentAction); } int i = edit.Frames.Count - 1; @@ -4164,11 +4481,11 @@ private AnimIdx KrAnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimensi for (int index = frameCount / 5 * 2; index < frameCount / 5 * 3; index++) { edit.AddFrame(bitBmp[index], bitBmp[index].Width/2); - TreeNode node = GetNode(_currentBody); + VirtualTreeNode node = GetNode(_currentBody); if (node != null) { node.ForeColor = Color.Empty; - node.Nodes[_currentAction].ForeColor = Color.Empty; + RefreshActionNode(node, _currentAction); } int i = edit.Frames.Count - 1; @@ -4211,11 +4528,11 @@ private AnimIdx KrAnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimensi for (int index = frameCount / 5 * 3; index < frameCount / 5 * 4; index++) { edit.AddFrame(bitBmp[index], bitBmp[index].Width/2); - TreeNode node = GetNode(_currentBody); + VirtualTreeNode node = GetNode(_currentBody); if (node != null) { node.ForeColor = Color.Empty; - node.Nodes[_currentAction].ForeColor = Color.Empty; + RefreshActionNode(node, _currentAction); } int i = edit.Frames.Count - 1; @@ -4258,11 +4575,11 @@ private AnimIdx KrAnimIdxPositions(int frameCount, Bitmap[] bitBmp, FrameDimensi for (int index = frameCount / 5 * 4; index < frameCount / 5 * 5; index++) { edit.AddFrame(bitBmp[index], bitBmp[index].Width/2); - TreeNode node = GetNode(_currentBody); + VirtualTreeNode node = GetNode(_currentBody); if (node != null) { node.ForeColor = Color.Empty; - node.Nodes[_currentAction].ForeColor = Color.Empty; + RefreshActionNode(node, _currentAction); } int i = edit.Frames.Count - 1; diff --git a/UoFiddler.Controls/Forms/PackOptionsForm.Designer.cs b/UoFiddler.Controls/Forms/PackOptionsForm.Designer.cs index 235d490f..696c6a3e 100644 --- a/UoFiddler.Controls/Forms/PackOptionsForm.Designer.cs +++ b/UoFiddler.Controls/Forms/PackOptionsForm.Designer.cs @@ -39,10 +39,16 @@ private void InitializeComponent() SpacingUpDown = new System.Windows.Forms.NumericUpDown(); OneRowPerDirectionCheckBox = new System.Windows.Forms.CheckBox(); ExportAllActionsCheckBox = new System.Windows.Forms.CheckBox(); + ScaleLabel = new System.Windows.Forms.Label(); + ScaleUpDown = new System.Windows.Forms.NumericUpDown(); + FormatLabel = new System.Windows.Forms.Label(); + SheetFormatRadioButton = new System.Windows.Forms.RadioButton(); + FramesXmlFormatRadioButton = new System.Windows.Forms.RadioButton(); OkButton = new System.Windows.Forms.Button(); CancelDialogButton = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)MaxWidthUpDown).BeginInit(); ((System.ComponentModel.ISupportInitialize)SpacingUpDown).BeginInit(); + ((System.ComponentModel.ISupportInitialize)ScaleUpDown).BeginInit(); SuspendLayout(); // // DirectionsLabel @@ -148,13 +154,63 @@ private void InitializeComponent() ExportAllActionsCheckBox.TabIndex = 7; ExportAllActionsCheckBox.Text = "Export all actions of the body"; ExportAllActionsCheckBox.UseVisualStyleBackColor = true; + // + // ScaleLabel + // + ScaleLabel.AutoSize = true; + ScaleLabel.Location = new System.Drawing.Point(212, 142); + ScaleLabel.Name = "ScaleLabel"; + ScaleLabel.Size = new System.Drawing.Size(88, 15); + ScaleLabel.Text = "Frame size (%):"; + // + // ScaleUpDown + // + ScaleUpDown.Increment = new decimal(new int[] { 10, 0, 0, 0 }); + ScaleUpDown.Location = new System.Drawing.Point(212, 160); + ScaleUpDown.Maximum = new decimal(new int[] { 400, 0, 0, 0 }); + ScaleUpDown.Minimum = new decimal(new int[] { 10, 0, 0, 0 }); + ScaleUpDown.Name = "ScaleUpDown"; + ScaleUpDown.Size = new System.Drawing.Size(80, 23); + ScaleUpDown.TabIndex = 8; + ScaleUpDown.Value = new decimal(new int[] { 100, 0, 0, 0 }); + // + // FormatLabel + // + FormatLabel.AutoSize = true; + FormatLabel.Location = new System.Drawing.Point(12, 236); + FormatLabel.Name = "FormatLabel"; + FormatLabel.Size = new System.Drawing.Size(48, 15); + FormatLabel.Text = "Format:"; + // + // SheetFormatRadioButton + // + SheetFormatRadioButton.AutoSize = true; + SheetFormatRadioButton.Checked = true; + SheetFormatRadioButton.Location = new System.Drawing.Point(12, 254); + SheetFormatRadioButton.Name = "SheetFormatRadioButton"; + SheetFormatRadioButton.Size = new System.Drawing.Size(170, 19); + SheetFormatRadioButton.TabIndex = 9; + SheetFormatRadioButton.TabStop = true; + SheetFormatRadioButton.Text = "Sprite sheet (.png + .json)"; + SheetFormatRadioButton.UseVisualStyleBackColor = true; + SheetFormatRadioButton.CheckedChanged += OnCheckedChangedFormat; + // + // FramesXmlFormatRadioButton + // + FramesXmlFormatRadioButton.AutoSize = true; + FramesXmlFormatRadioButton.Location = new System.Drawing.Point(12, 279); + FramesXmlFormatRadioButton.Name = "FramesXmlFormatRadioButton"; + FramesXmlFormatRadioButton.Size = new System.Drawing.Size(232, 19); + FramesXmlFormatRadioButton.TabIndex = 10; + FramesXmlFormatRadioButton.Text = "One image per frame (.png + .xml)"; + FramesXmlFormatRadioButton.UseVisualStyleBackColor = true; // // OkButton // - OkButton.Location = new System.Drawing.Point(218, 240); + OkButton.Location = new System.Drawing.Point(218, 312); OkButton.Name = "OkButton"; OkButton.Size = new System.Drawing.Size(75, 25); - OkButton.TabIndex = 8; + OkButton.TabIndex = 11; OkButton.Text = "OK"; OkButton.UseVisualStyleBackColor = true; OkButton.Click += OnClickOk; @@ -162,10 +218,10 @@ private void InitializeComponent() // CancelDialogButton // CancelDialogButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; - CancelDialogButton.Location = new System.Drawing.Point(299, 240); + CancelDialogButton.Location = new System.Drawing.Point(299, 312); CancelDialogButton.Name = "CancelDialogButton"; CancelDialogButton.Size = new System.Drawing.Size(75, 25); - CancelDialogButton.TabIndex = 9; + CancelDialogButton.TabIndex = 12; CancelDialogButton.Text = "Cancel"; CancelDialogButton.UseVisualStyleBackColor = true; // @@ -173,7 +229,7 @@ private void InitializeComponent() // AcceptButton = OkButton; CancelButton = CancelDialogButton; - ClientSize = new System.Drawing.Size(386, 277); + ClientSize = new System.Drawing.Size(386, 349); Controls.Add(DirectionsLabel); Controls.Add(DirectionsListBox); Controls.Add(MaxWidthLabel); @@ -185,6 +241,11 @@ private void InitializeComponent() Controls.Add(SpacingUpDown); Controls.Add(OneRowPerDirectionCheckBox); Controls.Add(ExportAllActionsCheckBox); + Controls.Add(ScaleLabel); + Controls.Add(ScaleUpDown); + Controls.Add(FormatLabel); + Controls.Add(SheetFormatRadioButton); + Controls.Add(FramesXmlFormatRadioButton); Controls.Add(OkButton); Controls.Add(CancelDialogButton); FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; @@ -196,6 +257,7 @@ private void InitializeComponent() Text = "Pack Frames"; ((System.ComponentModel.ISupportInitialize)MaxWidthUpDown).EndInit(); ((System.ComponentModel.ISupportInitialize)SpacingUpDown).EndInit(); + ((System.ComponentModel.ISupportInitialize)ScaleUpDown).EndInit(); ResumeLayout(false); PerformLayout(); } @@ -213,6 +275,11 @@ private void InitializeComponent() private System.Windows.Forms.NumericUpDown SpacingUpDown; private System.Windows.Forms.CheckBox OneRowPerDirectionCheckBox; private System.Windows.Forms.CheckBox ExportAllActionsCheckBox; + private System.Windows.Forms.Label ScaleLabel; + private System.Windows.Forms.NumericUpDown ScaleUpDown; + private System.Windows.Forms.Label FormatLabel; + private System.Windows.Forms.RadioButton SheetFormatRadioButton; + private System.Windows.Forms.RadioButton FramesXmlFormatRadioButton; private System.Windows.Forms.Button OkButton; private System.Windows.Forms.Button CancelDialogButton; } diff --git a/UoFiddler.Controls/Forms/PackOptionsForm.cs b/UoFiddler.Controls/Forms/PackOptionsForm.cs index 7409bf4a..73510d81 100644 --- a/UoFiddler.Controls/Forms/PackOptionsForm.cs +++ b/UoFiddler.Controls/Forms/PackOptionsForm.cs @@ -63,6 +63,12 @@ public PackOptionsForm() public bool ExportAllActions => ExportAllActionsCheckBox.Checked; + /// Size of the exported frames relative to the stored ones; 1 keeps them as they are. + public double FrameScale => (double)ScaleUpDown.Value / 100.0; + + /// Save one image per frame and a frames XML file instead of a sprite sheet. + public bool FramesXmlFormat => FramesXmlFormatRadioButton.Checked; + private void OnClickPreset(object sender, EventArgs e) { MaxWidthUpDown.Value = decimal.Parse(((Button)sender).Text); @@ -70,8 +76,23 @@ private void OnClickPreset(object sender, EventArgs e) private void OnCheckedChangedOneRowPerDirection(object sender, EventArgs e) { + UpdateSheetOptions(); + } + + private void OnCheckedChangedFormat(object sender, EventArgs e) + { + UpdateSheetOptions(); + } + + private void UpdateSheetOptions() + { + // The layout options only shape a sprite sheet + bool sheet = SheetFormatRadioButton.Checked; + SpacingUpDown.Enabled = sheet; + OneRowPerDirectionCheckBox.Enabled = sheet; + // Rows follow the directions, so the width limit does not apply - bool limitWidth = !OneRowPerDirectionCheckBox.Checked; + bool limitWidth = sheet && !OneRowPerDirectionCheckBox.Checked; MaxWidthUpDown.Enabled = limitWidth; Preset1024Button.Enabled = limitWidth; Preset2048Button.Enabled = limitWidth; diff --git a/UoFiddler.Controls/Forms/VdRemapForm.Designer.cs b/UoFiddler.Controls/Forms/VdRemapForm.Designer.cs new file mode 100644 index 00000000..b5c22bd3 --- /dev/null +++ b/UoFiddler.Controls/Forms/VdRemapForm.Designer.cs @@ -0,0 +1,199 @@ +/*************************************************************************** + * + * $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.Controls.Forms +{ + partial class VdRemapForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + private void InitializeComponent() + { + SourceLabel = new System.Windows.Forms.Label(); + LayoutLabel = new System.Windows.Forms.Label(); + LayoutComboBox = new System.Windows.Forms.ComboBox(); + ScaleLabel = new System.Windows.Forms.Label(); + ScaleUpDown = new System.Windows.Forms.NumericUpDown(); + DefaultsButton = new System.Windows.Forms.Button(); + MappingPanel = new System.Windows.Forms.Panel(); + MappingTable = new System.Windows.Forms.TableLayoutPanel(); + OkButton = new System.Windows.Forms.Button(); + CancelDialogButton = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)ScaleUpDown).BeginInit(); + MappingPanel.SuspendLayout(); + SuspendLayout(); + // + // SourceLabel + // + SourceLabel.AutoSize = true; + SourceLabel.Location = new System.Drawing.Point(12, 12); + SourceLabel.Name = "SourceLabel"; + SourceLabel.Size = new System.Drawing.Size(46, 15); + SourceLabel.TabIndex = 0; + SourceLabel.Text = "Source:"; + // + // LayoutLabel + // + LayoutLabel.AutoSize = true; + LayoutLabel.Location = new System.Drawing.Point(12, 40); + LayoutLabel.Name = "LayoutLabel"; + LayoutLabel.Size = new System.Drawing.Size(72, 15); + LayoutLabel.TabIndex = 1; + LayoutLabel.Text = "Save as type:"; + // + // LayoutComboBox + // + LayoutComboBox.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + LayoutComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + LayoutComboBox.Location = new System.Drawing.Point(100, 37); + LayoutComboBox.Name = "LayoutComboBox"; + LayoutComboBox.Size = new System.Drawing.Size(388, 23); + LayoutComboBox.TabIndex = 2; + LayoutComboBox.SelectedIndexChanged += OnLayoutChanged; + // + // ScaleLabel + // + ScaleLabel.AutoSize = true; + ScaleLabel.Location = new System.Drawing.Point(12, 72); + ScaleLabel.Name = "ScaleLabel"; + ScaleLabel.Size = new System.Drawing.Size(88, 15); + ScaleLabel.TabIndex = 3; + ScaleLabel.Text = "Frame size (%):"; + // + // ScaleUpDown + // + ScaleUpDown.Increment = new decimal(new int[] { 10, 0, 0, 0 }); + ScaleUpDown.Location = new System.Drawing.Point(110, 69); + ScaleUpDown.Maximum = new decimal(new int[] { 400, 0, 0, 0 }); + ScaleUpDown.Minimum = new decimal(new int[] { 10, 0, 0, 0 }); + ScaleUpDown.Name = "ScaleUpDown"; + ScaleUpDown.Size = new System.Drawing.Size(70, 23); + ScaleUpDown.TabIndex = 4; + ScaleUpDown.Value = new decimal(new int[] { 100, 0, 0, 0 }); + // + // DefaultsButton + // + DefaultsButton.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + DefaultsButton.AutoSize = true; + DefaultsButton.Location = new System.Drawing.Point(368, 67); + DefaultsButton.Name = "DefaultsButton"; + DefaultsButton.Size = new System.Drawing.Size(120, 27); + DefaultsButton.TabIndex = 5; + DefaultsButton.Text = "Default mapping"; + DefaultsButton.UseVisualStyleBackColor = true; + DefaultsButton.Click += OnClickDefaults; + // + // MappingPanel + // + MappingPanel.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + MappingPanel.AutoScroll = true; + MappingPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + MappingPanel.Controls.Add(MappingTable); + MappingPanel.Location = new System.Drawing.Point(12, 102); + MappingPanel.Name = "MappingPanel"; + MappingPanel.Size = new System.Drawing.Size(476, 410); + MappingPanel.TabIndex = 6; + // + // MappingTable + // + MappingTable.AutoSize = true; + MappingTable.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; + MappingTable.ColumnCount = 2; + MappingTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 210F)); + MappingTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 240F)); + MappingTable.Dock = System.Windows.Forms.DockStyle.Top; + MappingTable.Location = new System.Drawing.Point(0, 0); + MappingTable.Name = "MappingTable"; + MappingTable.Padding = new System.Windows.Forms.Padding(4); + MappingTable.Size = new System.Drawing.Size(457, 8); + MappingTable.TabIndex = 0; + // + // OkButton + // + OkButton.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + OkButton.DialogResult = System.Windows.Forms.DialogResult.OK; + OkButton.Location = new System.Drawing.Point(332, 522); + OkButton.Name = "OkButton"; + OkButton.Size = new System.Drawing.Size(75, 25); + OkButton.TabIndex = 7; + OkButton.Text = "Export"; + OkButton.UseVisualStyleBackColor = true; + // + // CancelDialogButton + // + CancelDialogButton.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + CancelDialogButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; + CancelDialogButton.Location = new System.Drawing.Point(413, 522); + CancelDialogButton.Name = "CancelDialogButton"; + CancelDialogButton.Size = new System.Drawing.Size(75, 25); + CancelDialogButton.TabIndex = 8; + CancelDialogButton.Text = "Cancel"; + CancelDialogButton.UseVisualStyleBackColor = true; + // + // VdRemapForm + // + AcceptButton = OkButton; + CancelButton = CancelDialogButton; + ClientSize = new System.Drawing.Size(500, 559); + Controls.Add(SourceLabel); + Controls.Add(LayoutLabel); + Controls.Add(LayoutComboBox); + Controls.Add(ScaleLabel); + Controls.Add(ScaleUpDown); + Controls.Add(DefaultsButton); + Controls.Add(MappingPanel); + Controls.Add(OkButton); + Controls.Add(CancelDialogButton); + MinimizeBox = false; + MinimumSize = new System.Drawing.Size(460, 400); + Name = "VdRemapForm"; + ShowInTaskbar = false; + StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + Text = "Body to .vd, remapped"; + ((System.ComponentModel.ISupportInitialize)ScaleUpDown).EndInit(); + MappingPanel.ResumeLayout(false); + MappingPanel.PerformLayout(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private System.Windows.Forms.Label SourceLabel; + private System.Windows.Forms.Label LayoutLabel; + private System.Windows.Forms.ComboBox LayoutComboBox; + private System.Windows.Forms.Label ScaleLabel; + private System.Windows.Forms.NumericUpDown ScaleUpDown; + private System.Windows.Forms.Button DefaultsButton; + private System.Windows.Forms.Panel MappingPanel; + private System.Windows.Forms.TableLayoutPanel MappingTable; + private System.Windows.Forms.Button OkButton; + private System.Windows.Forms.Button CancelDialogButton; + } +} diff --git a/UoFiddler.Controls/Forms/VdRemapForm.cs b/UoFiddler.Controls/Forms/VdRemapForm.cs new file mode 100644 index 00000000..d1463d97 --- /dev/null +++ b/UoFiddler.Controls/Forms/VdRemapForm.cs @@ -0,0 +1,156 @@ +/*************************************************************************** + * + * $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 System.Windows.Forms; +using Ultima; +using UoFiddler.Controls.Classes; + +namespace UoFiddler.Controls.Forms +{ + /// + /// Picks, for each action of a target body type's layout, which action of the source body goes there, + /// for a .vd export in that layout. + /// + public partial class VdRemapForm : Form + { + private static readonly MobType[] _layouts = { MobType.Monster, MobType.Sea, MobType.Animal, MobType.Human }; + + private readonly MobType _sourceType; + private readonly string[] _sourceNames; + private readonly bool[] _sourceHasFrames; + private readonly Func _actionNames; + private readonly List _rows = new(); + + /// Body being exported, for the title. + /// The body's own action layout. + /// For each action of the body, whether it has frames. + /// Action names of a layout. + public VdRemapForm(int body, MobType sourceType, bool[] sourceHasFrames, Func actionNames) + { + InitializeComponent(); + Icon = Options.GetFiddlerIcon(); + + _sourceType = sourceType; + _sourceHasFrames = sourceHasFrames; + _actionNames = actionNames; + string[] names = actionNames(sourceType); + _sourceNames = Enumerable.Range(0, sourceHasFrames.Length) + .Select(i => i < names.Length ? names[i] : $"Action {i}") + .ToArray(); + + Text = $"Body {body} to .vd, remapped"; + SourceLabel.Text = $"Source: body {body}, {DescribeLayout(sourceType)}"; + + foreach (MobType layout in _layouts) + { + LayoutComboBox.Items.Add(DescribeLayout(layout)); + } + + // Start on another layout than the body's own; that is what a remap is for + MobType start = sourceType == MobType.Animal ? MobType.Monster : MobType.Animal; + LayoutComboBox.SelectedIndex = Array.IndexOf(_layouts, start); + } + + public MobType TargetLayout => _layouts[LayoutComboBox.SelectedIndex]; + + /// For each action of the target layout, the source action written there, or -1 for none. + public int[] SourceActions => _rows.Select(row => row.SelectedIndex - 1).ToArray(); + + public int ScalePercent => (int)ScaleUpDown.Value; + + private static string DescribeLayout(MobType layout) + { + return layout switch + { + MobType.Monster => "monster (22 actions)", + MobType.Sea => "sea monster (9 actions, saved as a 22-action monster .vd)", + MobType.Animal => "animal (13 actions)", + MobType.Equipment => "equipment (35 actions)", + _ => "human (35 actions)" + }; + } + + private void OnLayoutChanged(object sender, EventArgs e) + { + BuildRows(); + } + + private void OnClickDefaults(object sender, EventArgs e) + { + ApplyDefaults(); + } + + private void BuildRows() + { + MobType layout = TargetLayout; + IReadOnlyList roles = MobActionMap.GetRoles(layout); + string[] targetNames = _actionNames(layout); + + var sourceItems = new List { "(empty)" }; + for (int i = 0; i < _sourceNames.Length; ++i) + { + sourceItems.Add(_sourceHasFrames[i] ? $"{i:D2} {_sourceNames[i]}" : $"{i:D2} {_sourceNames[i]} (no frames)"); + } + + MappingTable.SuspendLayout(); + MappingTable.Controls.Clear(); + MappingTable.RowStyles.Clear(); + _rows.Clear(); + MappingTable.RowCount = roles.Count; + + for (int target = 0; target < roles.Count; ++target) + { + string name = target < targetNames.Length ? targetNames[target] : $"Action {target}"; + var label = new Label + { + Text = $"{target:D2} {name}", + AutoSize = true, + Anchor = AnchorStyles.Left + }; + var combo = new ComboBox + { + DropDownStyle = ComboBoxStyle.DropDownList, + Dock = DockStyle.Fill + }; + combo.Items.AddRange(sourceItems.ToArray()); + + MappingTable.RowStyles.Add(new RowStyle(SizeType.AutoSize)); + MappingTable.Controls.Add(label, 0, target); + MappingTable.Controls.Add(combo, 1, target); + _rows.Add(combo); + } + + MappingTable.ResumeLayout(); + ApplyDefaults(); + } + + /// + /// Fills every row with the source action that shows the closest thing, or empty when that action has no frames. + /// + private void ApplyDefaults() + { + MobType layout = TargetLayout; + for (int target = 0; target < _rows.Count; ++target) + { + int source = MobActionMap.MapAction(layout, target, _sourceType); + if (source >= _sourceHasFrames.Length || (source >= 0 && !_sourceHasFrames[source])) + { + source = -1; + } + + _rows[target].SelectedIndex = source + 1; + } + } + } +} diff --git a/UoFiddler.Controls/Forms/VdRemapForm.resx b/UoFiddler.Controls/Forms/VdRemapForm.resx new file mode 100644 index 00000000..459ff736 --- /dev/null +++ b/UoFiddler.Controls/Forms/VdRemapForm.resx @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + diff --git a/UoFiddler.Controls/UserControls/AnimationListControl.cs b/UoFiddler.Controls/UserControls/AnimationListControl.cs index dfe66c9f..2a7f2aaf 100644 --- a/UoFiddler.Controls/UserControls/AnimationListControl.cs +++ b/UoFiddler.Controls/UserControls/AnimationListControl.cs @@ -1500,16 +1500,19 @@ private void OnClickPackFrames(object sender, EventArgs e) return; } + string files = optionsForm.FramesXmlFormat ? ".xml and _frames folder" : ".png, .json and _guide.png"; string message = saved.Count == 1 - ? $"Packed sheet {Path.GetFileName(saved[0])} (.png, .json and _guide.png) saved successfully." - : $"{saved.Count} packed sheets anim_{body}_ (.png, .json and _guide.png) saved successfully."; + ? $"Packed {Path.GetFileName(saved[0])} ({files}) saved successfully." + : $"{saved.Count} packed actions anim_{body}_ ({files}) saved successfully."; FileSavedDialog.Show(FindForm(), outDir, message); } /// /// Packs the frames of the chosen directions of one action into anim_{body}_{action}.png /// with a .json descriptor, a _guide.png showing frame bounds and anchors and, with one - /// row per direction, a _rows.txt naming the rows. + /// row per direction, a _rows.txt naming the rows. In the frames XML format each frame is saved + /// as its own image in anim_{body}_{action}_frames, listed in anim_{body}_{action}.xml. + /// Frames and centers are resized by the chosen frame size. /// /// The output path without extension, or null if the action has no frames. private static string PackAnimation(string outDir, int body, int action, PackOptionsForm options) @@ -1517,7 +1520,9 @@ private static string PackAnimation(string outDir, int body, int action, PackOpt var layout = new SpriteSheetLayout(options.MaxWidth, options.Spacing); var entries = new List(); var images = new List(); + var xmlFrames = new List<(int Direction, int Index, Point Center, Bitmap Image)>(); var rows = new StringBuilder(); + double scale = options.FrameScale; int rowCount = 0; try @@ -1532,7 +1537,7 @@ private static string PackAnimation(string outDir, int body, int action, PackOpt continue; } - if (options.OneRowPerDirection) + if (options.OneRowPerDirection && !options.FramesXmlFormat) { layout.NewRow(); rows.AppendLine($"Row {rowCount++}: {direction} {PackOptionsForm.DirectionNames[direction]}"); @@ -1546,18 +1551,49 @@ private static string PackAnimation(string outDir, int body, int action, PackOpt continue; } - PackedRect rect = layout.Place(frame.Bitmap.Width, frame.Bitmap.Height, wrap: !options.OneRowPerDirection); + // The frames are cache-owned, so pack copies + Bitmap image; + Point center = frame.Center; + if (scale != 1.0) + { + image = SpriteSheetPacker.ScaleNearest(frame.Bitmap, scale); + center = AnimIdx.ScaleCenter(frame.Center, frame.Bitmap.Height, image.Height, scale); + } + else + { + image = new Bitmap(frame.Bitmap); + } + + images.Add(image); + + if (options.FramesXmlFormat) + { + xmlFrames.Add((direction, i, center, image)); + continue; + } + + PackedRect rect = layout.Place(image.Width, image.Height, wrap: !options.OneRowPerDirection); entries.Add(new PackedFrameEntry { Direction = direction, Index = i, Frame = rect, - Center = new PackedPoint { X = frame.Center.X, Y = frame.Center.Y } + Center = new PackedPoint { X = center.X, Y = center.Y } }); + } + } + + string baseName = Path.Combine(outDir, $"anim_{body}_{action}"); - // The frames are cache-owned - images.Add(new Bitmap(frame.Bitmap)); + if (options.FramesXmlFormat) + { + if (xmlFrames.Count == 0) + { + return null; } + + FramesXml.Write(baseName + ".xml", xmlFrames); + return baseName; } if (entries.Count == 0) @@ -1565,7 +1601,6 @@ private static string PackAnimation(string outDir, int body, int action, PackOpt return null; } - string baseName = Path.Combine(outDir, $"anim_{body}_{action}"); string imageFile = baseName + ".png"; List rects = entries.Select(entry => entry.Frame).ToList(); @@ -1673,8 +1708,8 @@ private void OnClickUnpackFrames(object sender, EventArgs e) using var fileDialog = new OpenFileDialog { InitialDirectory = SpriteSheetPacker.LastFolder, - Filter = "Packed sheet (*.json)|*.json|All files (*.*)|*.*", - Title = "Select the Json file of a packed sheet" + Filter = "Packed frames (*.json, *.xml)|*.json;*.xml|Packed sheet (*.json)|*.json|Frames XML (*.xml)|*.xml|All files (*.*)|*.*", + Title = "Select the Json file of a packed sheet or a frames XML file" }; if (fileDialog.ShowDialog(this) != DialogResult.OK) { @@ -1728,7 +1763,7 @@ private void OnClickBulkUnpackFrames(object sender, EventArgs e) using var folderDialog = new FolderBrowserDialog { - Description = $"Select the folder holding the packed sheets anim_{body}_.json", + Description = $"Select the folder holding the packed sheets anim_{body}_.json or frames XML files anim_{body}_.xml", ShowNewFolderButton = false, SelectedPath = SpriteSheetPacker.LastFolder }; @@ -1739,14 +1774,23 @@ private void OnClickBulkUnpackFrames(object sender, EventArgs e) SpriteSheetPacker.LastFolder = folderDialog.SelectedPath; - // Only sheets of the selected body are imported; their actions come from the file names + // Only files of the selected body are imported; their actions come from the file names. + // A sheet wins over a frames XML file of the same action. var sheets = new SortedDictionary(); int otherFiles = 0; - foreach (string file in Directory.GetFiles(folderDialog.SelectedPath, "*.json")) + foreach (string file in Directory.GetFiles(folderDialog.SelectedPath, "*.json") + .Concat(Directory.GetFiles(folderDialog.SelectedPath, "*.xml"))) { if (TryParsePackedAnimationName(file, out int packedBody, out int packedAction) && packedBody == body) { - sheets[packedAction] = file; + if (!sheets.ContainsKey(packedAction)) + { + sheets[packedAction] = file; + } + else + { + otherFiles++; + } } else { @@ -1756,7 +1800,7 @@ private void OnClickBulkUnpackFrames(object sender, EventArgs e) if (sheets.Count == 0) { - MessageBox.Show($"No packed sheets anim_{body}_.json found in {folderDialog.SelectedPath}.", + MessageBox.Show($"No packed sheets anim_{body}_.json or frames XML files anim_{body}_.xml found in {folderDialog.SelectedPath}.", title, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } @@ -1799,7 +1843,7 @@ private void OnClickBulkUnpackFrames(object sender, EventArgs e) string message = $"Imported {imported} of {sheets.Count} sheet(s), {frames} frames, into body {body}."; if (otherFiles > 0) { - message += $"\nIgnored {otherFiles} other Json file(s)."; + message += $"\nIgnored {otherFiles} other Json or XML file(s)."; } if (errors.Count > 0) @@ -1832,20 +1876,101 @@ private sealed class UnpackResult public string Info { get; set; } = string.Empty; } + private static bool IsFramesXml(string file) + { + return string.Equals(Path.GetExtension(file), ".xml", StringComparison.OrdinalIgnoreCase); + } + /// - /// Imports a packed sheet into of (a MUL body). - /// The sheet is read and checked before anything changes, so a failure leaves the animation as it was. + /// The frames listed in a packed sheet (.json) or a frames XML file (.xml), each with the image it is + /// cut from: the sheet, or the frame's own image with a rect covering all of it. /// - /// Replace each imported direction's frames instead of appending to them. - private static UnpackResult UnpackAnimation(string jsonFile, int body, int action, bool replace) + private sealed class PackedFrames : IDisposable + { + public List<(PackedFrameEntry Entry, Bitmap Source)> Frames { get; } = new(); + + public List Images { get; } = new(); + + /// Frames of a frames XML file whose image file was not found. + public int MissingImages { get; set; } + + public void Dispose() + { + foreach (Bitmap image in Images) + { + image.Dispose(); + } + } + } + + private static PackedFrames ReadPackedFrames(string file) { - string name = Path.GetFileName(jsonFile); - PackedAnimation packed = SpriteSheetPacker.ReadJson(jsonFile); - if (packed.Frames == null || packed.Frames.Count == 0) + string name = Path.GetFileName(file); + var result = new PackedFrames(); + try + { + if (IsFramesXml(file)) + { + foreach (FramesXmlFrame frame in FramesXml.Read(file)) + { + string imageFile = FramesXml.FindImage(file, frame); + if (imageFile == null) + { + result.MissingImages++; + continue; + } + + Bitmap image = FramesXml.LoadImage(imageFile); + result.Images.Add(image); + result.Frames.Add((new PackedFrameEntry + { + Direction = frame.Direction, + Index = frame.Index, + Frame = new PackedRect { X = 0, Y = 0, W = image.Width, H = image.Height }, + Center = new PackedPoint { X = frame.Center.X, Y = frame.Center.Y } + }, image)); + } + + if (result.Frames.Count == 0 && result.MissingImages == 0) + { + throw new InvalidDataException($"{name} lists no frames."); + } + } + else + { + PackedAnimation packed = SpriteSheetPacker.ReadJson(file); + if (packed.Frames == null || packed.Frames.Count == 0) + { + throw new InvalidDataException($"{name} lists no frames."); + } + + Bitmap sheet = SpriteSheetPacker.LoadSheet(file, packed.Meta); + result.Images.Add(sheet); + foreach (PackedFrameEntry entry in packed.Frames.Where(entry => entry != null)) + { + result.Frames.Add((entry, sheet)); + } + } + } + catch { - throw new InvalidDataException($"{name} lists no frames."); + result.Dispose(); + throw; } + return result; + } + + /// + /// Imports a packed sheet (.json) or frames XML file (.xml) into of + /// (a MUL body). The file is read and checked before anything changes, so a + /// failure leaves the animation as it was. + /// + /// Replace each imported direction's frames instead of appending to them. + private static UnpackResult UnpackAnimation(string packedFile, int body, int action, bool replace) + { + string name = Path.GetFileName(packedFile); + int fileBody = body; Animations.Translate(ref fileBody); int fileType = BodyConverter.Convert(ref fileBody); @@ -1861,17 +1986,22 @@ private static UnpackResult UnpackAnimation(string jsonFile, int body, int actio int skippedFrames = 0; var directions = new SortedDictionary>(); - // A mirrored direction (5-7) is only imported when the sheet does not also hold the stored one - var storedOnSheet = packed.Frames - .Where(entry => entry != null && entry.Direction >= 0 && entry.Direction < PackOptionsForm.StoredDirections) - .Select(entry => entry.Direction) - .ToHashSet(); - try { - using (Bitmap sheet = SpriteSheetPacker.LoadSheet(jsonFile, packed.Meta)) + using (PackedFrames packed = ReadPackedFrames(packedFile)) { - foreach (PackedFrameEntry entry in packed.Frames.Where(entry => entry != null).OrderBy(entry => entry.Index)) + if (packed.MissingImages > 0) + { + result.Notes += $"\nSkipped {packed.MissingImages} frame(s) whose image file was not found."; + } + + // A mirrored direction (5-7) is only imported when the file does not also hold the stored one + var storedOnSheet = packed.Frames + .Where(frame => frame.Entry.Direction >= 0 && frame.Entry.Direction < PackOptionsForm.StoredDirections) + .Select(frame => frame.Entry.Direction) + .ToHashSet(); + + foreach (var (entry, sheet) in packed.Frames.OrderBy(frame => frame.Entry.Index)) { if (entry.Direction < 0 || entry.Direction >= PackOptionsForm.DirectionNames.Length) { diff --git a/UoFiddler.Controls/UserControls/VirtualTreeView.cs b/UoFiddler.Controls/UserControls/VirtualTreeView.cs new file mode 100644 index 00000000..9db68404 --- /dev/null +++ b/UoFiddler.Controls/UserControls/VirtualTreeView.cs @@ -0,0 +1,743 @@ +/*************************************************************************** + * + * $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; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; + +namespace UoFiddler.Controls.UserControls +{ + /// + /// A node of a . Nodes are plain objects: none of them owns a native item. + /// + public sealed class VirtualTreeNode + { + private string _text = string.Empty; + private Color _foreColor = Color.Empty; + private VirtualTreeView _rootOwner; + + public VirtualTreeNode() + { + Nodes = new VirtualTreeNodeCollection(null, this); + } + + public string Text + { + get => _text; + set + { + _text = value ?? string.Empty; + TreeView?.Invalidate(); + } + } + + public object Tag { get; set; } + + public Color ForeColor + { + get => _foreColor; + set + { + if (_foreColor != value) + { + _foreColor = value; + TreeView?.Invalidate(); + } + } + } + + public string ToolTipText { get; set; } = string.Empty; + + public VirtualTreeNode Parent { get; internal set; } + + public VirtualTreeNodeCollection Nodes { get; } + + public bool IsExpanded { get; internal set; } + + public int Level => Parent == null ? 0 : Parent.Level + 1; + + public VirtualTreeView TreeView => Parent != null ? Parent.TreeView : _rootOwner; + + internal void SetRootOwner(VirtualTreeView owner) + { + _rootOwner = owner; + } + + public void Expand() + { + VirtualTreeView tree = TreeView; + if (tree != null) + { + tree.SetExpanded(this, true); + } + else + { + IsExpanded = true; + } + } + + public void Collapse() + { + VirtualTreeView tree = TreeView; + if (tree != null) + { + tree.SetExpanded(this, false); + } + else + { + IsExpanded = false; + } + } + + public void Remove() + { + if (Parent != null) + { + Parent.Nodes.Remove(this); + } + else + { + _rootOwner?.Nodes.Remove(this); + } + } + + public override string ToString() => Text; + } + + public sealed class VirtualTreeNodeCollection : IEnumerable + { + private readonly List _nodes = new(); + private readonly VirtualTreeView _tree; + private readonly VirtualTreeNode _owner; + + internal VirtualTreeNodeCollection(VirtualTreeView tree, VirtualTreeNode owner) + { + _tree = tree; + _owner = owner; + } + + public int Count => _nodes.Count; + + public VirtualTreeNode this[int index] => _nodes[index]; + + private VirtualTreeView Tree => _tree ?? _owner?.TreeView; + + public void Add(VirtualTreeNode node) + { + Attach(node); + _nodes.Add(node); + Tree?.OnStructureChanged(); + } + + public void AddRange(IEnumerable nodes) + { + foreach (VirtualTreeNode node in nodes) + { + Attach(node); + _nodes.Add(node); + } + + Tree?.OnStructureChanged(); + } + + public void Remove(VirtualTreeNode node) + { + if (_nodes.Remove(node)) + { + VirtualTreeView tree = Tree; + Detach(node); + tree?.OnStructureChanged(); + } + } + + public void Clear() + { + VirtualTreeView tree = Tree; + foreach (VirtualTreeNode node in _nodes) + { + Detach(node); + } + + _nodes.Clear(); + tree?.OnStructureChanged(); + } + + public int IndexOf(VirtualTreeNode node) => _nodes.IndexOf(node); + + public IEnumerator GetEnumerator() => _nodes.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + private void Attach(VirtualTreeNode node) + { + node.Parent = _owner; + node.SetRootOwner(_owner == null ? _tree : null); + } + + private static void Detach(VirtualTreeNode node) + { + node.Parent = null; + node.SetRootOwner(null); + } + } + + public sealed class VirtualTreeNodeEventArgs : EventArgs + { + public VirtualTreeNodeEventArgs(VirtualTreeNode node) + { + Node = node; + } + + public VirtualTreeNode Node { get; } + } + + /// + /// A tree drawn on a virtual : only the visible rows are ever asked for, so filling + /// and destroying it costs the same for ten nodes or a hundred thousand, unlike , + /// which makes and destroys a native item per node. + /// + public class VirtualTreeView : ListView + { + private const int _indent = 16; + private const int _glyphSize = 16; + + private readonly List _rows = new(); + private VirtualTreeNode _selectedNode; + private int _updateDepth; + private bool _rowsDirty; + private bool _suppressSelectionEvents; + private const int _toolTipDuration = 20000; + private readonly ToolTip _toolTip = new ToolTip(); + private readonly Timer _toolTipTimer = new Timer { Interval = 500 }; + private VirtualTreeNode _toolTipNode; + + public VirtualTreeView() + { + Nodes = new VirtualTreeNodeCollection(this, null); + + VirtualMode = true; + View = View.Details; + HeaderStyle = ColumnHeaderStyle.None; + FullRowSelect = true; + MultiSelect = false; + HideSelection = false; + OwnerDraw = true; + DoubleBuffered = true; + Columns.Add(string.Empty); + + _toolTipTimer.Tick += OnToolTipTimer; + } + + /// Raised before a node's children are shown; a lazy node fills them in here. + public event EventHandler BeforeExpand; + + /// Raised when the selected node changes, including when it is set from code. + public event EventHandler AfterSelect; + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public VirtualTreeNodeCollection Nodes { get; } + + /// + /// Show a node's when the mouse rests on it. A node without + /// one, or with this off, still gets its full text when the row cuts it off, as in . + /// + [DefaultValue(false)] + public bool ShowNodeToolTips { get; set; } + + // The tooltip is shown by hand for the row under the mouse. An automatic ToolTip treats the whole list as + // one area, so after it pops once or after a click it would not come back while the mouse stays inside. + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + + VirtualTreeNode node = NodeAt(e.Location); + if (ReferenceEquals(node, _toolTipNode)) + { + return; + } + + _toolTipNode = node; + HideToolTip(); + if (GetToolTipText(node) != null) + { + _toolTipTimer.Start(); + } + } + + private void OnToolTipTimer(object sender, EventArgs e) + { + _toolTipTimer.Stop(); + + Point mouse = PointToClient(Cursor.Position); + if (_toolTipNode == null || !ClientRectangle.Contains(mouse) || !ReferenceEquals(NodeAt(mouse), _toolTipNode)) + { + return; + } + + string text = GetToolTipText(_toolTipNode); + if (text != null) + { + _toolTip.Show(text, this, mouse.X + 12, mouse.Y + 20, _toolTipDuration); + } + } + + private string GetToolTipText(VirtualTreeNode node) + { + if (node == null) + { + return null; + } + + if (ShowNodeToolTips && !string.IsNullOrEmpty(node.ToolTipText)) + { + return node.ToolTipText; + } + + return TextLeft(node) + TextRenderer.MeasureText(node.Text, Font).Width > ClientSize.Width ? node.Text : null; + } + + private void HideToolTip() + { + _toolTipTimer.Stop(); + _toolTip.Hide(this); + } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + _toolTipNode = null; + HideToolTip(); + } + + protected override void OnMouseWheel(MouseEventArgs e) + { + // The rows move under the mouse; the next mouse move picks up the new row + _toolTipNode = null; + HideToolTip(); + base.OnMouseWheel(e); + } + + protected override void WndProc(ref Message m) + { + // Hide the tooltip before the list handles a click or key: ListView runs its own click handling + // (drag detection, selection) before OnMouseDown is raised + switch (m.Msg) + { + case 0x0100: // WM_KEYDOWN + case 0x0201: // WM_LBUTTONDOWN + case 0x0203: // WM_LBUTTONDBLCLK + case 0x0204: // WM_RBUTTONDOWN + case 0x0207: // WM_MBUTTONDOWN + HideToolTip(); + break; + } + + base.WndProc(ref m); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _toolTipTimer.Dispose(); + _toolTip.Dispose(); + } + + base.Dispose(disposing); + } + + private static int TextLeft(VirtualTreeNode node) + { + return (node.Level * _indent) + _glyphSize + 2; + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public VirtualTreeNode SelectedNode + { + get => _selectedNode; + set => Select(value, raiseEvent: true); + } + + public new void BeginUpdate() + { + _updateDepth++; + base.BeginUpdate(); + } + + public new void EndUpdate() + { + if (_updateDepth > 0 && --_updateDepth == 0 && _rowsDirty) + { + RebuildRows(); + } + + base.EndUpdate(); + } + + internal void OnStructureChanged() + { + if (_updateDepth > 0) + { + _rowsDirty = true; + return; + } + + RebuildRows(); + } + + internal void SetExpanded(VirtualTreeNode node, bool expanded) + { + if (node.IsExpanded == expanded) + { + return; + } + + if (expanded) + { + // The handler may replace the children; collect one rebuild for both changes + BeginUpdate(); + try + { + BeforeExpand?.Invoke(this, new VirtualTreeNodeEventArgs(node)); + node.IsExpanded = node.Nodes.Count > 0; + _rowsDirty = true; + } + finally + { + EndUpdate(); + } + } + else + { + node.IsExpanded = false; + OnStructureChanged(); + } + } + + private void RebuildRows() + { + _rowsDirty = false; + int oldIndex = _selectedNode == null ? -1 : _rows.IndexOf(_selectedNode); + + _rows.Clear(); + foreach (VirtualTreeNode node in Nodes) + { + AddRows(node); + } + + _suppressSelectionEvents = true; + try + { + SelectedIndices.Clear(); + VirtualListSize = _rows.Count; + } + finally + { + _suppressSelectionEvents = false; + } + + if (_selectedNode == null) + { + Invalidate(); + return; + } + + if (_rows.Contains(_selectedNode)) + { + Select(_selectedNode, raiseEvent: false); + return; + } + + // Like TreeView: a node hidden by a collapse passes the selection to the nearest shown parent; + // a removed node passes it to the row that took its place. + VirtualTreeNode replacement = null; + if (IsInTree(_selectedNode)) + { + replacement = _selectedNode.Parent; + while (replacement != null && !_rows.Contains(replacement)) + { + replacement = replacement.Parent; + } + } + else if (_rows.Count > 0 && oldIndex >= 0) + { + replacement = _rows[Math.Min(oldIndex, _rows.Count - 1)]; + } + + _selectedNode = null; + Select(replacement, raiseEvent: true); + } + + private void AddRows(VirtualTreeNode node) + { + _rows.Add(node); + if (!node.IsExpanded) + { + return; + } + + foreach (VirtualTreeNode child in node.Nodes) + { + AddRows(child); + } + } + + private bool IsInTree(VirtualTreeNode node) + { + while (node.Parent != null) + { + node = node.Parent; + } + + return node.TreeView == this && Nodes.IndexOf(node) >= 0; + } + + private void Select(VirtualTreeNode node, bool raiseEvent) + { + if (node != null) + { + for (VirtualTreeNode parent = node.Parent; parent != null; parent = parent.Parent) + { + parent.Expand(); + } + + if (_rowsDirty && _updateDepth == 0) + { + RebuildRows(); + } + } + + bool changed = !ReferenceEquals(node, _selectedNode); + _selectedNode = node; + + int index = node == null ? -1 : _rows.IndexOf(node); + _suppressSelectionEvents = true; + try + { + SelectedIndices.Clear(); + if (index >= 0) + { + SelectedIndices.Add(index); + FocusedItem = Items[index]; + EnsureVisible(index); + } + } + finally + { + _suppressSelectionEvents = false; + } + + Invalidate(); + if (changed && raiseEvent) + { + AfterSelect?.Invoke(this, new VirtualTreeNodeEventArgs(node)); + } + } + + protected override void OnSelectedIndexChanged(EventArgs e) + { + base.OnSelectedIndexChanged(e); + if (_suppressSelectionEvents || SelectedIndices.Count == 0) + { + return; + } + + int index = SelectedIndices[0]; + VirtualTreeNode node = index < _rows.Count ? _rows[index] : null; + if (node != null && !ReferenceEquals(node, _selectedNode)) + { + _selectedNode = node; + AfterSelect?.Invoke(this, new VirtualTreeNodeEventArgs(node)); + } + } + + protected override void OnRetrieveVirtualItem(RetrieveVirtualItemEventArgs e) + { + VirtualTreeNode node = e.ItemIndex < _rows.Count ? _rows[e.ItemIndex] : null; + e.Item = new ListViewItem(node?.Text ?? string.Empty) { ToolTipText = node?.ToolTipText ?? string.Empty }; + base.OnRetrieveVirtualItem(e); + } + + protected override void OnDrawColumnHeader(DrawListViewColumnHeaderEventArgs e) + { + e.DrawDefault = true; + base.OnDrawColumnHeader(e); + } + + protected override void OnDrawItem(DrawListViewItemEventArgs e) + { + VirtualTreeNode node = e.ItemIndex < _rows.Count ? _rows[e.ItemIndex] : null; + if (node == null) + { + return; + } + + Rectangle bounds = new Rectangle(0, e.Bounds.Y, ClientSize.Width, e.Bounds.Height); + bool selected = ReferenceEquals(node, _selectedNode); + bool focused = selected && Focused; + Color back = focused ? SystemColors.Highlight : selected ? SystemColors.ControlLight : BackColor; + using (var brush = new SolidBrush(back)) + { + e.Graphics.FillRectangle(brush, bounds); + } + + int x = bounds.X + (node.Level * _indent); + if (node.Nodes.Count > 0) + { + DrawGlyph(e.Graphics, new Rectangle(x, bounds.Y + ((bounds.Height - _glyphSize) / 2), _glyphSize, _glyphSize), node.IsExpanded); + } + + Color fore = focused ? SystemColors.HighlightText : node.ForeColor.IsEmpty ? ForeColor : node.ForeColor; + var textBounds = new Rectangle(x + _glyphSize + 2, bounds.Y, Math.Max(0, bounds.Right - x - _glyphSize - 2), bounds.Height); + TextRenderer.DrawText(e.Graphics, node.Text, Font, textBounds, fore, + TextFormatFlags.VerticalCenter | TextFormatFlags.Left | TextFormatFlags.NoPrefix | TextFormatFlags.EndEllipsis); + } + + protected override void OnDrawSubItem(DrawListViewSubItemEventArgs e) + { + // The whole row is drawn in OnDrawItem + } + + private void DrawGlyph(Graphics g, Rectangle rect, bool expanded) + { + VisualStyleElement element = expanded ? VisualStyleElement.TreeView.Glyph.Opened : VisualStyleElement.TreeView.Glyph.Closed; + if (Application.RenderWithVisualStyles && VisualStyleRenderer.IsElementDefined(element)) + { + new VisualStyleRenderer(element).DrawBackground(g, rect); + return; + } + + var box = new Rectangle(rect.X + 4, rect.Y + 4, 8, 8); + g.DrawRectangle(SystemPens.GrayText, box); + g.DrawLine(SystemPens.WindowText, box.X + 2, box.Y + 4, box.Right - 2, box.Y + 4); + if (!expanded) + { + g.DrawLine(SystemPens.WindowText, box.X + 4, box.Y + 2, box.X + 4, box.Bottom - 2); + } + } + + protected override void OnMouseDown(MouseEventArgs e) + { + // Like TreeView, a click hides the tooltip until the mouse moves to another row + HideToolTip(); + + VirtualTreeNode node = NodeAt(e.Location); + if (node != null && e.Button == MouseButtons.Left && node.Nodes.Count > 0) + { + int glyphX = node.Level * _indent; + if (e.X >= glyphX && e.X < glyphX + _glyphSize) + { + Toggle(node); + return; + } + } + + base.OnMouseDown(e); + } + + protected override void OnMouseDoubleClick(MouseEventArgs e) + { + VirtualTreeNode node = NodeAt(e.Location); + if (node != null && e.Button == MouseButtons.Left && node.Nodes.Count > 0) + { + Toggle(node); + } + + base.OnMouseDoubleClick(e); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + HideToolTip(); + + VirtualTreeNode node = _selectedNode; + if (node != null) + { + switch (e.KeyCode) + { + case Keys.Right: + case Keys.Add: + if (node.Nodes.Count > 0 && !node.IsExpanded) + { + node.Expand(); + } + else if (e.KeyCode == Keys.Right && node.IsExpanded && node.Nodes.Count > 0) + { + SelectedNode = node.Nodes[0]; + } + + e.Handled = true; + return; + case Keys.Left: + case Keys.Subtract: + if (node.IsExpanded) + { + node.Collapse(); + } + else if (e.KeyCode == Keys.Left && node.Parent != null) + { + SelectedNode = node.Parent; + } + + e.Handled = true; + return; + } + } + + base.OnKeyDown(e); + } + + protected override void OnClientSizeChanged(EventArgs e) + { + base.OnClientSizeChanged(e); + if (Columns.Count > 0) + { + Columns[0].Width = Math.Max(1, ClientSize.Width); + } + } + + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + Invalidate(); + } + + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + Invalidate(); + } + + private VirtualTreeNode NodeAt(Point location) + { + ListViewItem item = GetItemAt(location.X, location.Y); + return item != null && item.Index < _rows.Count ? _rows[item.Index] : null; + } + + private void Toggle(VirtualTreeNode node) + { + if (node.IsExpanded) + { + node.Collapse(); + } + else + { + node.Expand(); + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/DesignFile.cs b/UoFiddler.Plugin.MultiEditor/Classes/DesignFile.cs new file mode 100644 index 00000000..12bcb59b --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/DesignFile.cs @@ -0,0 +1,142 @@ +/*************************************************************************** + * + * "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.Editing; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// + /// What a design file holds: the design as the editor has it, which the client's multi and + /// the export formats cannot keep (its size as drawn, the layers, the floors). + /// + /// Title of the design. + /// Width in cells, as drawn: nothing is cut down to the tiles. + /// Height in cells. + /// Z of the first floor. + /// 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. + internal sealed record DesignData(string Name, int Width, int Height, int FirstFloorZ, + List Levels, List Layers, int ActiveLayer); + + /// + /// The editor's own design file (*.uomd): XML with the size, the floors and one element per + /// layer listing its tiles as id x y z flag extra (id in hex, flag 0 for a dynamic tile). + /// The root element is the header: version is the format version, which says how to + /// read the rest. It counts changes of this format and has nothing to do with the plugin's version. + /// + internal static class DesignFile + { + public const string Extension = "uomd"; + + public const string Filter = "Multi editor design (*.uomd)|*.uomd|All files (*.*)|*.*"; + + /// + /// The format version written to every file. Raise it when the content changes in a way + /// an older editor would misread, and keep reading the versions below it: Load refuses a + /// file with a higher version than this, or with none. + /// + public const int Version = 1; + + /// Largest width or height read: nothing the editor makes comes near it. + private const int _maxSize = 512; + + public static void Save(string path, DesignData design) + { + var root = new XElement("MultiDesign", + new XAttribute("version", Version), + new XAttribute("name", LayerStore.XmlSafe(design.Name ?? string.Empty, string.Empty)), + new XAttribute("width", design.Width), + new XAttribute("height", design.Height), + new XAttribute("firstFloorZ", design.FirstFloorZ)); + + if (design.Levels != null) + { + root.Add(new XElement("Levels", design.Levels.Select(l => + new XElement("Level", new XAttribute("name", LayerStore.XmlSafe(l.Name, "Floor")), new XAttribute("startZ", l.StartZ))))); + } + + var layers = new XElement("Layers", new XAttribute("active", design.ActiveLayer)); + foreach (SavedLayer layer in design.Layers) + { + layers.Add(new XElement("Layer", + new XAttribute("name", LayerStore.XmlSafe(layer.Name, "Layer")), + new XAttribute("visible", layer.Visible), + LayerStore.TilesText(layer.Tiles))); + } + + root.Add(layers); + new XDocument(root).Save(path); + } + + /// Reads a design file. Throws when it is not one or is damaged. + public static DesignData Load(string path) + { + try + { + XElement root = XDocument.Load(path).Root; + if (root == null || root.Name.LocalName != "MultiDesign") + { + throw new InvalidDataException("This is not a multi editor design file."); + } + + int version = (int?)root.Attribute("version") ?? 0; + if (version < 1) + { + throw new InvalidDataException("The design file does not say which format version it is."); + } + + if (version > Version) + { + throw new InvalidDataException( + $"This design is format version {version}, saved by a newer multi editor. This editor reads up to version {Version}."); + } + + int width = (int)root.Attribute("width"); + int height = (int)root.Attribute("height"); + if (width < 1 || height < 1 || width > _maxSize || height > _maxSize) + { + throw new InvalidDataException($"The design's size ({width} x {height}) is not valid."); + } + + List levels = root.Element("Levels")?.Elements("Level") + .Select(l => new LevelDefinition((string)l.Attribute("name") ?? "Floor", (int)l.Attribute("startZ"))).ToList(); + + var layers = new List(); + XElement layersElement = root.Element("Layers"); + foreach (XElement element in layersElement?.Elements("Layer") ?? Enumerable.Empty()) + { + // Not "in the file" in the layers file's sense: every tile is listed here, by cell. + layers.Add(new SavedLayer((string)element.Attribute("name") ?? "Layer", + (bool?)element.Attribute("visible") ?? true, InFile: false, LayerStore.ParseTiles(element.Value))); + } + + if (layers.Count == 0) + { + layers.Add(new SavedLayer(MultiEditorComponentList.BaseLayerName, true, false, new())); + } + + 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); + } + catch (Exception ex) when (ex is XmlException or FormatException or OverflowException or IndexOutOfRangeException or ArgumentNullException) + { + throw new InvalidDataException("The design file is damaged: " + ex.Message, ex); + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/EditCommand.cs b/UoFiddler.Plugin.MultiEditor/Classes/EditCommand.cs index e57ba7ff..3c787b4c 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/EditCommand.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/EditCommand.cs @@ -16,14 +16,15 @@ namespace UoFiddler.Plugin.MultiEditor.Classes /// /// 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) + 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); + 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; @@ -67,8 +68,21 @@ public EditCommand(string action, int width, int height) public int NewHeight { get; set; } + /// + /// The layer list (order and names) before and after the edit; null when the edit did not + /// touch it. + /// + public List<(TileLayer Layer, string Name)> LayersBefore { get; set; } + + public List<(TileLayer Layer, string Name)> LayersAfter { get; set; } + + /// The active layer before and after an edit of the layer list. + public TileLayer ActiveLayerBefore { get; set; } + + public TileLayer ActiveLayerAfter { get; set; } + public bool IsEmpty => Added.Count == 0 && Removed.Count == 0 && Before.Count == 0 && - OldWidth == NewWidth && OldHeight == NewHeight; + OldWidth == NewWidth && OldHeight == NewHeight && LayersBefore == null; public void CaptureAfter() { diff --git a/UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs b/UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs index cca7e3e2..e7f60b81 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/GroupTransform.cs @@ -66,11 +66,15 @@ internal static class GroupTransform /// /// The tiles to add for the transformed group, placed so the group's box keeps its top-left - /// cell. Every tile of is replaced. + /// cell. Every tile of is replaced. With + /// the box is that of the larger group this one is a part of, so parts turned one by one + /// (the layers of a design) stay where they were to each other. /// public static List<(ushort Id, int X, int Y, int Z, bool Invisible, int Extra)> Apply( - IReadOnlyCollection group, HouseStyles styles, RotationTable table, GroupTransformKind kind) + IReadOnlyCollection group, HouseStyles styles, RotationTable table, GroupTransformKind kind, + IReadOnlyCollection frame = null) { + frame ??= group; var m = Matrix(kind); bool mirror = (m.A * m.D) - (m.B * m.C) < 0; bool swaps = SwapsAxes(kind); @@ -115,8 +119,8 @@ string MapDirection(string label) } // Keep the group's top-left: shift by the change of the cell box's corner. - int minX = group.Min(t => t.X), minY = group.Min(t => t.Y); - var mapped = group.Select(t => MapCell(t.X, t.Y)).ToList(); + int minX = frame.Min(t => t.X), minY = frame.Min(t => t.Y); + var mapped = frame.Select(t => MapCell(t.X, t.Y)).ToList(); int shiftX = minX - mapped.Min(c => c.X); int shiftY = minY - mapped.Min(c => c.Y); diff --git a/UoFiddler.Plugin.MultiEditor/Classes/LayerStore.cs b/UoFiddler.Plugin.MultiEditor/Classes/LayerStore.cs new file mode 100644 index 00000000..126f0d43 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/LayerStore.cs @@ -0,0 +1,177 @@ +/*************************************************************************** + * + * "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.Security.Cryptography; +using System.Text; +using System.Xml; +using System.Xml.Linq; +using Ultima; +using UoFiddler.Controls.Classes; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// + /// The layers file: the client's multi cannot hold layers, so they are kept beside the + /// settings, one file per client folder and multi id. Each set of layers names the multi it + /// belongs to by a fingerprint of its tiles, so layers are never put on a multi that was + /// changed elsewhere. The file keeps the last few sets: a multi saved to the client is in + /// memory until the client files are written, and until then the files still hold an older one. + /// + internal static class LayerStore + { + private const string _folderName = "MultiEditorLayers"; + private const int _setsKept = 5; + + /// Where the layers of a client multi are kept. + public static string FilePath(int clientId) + { + // One folder per client install, named by a short hash of its path. + string root = (Files.RootDir ?? string.Empty).TrimEnd('\\', '/').ToUpperInvariant(); + string key = Convert.ToHexString(SHA1.HashData(Encoding.UTF8.GetBytes(root)), 0, 6); + return Path.Combine(Options.AppDataPath ?? string.Empty, _folderName, key, $"0x{clientId:X4}.xml"); + } + + /// + /// 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) + { + string path = FilePath(clientId); + string multi = fingerprint.ToString(CultureInfo.InvariantCulture); + List sets = ReadSets(path).Where(s => (string)s.Attribute("multi") != multi).ToList(); + + bool plain = layers.Count == 1 && layers[0].InFile && layers[0].Visible && + layers[0].Name == MultiEditorComponentList.BaseLayerName; + if (!plain) + { + var set = new XElement("Layers", new XAttribute("multi", multi), new XAttribute("active", activeIndex)); + foreach (SavedLayer layer in layers) + { + set.Add(new XElement("Layer", + new XAttribute("name", XmlSafe(layer.Name, "Layer")), + new XAttribute("visible", layer.Visible), + new XAttribute("inFile", layer.InFile), + TilesText(layer.Tiles))); + } + + sets.Insert(0, set); + } + + if (sets.Count == 0) + { + if (File.Exists(path)) + { + File.Delete(path); + } + + return; + } + + Directory.CreateDirectory(Path.GetDirectoryName(path)); + new XDocument(new XElement("LayerSets", sets.Take(_setsKept))).Save(path); + } + + /// + /// 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) + { + try + { + string multi = fingerprint.ToString(CultureInfo.InvariantCulture); + XElement set = ReadSets(FilePath(clientId)).FirstOrDefault(s => (string)s.Attribute("multi") == multi); + if (set == null) + { + return null; + } + + var layers = new List(); + foreach (XElement element in set.Elements("Layer")) + { + layers.Add(new SavedLayer((string)element.Attribute("name") ?? "Layer", + (bool?)element.Attribute("visible") ?? true, (bool?)element.Attribute("inFile") ?? true, ParseTiles(element.Value))); + } + + return layers.Count == 0 ? null : (layers, (int?)set.Attribute("active") ?? 0); + } + catch (Exception ex) when (ex is FormatException or IndexOutOfRangeException or OverflowException) + { + // A damaged set costs the layers, not the design. + return null; + } + } + + /// The sets of layers in a file, newest first; none when it is missing or damaged. + private static List ReadSets(string path) + { + if (!File.Exists(path)) + { + return new List(); + } + + try + { + return XDocument.Load(path).Root?.Elements("Layers").ToList() ?? new List(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or XmlException) + { + return new List(); + } + } + + /// Tiles as text: id x y z flag extra (id in hex, flag 0 for a dynamic tile), joined by semicolons. + public static string TilesText(List<(ushort Id, int X, int Y, int Z, bool Invisible, int Extra)> tiles) + { + return tiles == null ? string.Empty : string.Join(";", tiles.Select(t => + string.Create(CultureInfo.InvariantCulture, $"{t.Id:X} {t.X} {t.Y} {t.Z} {(t.Invisible ? 0 : 1)} {t.Extra}"))); + } + + /// Reads back. Throws FormatException and the like on damaged text. + public static List<(ushort Id, int X, int Y, int Z, bool Invisible, int Extra)> ParseTiles(string text) + { + var tiles = new List<(ushort, int, int, int, bool, int)>(); + foreach (string record in text.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + string[] parts = record.Split(' '); + tiles.Add((ushort.Parse(parts[0], NumberStyles.HexNumber, CultureInfo.InvariantCulture), + int.Parse(parts[1], CultureInfo.InvariantCulture), int.Parse(parts[2], CultureInfo.InvariantCulture), + int.Parse(parts[3], CultureInfo.InvariantCulture), parts[4] == "0", + int.Parse(parts[5], CultureInfo.InvariantCulture))); + } + + return tiles; + } + + /// A name without the characters XML cannot hold (control characters, half surrogate pairs). + public static string XmlSafe(string name, string whenEmpty) + { + var text = new StringBuilder(name.Length); + for (int i = 0; i < name.Length; i++) + { + if (char.IsHighSurrogate(name[i]) && i + 1 < name.Length && char.IsLowSurrogate(name[i + 1])) + { + text.Append(name[i]).Append(name[++i]); + } + else if (XmlConvert.IsXmlChar(name[i])) + { + text.Append(name[i]); + } + } + + return text.Length > 0 ? text.ToString() : whenEmpty; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs b/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs new file mode 100644 index 00000000..07cece0e --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.Layers.cs @@ -0,0 +1,474 @@ +/*************************************************************************** + * + * "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.Classes +{ + // 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. + internal partial class MultiEditorComponentList + { + public const string BaseLayerName = "Base"; + + /// Largest width or height a design is grown to for tiles only the layers file has. + public const int MaxRestoredSize = 512; + + private List _layers = new() { new TileLayer(BaseLayerName) }; + private TileLayer _activeLayer; + + /// The layers, bottom first. There is always at least one. + public IReadOnlyList Layers => _layers; + + /// The layer new tiles go on. + public TileLayer ActiveLayer + { + get => _activeLayer != null && _layers.Contains(_activeLayer) ? _activeLayer : _layers[^1]; + set => _activeLayer = value; + } + + /// Tiles per layer, counted in one pass. A layer without tiles is not listed. + public Dictionary LayerTileCounts() + { + var counts = new Dictionary(); + foreach (MultiTile tile in RealTiles) + { + counts[tile.Layer] = counts.GetValueOrDefault(tile.Layer) + 1; + } + + return counts; + } + + public int LayerTileCount(TileLayer layer) + { + int count = 0; + foreach (MultiTile tile in RealTiles) + { + if (tile.Layer == layer) + { + ++count; + } + } + + return count; + } + + /// Number of tiles on hidden layers. + public int HiddenLayerTileCount + { + get + { + int count = 0; + foreach (MultiTile tile in RealTiles) + { + if (!tile.Layer.Visible) + { + ++count; + } + } + + return count; + } + } + + /// A layer name not in use yet: the name itself, or the name with the lowest free number. + public string FreeLayerName(string name) + { + if (_layers.All(l => l.Name != name)) + { + return name; + } + + for (int i = 2; ; i++) + { + string numbered = $"{name} {i}"; + if (_layers.All(l => l.Name != numbered)) + { + return numbered; + } + } + } + + // ---------------------------------------------------------------- layer edits + + /// Adds an empty layer above the active one and makes it active. + public TileLayer LayerAdd(string name) + { + BeginEdit("Add Layer"); + RecordLayers(); + var layer = new TileLayer(name); + _layers.Insert(_layers.IndexOf(ActiveLayer) + 1, layer); + ActiveLayer = layer; + EndEdit(); + return layer; + } + + /// Removes a layer with its tiles. The last layer stays. + public bool LayerRemove(TileLayer layer) + { + int index = _layers.IndexOf(layer); + if (index < 0 || _layers.Count == 1) + { + return false; + } + + BeginEdit("Delete Layer"); + RecordLayers(); + foreach (MultiTile tile in RealTiles.Where(t => t.Layer == layer).ToList()) + { + RecordRemove(tile); + } + + _layers.RemoveAt(index); + ActiveLayer = _layers[Math.Max(0, index - 1)]; + EndEdit(); + return true; + } + + /// Adds a copy of a layer, with copies of its tiles, above it and makes it active. + public TileLayer LayerDuplicate(TileLayer layer) + { + int index = _layers.IndexOf(layer); + if (index < 0) + { + return null; + } + + BeginEdit("Duplicate Layer"); + RecordLayers(); + var copy = new TileLayer(FreeLayerName(layer.Name + " copy")) { Visible = layer.Visible }; + _layers.Insert(index + 1, copy); + foreach (MultiTile tile in RealTiles.Where(t => t.Layer == layer).ToList()) + { + RecordNew(tile.Id, tile.X, tile.Y, tile.Z, tile.Invisible, tile.Extra, layer: copy); + } + + ActiveLayer = copy; + EndEdit(); + return copy; + } + + /// + /// Moves a layer's tiles to the layer below it and removes the layer. A tile the lower + /// layer already has (same id, cell and Z) is dropped. + /// + public bool LayerMergeDown(TileLayer layer) + { + int index = _layers.IndexOf(layer); + if (index < 1) + { + return false; + } + + TileLayer below = _layers[index - 1]; + BeginEdit("Merge Layer"); + RecordLayers(); + MoveToLayer(RealTiles.Where(t => t.Layer == layer).ToList(), below); + _layers.RemoveAt(index); + ActiveLayer = below; + EndEdit(); + return true; + } + + /// Moves a layer up (+1) or down (-1) in the list. + public bool LayerMove(TileLayer layer, int delta) + { + int index = _layers.IndexOf(layer); + int target = index + delta; + if (index < 0 || target < 0 || target >= _layers.Count || delta == 0) + { + return false; + } + + BeginEdit("Move Layer"); + RecordLayers(); + _layers.RemoveAt(index); + _layers.Insert(target, layer); + EndEdit(); + return true; + } + + public bool LayerRename(TileLayer layer, string name) + { + if (!_layers.Contains(layer) || string.IsNullOrWhiteSpace(name) || layer.Name == name) + { + return false; + } + + BeginEdit("Rename Layer"); + RecordLayers(); + layer.Name = name; + EndEdit(); + return true; + } + + /// Puts tiles on another layer in one undo step. + public void TilesSetLayer(IEnumerable tiles, TileLayer layer) + { + if (!_layers.Contains(layer)) + { + return; + } + + BeginEdit("Move To Layer"); + MoveToLayer(new List(tiles), layer); + EndEdit(); + } + + private void MoveToLayer(List tiles, TileLayer layer) + { + foreach (MultiTile tile in tiles) + { + if (!Contains(tile) || tile.Layer == layer) + { + continue; + } + + if (Cell(tile.X, tile.Y).Any(o => o.Layer == layer && o.Id == tile.Id && o.Z == tile.Z)) + { + RecordRemove(tile); + } + else + { + RecordChange(tile, tile.Id, tile.X, tile.Y, tile.Z, tile.Invisible, layer); + } + } + } + + // ---------------------------------------------------------------- undo support + + private List<(TileLayer Layer, string Name)> LayerSnapshot() => _layers.Select(l => (l, l.Name)).ToList(); + + /// Call inside an edit before the layer list or a layer name changes. + private void RecordLayers() + { + if (_current.LayersBefore == null) + { + _current.LayersBefore = LayerSnapshot(); + _current.ActiveLayerBefore = ActiveLayer; + } + } + + private void CaptureLayersAfter(EditCommand command) + { + if (command.LayersBefore == null) + { + return; + } + + List<(TileLayer Layer, string Name)> after = LayerSnapshot(); + if (after.SequenceEqual(command.LayersBefore)) + { + command.LayersBefore = null; + } + else + { + command.LayersAfter = after; + command.ActiveLayerAfter = ActiveLayer; + } + } + + private void RestoreLayerList(List<(TileLayer Layer, string Name)> layers) + { + _layers = layers.Select(l => l.Layer).ToList(); + foreach ((TileLayer layer, string name) in layers) + { + layer.Name = name; + } + } + + // ---------------------------------------------------------------- layers file + + /// + /// The cell the saved multi counts its tile offsets from (the same rule the client list + /// uses when it is made from this design). A saved multi is cut down to its tiles, so + /// cells shift when it is opened again, but a tile's offset from this cell stays. The + /// layers file therefore keeps offsets, not cells. + /// + public (int X, int Y) SaveOrigin + { + get + { + int x = (int)Math.Round(Width / 2.0) - 1; + int y = (int)Math.Round(Height / 2.0) - 1; + return (x < 0 ? Width / 2 : x, y < 0 ? Height / 2 : y); + } + } + + /// + /// A number that names the tiles writes, by their offsets from + /// and whatever their order. The layers file keeps it to know + /// the multi it was saved with. + /// + public long Fingerprint((int X, int Y) origin, bool includeHidden = true) + { + long sum = 0; + var seen = new HashSet<(ushort, int, int, int)>(); + foreach (MultiTile tile in RealTiles) + { + if ((!includeHidden && !tile.Layer.Visible) || !seen.Add((tile.Id, tile.X, tile.Y, tile.Z))) + { + continue; + } + + unchecked + { + long h = (tile.Id * 73856093L) ^ ((tile.X - origin.X) * 19349663L) ^ ((tile.Y - origin.Y) * 83492791L) ^ (tile.Z * 2654435761L); + sum += (h * 1099511628211L) + (h >> 7) + 1; + } + } + + return sum; + } + + /// + /// The layers as the layers file keeps them, tiles as offsets from . + /// With false the hidden layers are marked as not in the + /// saved multi. + /// + public List SaveLayers(bool includeHidden) + { + (int ox, int oy) = SaveOrigin; + var result = new List(); + for (int i = 0; i < _layers.Count; i++) + { + TileLayer layer = _layers[i]; + bool inFile = includeHidden || layer.Visible; + // The first layer takes whatever the others do not claim, so it lists only the + // tiles another layer has too: the multi holds such a tile once. + var tiles = RealTiles + .Where(t => t.Layer == layer && (i > 0 || !inFile || Cell(t.X, t.Y).Any(o => o != t && o.Id == t.Id && o.Z == t.Z))) + .Select(t => (t.Id, t.X - ox, t.Y - oy, t.Z, t.Invisible, t.Extra)).ToList(); + result.Add(new SavedLayer(layer.Name, layer.Visible, inFile, tiles)); + } + + return result; + } + + /// The layers with all their tiles by cell, as a design file keeps them. + public List DesignLayers() + { + return _layers.Select(layer => new SavedLayer(layer.Name, layer.Visible, false, + RealTiles.Where(t => t.Layer == layer).Select(t => (t.Id, t.X, t.Y, t.Z, t.Invisible, t.Extra)).ToList())).ToList(); + } + + /// + /// Puts a freshly loaded design back on its saved layers. Not an undo step. + /// is the cell of the loaded multi the saved offsets count from + /// (its centre). A layer that was saved with the multi claims its tiles by id, cell and Z, + /// and what the multi no longer has is dropped; a layer that was left out of the multi + /// gets its tiles back from the file, and the design grows when they reach past its edge. + /// Tiles nobody claims stay on the first layer. + /// + public void RestoreLayers(IReadOnlyList saved, int activeIndex, (int X, int Y) origin) + { + if (saved == null || saved.Count == 0) + { + return; + } + + // Room for the tiles only the layers file has: everything moves right and down by the shift. + var extra = saved.Where(l => !l.InFile).SelectMany(l => l.Tiles ?? new()).ToList(); + if (extra.Count > 0) + { + int shiftX = Math.Max(0, -(extra.Min(t => t.X) + origin.X)); + int shiftY = Math.Max(0, -(extra.Min(t => t.Y) + origin.Y)); + int width = Math.Max(Width + shiftX, extra.Max(t => t.X) + origin.X + shiftX + 1); + int height = Math.Max(Height + shiftY, extra.Max(t => t.Y) + origin.Y + shiftY + 1); + if (width > MaxRestoredSize || height > MaxRestoredSize) + { + // No design is that large: the file is damaged. The design opens without layers. + return; + } + + if (shiftX != 0 || shiftY != 0 || width != Width || height != Height) + { + var all = new List(RealTiles); + foreach (MultiTile tile in all) + { + tile.X += shiftX; + tile.Y += shiftY; + } + + RebuildGrid(width, height, all); + origin = (origin.X + shiftX, origin.Y + shiftY); + } + } + + TileLayer first = _layers[0]; + first.Name = saved[0].Name; + first.Visible = saved[0].Visible; + _layers = new List { first }; + for (int i = 1; i < saved.Count; i++) + { + var layer = new TileLayer(saved[i].Name) { Visible = saved[i].Visible }; + _layers.Add(layer); + if (!saved[i].InFile) + { + continue; + } + + foreach ((ushort id, int dx, int dy, int z, _, _) in saved[i].Tiles ?? new()) + { + int x = dx + origin.X; + int y = dy + origin.Y; + if (InBounds(x, y) && Cell(x, y).FirstOrDefault(t => t.Layer == first && t.Id == id && t.Z == z) is { } tile) + { + tile.Layer = layer; + } + } + } + + // A tile that sat on two layers is in the multi once and went to one of them: the + // other layers that list it get a copy. + for (int i = 0; i < saved.Count; i++) + { + if (!saved[i].InFile) + { + continue; + } + + foreach ((ushort id, int dx, int dy, int z, bool invisible, int extraField) in saved[i].Tiles ?? new()) + { + int x = dx + origin.X; + int y = dy + origin.Y; + if (InBounds(x, y) && Cell(x, y).All(t => t.Layer != _layers[i] || t.Id != id || t.Z != z) && + Cell(x, y).Any(t => t.Id == id && t.Z == z)) + { + GridInsert(new MultiTile(id, x, y, z, invisible) { Extra = extraField, Solver = ++_solverCounter, Layer = _layers[i] }); + } + } + } + + // After the claims, so a claim never takes a tile that only the layers file has. + for (int i = 0; i < saved.Count; i++) + { + if (saved[i].InFile) + { + continue; + } + + foreach ((ushort id, int dx, int dy, int z, bool invisible, int extraField) in saved[i].Tiles ?? new()) + { + GridInsert(new MultiTile(id, dx + origin.X, dy + origin.Y, ClampZ(z), invisible) + { + Extra = extraField, + Solver = ++_solverCounter, + Layer = _layers[i] + }); + } + } + + ActiveLayer = _layers[Math.Clamp(activeIndex, 0, _layers.Count - 1)]; + RecalculateMinMax(); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs b/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs index 0d7ec153..b11941e1 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/MultiEditorComponentList.cs @@ -130,14 +130,18 @@ public IEnumerable RealTiles /// /// Export to given multi id /// - public void AddToSdkComponentList(int id) + public void AddToSdkComponentList(int id, bool includeHidden = true) { - Multis.Add(id, ConvertToSdk()); + Multis.Add(id, ConvertToSdk(includeHidden)); Options.ChangedUltimaClass["Multis"] = true; ControlEvents.FireMultiChangeEvent(this, id); } - public MultiComponentList ConvertToSdk() + /// + /// The design as the client keeps it. Tiles on hidden layers can be left out, and a tile + /// that sits on two layers with the same id, cell and Z is written once. + /// + public MultiComponentList ConvertToSdk(bool includeHidden = true) { var tiles = new MTileList[Width][]; for (int x = 0; x < Width; ++x) @@ -149,22 +153,31 @@ public MultiComponentList ConvertToSdk() } } + int count = 0; + var written = new HashSet<(ushort, int, int, int)>(); foreach (MultiTile tile in RealTiles) { + if ((!includeHidden && !tile.Layer.Visible) || !written.Add((tile.Id, tile.X, tile.Y, tile.Z))) + { + continue; + } + tiles[tile.X][tile.Y].Add(tile.Id, (sbyte)tile.Z, tile.Invisible ? (sbyte)0 : (sbyte)1, tile.Extra); + ++count; } - return new MultiComponentList(tiles, _tileCount, Width, Height); + return new MultiComponentList(tiles, count, Width, Height); } public bool InBounds(int x, int y) => x >= 0 && x < Width && y >= 0 && y < Height; /// - /// False for tiles hidden one by one and, while walls are hidden, for tiles flagged as walls. + /// False for tiles hidden one by one, tiles on a hidden layer and, while walls are hidden, + /// for tiles flagged as walls. /// public bool IsShown(MultiTile tile) { - return !tile.Hidden && !(_parent.HideWalls && (TileData.ItemTable[tile.Id].Flags & TileFlag.Wall) != 0); + return !tile.Hidden && tile.Layer.Visible && !(_parent.HideWalls && (TileData.ItemTable[tile.Id].Flags & TileFlag.Wall) != 0); } public int HiddenCount @@ -538,7 +551,7 @@ public void ReplaceTiles(IEnumerable remove, IEnumerable<(ushort Id, /// step (rotate and mirror). Returns the tiles added. /// public List ReplaceTiles(IEnumerable remove, - IEnumerable<(ushort Id, int X, int Y, int Z, bool Invisible, int Extra)> add, string action, int width, int height) + IEnumerable<(ushort Id, int X, int Y, int Z, bool Invisible, int Extra, TileLayer Layer)> add, string action, int width, int height) { BeginEdit(action); foreach (MultiTile tile in new List(remove)) @@ -560,9 +573,9 @@ public List ReplaceTiles(IEnumerable remove, } var added = new List(); - foreach (var (id, x, y, z, invisible, extra) in add) + foreach (var (id, x, y, z, invisible, extra, layer) in add) { - if (RecordNew(id, x, y, z, invisible, extra) is { } tile) + if (RecordNew(id, x, y, z, invisible, extra, layer: layer) is { } tile) { added.Add(tile); } @@ -573,11 +586,11 @@ public List ReplaceTiles(IEnumerable remove, } /// - /// Adds a batch of tiles in a single undo step (used by copy/paste). + /// Adds a batch of tiles in a single undo step (paste, blueprint, duplicate, repeat). /// - public void TileAddBatch(List<(ushort id, int x, int y, int z, bool invisible, int extra)> tiles) + public void TileAddBatch(List<(ushort id, int x, int y, int z, bool invisible, int extra)> tiles, string action = "Paste") { - BeginEdit("Paste"); + BeginEdit(action); foreach (var (id, x, y, z, invisible, extra) in tiles) { RecordNew(id, x, y, z, invisible, extra); @@ -691,6 +704,12 @@ private void Apply(EditCommand command, bool undo) } } + if ((undo ? command.LayersBefore : command.LayersAfter) is { } layers) + { + RestoreLayerList(layers); + _activeLayer = undo ? command.ActiveLayerBefore : command.ActiveLayerAfter; + } + RecalculateMinMax(); } @@ -707,6 +726,7 @@ private void EndEdit() command.NewWidth = Width; command.NewHeight = Height; command.CaptureAfter(); + CaptureLayersAfter(command); if (command.IsEmpty) { return; @@ -723,8 +743,11 @@ private void EndEdit() /// Adds a new tile unless it is out of bounds or the same id already sits at the same Z in /// that cell. With , other tiles of the same kind at that Z go /// first: a flat tile replaces flat tiles, a tile with height replaces tiles with height. + /// The tile goes on , or on the active layer, which is shown if it + /// was hidden so what is built can be seen. Layers do not see each other's tiles: the same + /// tile may sit on two of them. /// - private MultiTile RecordNew(ushort id, int x, int y, int z, bool invisible, int extra, bool replace = false) + private MultiTile RecordNew(ushort id, int x, int y, int z, bool invisible, int extra, bool replace = false, TileLayer layer = null) { if (!InBounds(x, y)) { @@ -737,22 +760,28 @@ private MultiTile RecordNew(ushort id, int x, int y, int z, bool invisible, int bool flat = TileData.ItemTable[id].Height == 0; foreach (MultiTile other in GetTilesAt(x, y)) { - if (other.Z == z && other.Id != id && (other.Height == 0) == flat) + if (other.Z == z && other.Id != id && (other.Height == 0) == flat && IsShown(other)) { RecordRemove(other); } } } + if (layer == null) + { + layer = ActiveLayer; + layer.Visible = true; + } + foreach (MultiTile other in Cell(x, y)) { - if (other.Id == id && other.Z == z) + if (other.Id == id && other.Z == z && other.Layer == layer) { return null; } } - var tile = new MultiTile(id, x, y, z, invisible) { Extra = extra, Solver = ++_solverCounter }; + var tile = new MultiTile(id, x, y, z, invisible) { Extra = extra, Solver = ++_solverCounter, Layer = layer }; GridInsert(tile); _current.Added.Add(tile); return tile; @@ -779,9 +808,9 @@ private void RecordRemove(MultiTile tile) _current.Removed.Add(tile); } - private void RecordChange(MultiTile tile, ushort id, int x, int y, int z, bool invisible) + private void RecordChange(MultiTile tile, ushort id, int x, int y, int z, bool invisible, TileLayer layer = null) { - var target = new TileState(id, x, y, z, invisible); + var target = new TileState(id, x, y, z, invisible, layer ?? tile.Layer); if (TileState.Of(tile) == target || !InBounds(x, y)) { return; @@ -841,6 +870,7 @@ private void RebuildGrid(int width, int height, IEnumerable tiles) { if (InBounds(tile.X, tile.Y)) { + tile.Layer ??= _layers[0]; Cell(tile.X, tile.Y).Add(tile); ++_tileCount; } diff --git a/UoFiddler.Plugin.MultiEditor/Classes/MultiTile.cs b/UoFiddler.Plugin.MultiEditor/Classes/MultiTile.cs index bdacb6ab..b424e4fd 100644 --- a/UoFiddler.Plugin.MultiEditor/Classes/MultiTile.cs +++ b/UoFiddler.Plugin.MultiEditor/Classes/MultiTile.cs @@ -96,6 +96,9 @@ public int Z /// public int Extra { get; set; } + /// The layer the tile is on; set when the tile joins a design. + public TileLayer Layer { get; set; } + public bool Walkable { get; private set; } public bool DoubleSurface { get; private set; } diff --git a/UoFiddler.Plugin.MultiEditor/Classes/TileLayer.cs b/UoFiddler.Plugin.MultiEditor/Classes/TileLayer.cs new file mode 100644 index 00000000..98c0dc11 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Classes/TileLayer.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. + * + ***************************************************************************/ + +using System.Collections.Generic; + +namespace UoFiddler.Plugin.MultiEditor.Classes +{ + /// + /// A named group of tiles in a design. Every tile is on exactly one layer and new tiles go on + /// the active one. Layers only exist in the editor: the client's multi has no notion of them. + /// + public sealed class TileLayer + { + public TileLayer(string name) + { + Name = name; + } + + public string Name { get; set; } + + /// Hidden layers are not drawn, hovered, selected or removed. View only: not an undo step. + public bool Visible { get; set; } = true; + + 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/Editing/EditorSession.Commands.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs index 89a19463..0712822d 100644 --- a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.Commands.cs @@ -104,6 +104,260 @@ public void Paste() 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; + + /// The layer new tiles go on. Choosing a hidden layer shows it. + public TileLayer ActiveLayer + { + get => CompList.ActiveLayer; + set + { + if (value == null || !CompList.Layers.Contains(value) || value == CompList.ActiveLayer) + { + return; + } + + CompList.ActiveLayer = value; + if (!value.Visible) + { + SetLayerVisible(value, true); + } + else + { + LayersChanged?.Invoke(); + } + } + } + + /// Shows or hides a layer. Hidden tiles leave the selection. View only: not an undo step. + public void SetLayerVisible(TileLayer layer, bool visible) + { + if (layer == null || layer.Visible == visible) + { + return; + } + + layer.Visible = visible; + LayersChanged?.Invoke(); + OnViewChanged(); + } + + /// Shows only this layer, or every layer when it is already the only one shown. + public void SoloLayer(TileLayer layer) + { + if (!CompList.Layers.Contains(layer)) + { + return; + } + + bool alone = layer.Visible && CompList.Layers.All(l => l == layer || !l.Visible); + foreach (TileLayer other in CompList.Layers) + { + other.Visible = alone || other == layer; + } + + LayersChanged?.Invoke(); + OnViewChanged(); + } + + /// Adds an empty layer above the active one and makes it active. + public TileLayer AddLayer(string name = null) + { + TileLayer layer = CompList.LayerAdd(CompList.FreeLayerName(string.IsNullOrWhiteSpace(name) ? "Layer" : name.Trim())); + AfterEdit(); + return layer; + } + + /// Deletes a layer with its tiles. False for the last layer, which stays. + public bool RemoveLayer(TileLayer layer) + { + return LayerEdit(CompList.LayerRemove(layer)); + } + + public bool DuplicateLayer(TileLayer layer) + { + return LayerEdit(CompList.LayerDuplicate(layer) != null); + } + + /// Moves a layer's tiles to the layer below it and removes the layer. + public bool MergeLayerDown(TileLayer layer) + { + return LayerEdit(CompList.LayerMergeDown(layer)); + } + + /// Moves a layer up (+1) or down (-1) in the list. + public bool MoveLayer(TileLayer layer, int delta) + { + return LayerEdit(CompList.LayerMove(layer, delta)); + } + + public bool RenameLayer(TileLayer layer, string name) + { + return LayerEdit(CompList.LayerRename(layer, name?.Trim())); + } + + /// Puts the selected tiles on a layer. + public void MoveSelectionToLayer(TileLayer layer) + { + if (_selection.Count == 0 || layer == null) + { + return; + } + + CompList.TilesSetLayer(_selection.ToList(), layer); + AfterEdit(); + OnViewChanged(); + } + + /// Selects every editable tile of a layer. + public void SelectLayer(TileLayer layer, bool add = false) + { + SelectWhere(t => t.Layer == layer, add); + } + + /// Puts a freshly loaded design back on its saved layers (see the layers file). + public void RestoreLayers(IReadOnlyList saved, int activeIndex, (int X, int Y) origin) + { + CompList.RestoreLayers(saved, activeIndex, origin); + RebuildLevels(); + LayersChanged?.Invoke(); + OnViewChanged(); + } + + // ---------------------------------------------------------------- design file + + /// The design as a design file keeps it: size, floors, layers and tiles. + public DesignData ToDesign() + { + return new DesignData(Title, CompList.Width, CompList.Height, FirstFloorZ, + CustomLevels ? _levelDefinitions.ToList() : null, CompList.DesignLayers(), + CompList.Layers.ToList().IndexOf(CompList.ActiveLayer)); + } + + /// Opens what a design file holds as this session's document. + public void LoadDesign(DesignData design) + { + NewBlank(design.Width, design.Height, design.FirstFloorZ); + CompList.RestoreLayers(design.Layers, design.ActiveLayer, (0, 0)); + if (design.Levels != null) + { + SetLevelDefinitions(design.Levels); + } + + RebuildLevels(); + Modified = false; + DocumentChanged?.Invoke(); + LayersChanged?.Invoke(); + OnViewChanged(); + } + + private bool LayerEdit(bool done) + { + if (done) + { + AfterEdit(); + } + + return done; + } + + // ---------------------------------------------------------------- repeat + + /// + /// Copies of tiles along a direction: copy i (1 to ) of every tile + /// is moved by i times the step. Copies outside the multi or the Z range are left out and + /// counted in . + /// + public static List<(ushort id, int x, int y, int z, bool invisible, int extra)> RepeatTiles( + IEnumerable source, int copies, int dx, int dy, int dz, int width, int height, out int skipped) + { + var result = new List<(ushort, int, int, int, bool, int)>(); + skipped = 0; + if (dx == 0 && dy == 0 && dz == 0) + { + return result; + } + + List tiles = source.OrderBy(t => t.X).ThenBy(t => t.Y).ThenBy(t => t.Z).ToList(); + for (int i = 1; i <= copies; i++) + { + foreach (MultiTile tile in tiles) + { + int x = tile.X + (i * dx); + int y = tile.Y + (i * dy); + int z = tile.Z + (i * dz); + if (x < 0 || y < 0 || x >= width || y >= height || z < sbyte.MinValue || z > sbyte.MaxValue) + { + skipped++; + continue; + } + + result.Add((tile.Id, x, y, z, tile.Invisible, tile.Extra)); + } + } + + return result; + } + + private List<(ushort id, int x, int y, int z, bool invisible, int extra)> RepeatOfSelection( + int copies, int dx, int dy, int dz, out int skipped) + { + return RepeatTiles(_selection, copies, dx, dy, dz, CompList.Width, CompList.Height, out skipped); + } + + /// + /// Shows the copies a repeat of the selection would add, as ghosts, until + /// . Returns how many tiles it adds and how many fall outside. + /// + public (int Added, int Skipped) PreviewRepeat(int copies, int dx, int dy, int dz) + { + if (_temporaryTool != _repeatTool) + { + CancelTool(); + _stampLabel = "Repeat"; + _temporaryTool = _repeatTool; + ToolChanged?.Invoke(); + } + + var tiles = RepeatOfSelection(copies, dx, dy, dz, out int skipped); + _repeatTool.Show(tiles); + Invalidated?.Invoke(); + return (tiles.Count, skipped); + } + + public void EndRepeatPreview() + { + if (_temporaryTool == _repeatTool) + { + CancelTool(); + } + } + + /// True while the repeat dialog's copies are shown on the canvas. + public bool PreviewingRepeat => _temporaryTool == _repeatTool; + + /// Adds copies of the selection along a direction in one undo step. The selection stays as it is. + public void RepeatSelection(int copies, int dx, int dy, int dz) + { + EndRepeatPreview(); + var tiles = RepeatOfSelection(copies, dx, dy, dz, out _); + if (tiles.Count == 0) + { + return; + } + + CompList.TileAddBatch(tiles, "Repeat Selection"); + 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() { @@ -281,7 +535,15 @@ public string TransformGroup(GroupTransformKind kind) } _rotationTable ??= RotationTable.LoadDefault(); - var add = GroupTransform.Apply(group, HouseStyles, _rotationTable, kind); + + // Turned layer by layer, so every new tile is on the layer of the tiles it came from, + // all about the corner of the whole group. + var add = new List<(ushort Id, int X, int Y, int Z, bool Invisible, int Extra, TileLayer Layer)>(); + foreach (IGrouping layer in group.GroupBy(t => t.Layer)) + { + add.AddRange(GroupTransform.Apply(layer.ToList(), HouseStyles, _rotationTable, kind, group) + .Select(t => (t.Id, t.X, t.Y, t.Z, t.Invisible, t.Extra, layer.Key))); + } int width = CompList.Width; int height = CompList.Height; @@ -295,7 +557,7 @@ public string TransformGroup(GroupTransformKind kind) // New wall posts may reach a cell past the old edge: keep everything inside. int shiftX = Math.Max(0, -add.Min(t => t.X)); int shiftY = Math.Max(0, -add.Min(t => t.Y)); - add = add.Select(t => (t.Id, t.X + shiftX, t.Y + shiftY, t.Z, t.Invisible, t.Extra)).ToList(); + add = add.Select(t => (t.Id, t.X + shiftX, t.Y + shiftY, t.Z, t.Invisible, t.Extra, t.Layer)).ToList(); width = Math.Max(width, add.Max(t => t.X) + 1); height = Math.Max(height, add.Max(t => t.Y) + 1); } diff --git a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs index e14adb9d..2fa581f9 100644 --- a/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs +++ b/UoFiddler.Plugin.MultiEditor/Editing/EditorSession.cs @@ -55,9 +55,13 @@ internal sealed partial class EditorSession : IEditorContext, IMultiViewSettings private readonly Dictionary _tools = new Dictionary(); private readonly ArtMasks _masks; private readonly PasteTool _pasteTool; + private readonly RepeatPreviewTool _repeatTool; private EditorTool _temporaryTool; + private string _stampLabel = "Paste"; + private bool _pickClick; private ToolKind _toolKind = ToolKind.Select; + private ToolKind _lastTileTool = ToolKind.Draw; private Point _mouseLoc; private bool _mouseInside; private (int X, int Y, int Z) _cursorCell = (int.MinValue, int.MinValue, int.MinValue); @@ -92,6 +96,7 @@ public EditorSession(ArtMasks masks, HouseStyles houseStyles) _tools[ToolKind.Foundation] = new FoundationTool(this); _tools[ToolKind.FloorPattern] = new FloorPatternTool(this); _pasteTool = new PasteTool(this); + _repeatTool = new RepeatPreviewTool(this); CompList = new MultiEditorComponentList(0, 0, this); } @@ -111,6 +116,9 @@ public EditorSession(ArtMasks masks, HouseStyles houseStyles) public event Action ToolChanged; + /// The layer list, a layer's name or visibility, the active layer or the tile counts changed. + public event Action LayersChanged; + public event Action DrawTileChanged; /// A view option changed (floor, level, height limit, filters). @@ -187,6 +195,7 @@ private void SetDocument(MultiEditorComponentList list) RebuildLevels(); DocumentChanged?.Invoke(); + LayersChanged?.Invoke(); SelectionChanged?.Invoke(); ViewChanged?.Invoke(); Invalidated?.Invoke(); @@ -336,6 +345,11 @@ public ToolKind Tool { CancelTool(); _toolKind = value; + if (IsTileTool(value)) + { + _lastTileTool = value; + } + ToolChanged?.Invoke(); Invalidated?.Invoke(); } @@ -343,6 +357,20 @@ public ToolKind Tool public EditorTool ActiveTool => _temporaryTool ?? _tools[_toolKind]; + /// True for the tools that place the draw tile (draw, rectangle, line). + public static bool IsTileTool(ToolKind kind) + { + return kind is ToolKind.Draw or ToolKind.RectFill or ToolKind.Line; + } + + /// + /// True while Alt is held with a draw tile tool and nothing is being dragged: a click then + /// picks the tile under the cursor instead of placing one, and the tool shows no preview. + /// + public bool PickingWithAlt => + _temporaryTool == null && IsTileTool(_toolKind) && !_tools[_toolKind].IsDragging && + (Control.ModifierKeys & Keys.Alt) != 0; + /// The bordered floor laid by the floor pattern tool, or null. public FloorPattern FloorPattern { get; set; } @@ -355,9 +383,12 @@ public void ToolOptionsChanged() Invalidated?.Invoke(); } - /// True while a paste is waiting to be placed. + /// True while tiles are on the cursor to be placed (paste, blueprint, duplicate) or a repeat is previewed. public bool Pasting => _temporaryTool != null; + /// What is on the cursor while : "Paste", "Blueprint", "Duplicate"... + public string StampLabel => _stampLabel; + public ushort DrawTileId => _drawTileId; public int BrushSize { get; set; } = 1; @@ -373,14 +404,26 @@ public void ToolOptionsChanged() /// Drops a drag, a pending paste or any other half-done tool action. public void CancelTool() { + bool wasTemporary = _temporaryTool != null; _temporaryTool?.Cancel(); _temporaryTool = null; + _pickClick = false; + if (wasTemporary) + { + // Esc and right click are the only ways out of a stamp: the labels follow. + ToolChanged?.Invoke(); + } + _tools[_toolKind].Cancel(); Invalidated?.Invoke(); } - /// Starts placing a group of tiles with the mouse. - public void BeginPaste(List tiles) + /// + /// Starts placing a group of tiles with the mouse. They stay on the cursor for more + /// placements until the tool is cancelled. names what is placed, + /// for the tool label and the undo step. + /// + public void BeginPaste(List tiles, string label = "Paste") { if (tiles == null || tiles.Count == 0 || !HasDocument) { @@ -388,7 +431,8 @@ public void BeginPaste(List tiles) } CancelTool(); - _pasteTool.Begin(tiles); + _stampLabel = label; + _pasteTool.Begin(tiles, label); _temporaryTool = _pasteTool; ToolChanged?.Invoke(); Invalidated?.Invoke(); @@ -401,6 +445,16 @@ public void SetDrawTile(ushort id) Invalidated?.Invoke(); } + /// Makes a tile picked on the canvas the draw tile; the pick tool hands over to the draw tool used last. + public void PickDrawTile(ushort id) + { + SetDrawTile(id); + if (_temporaryTool == null && _toolKind == ToolKind.Pipette) + { + Tool = _lastTileTool; + } + } + // ---------------------------------------------------------------- selection and hover public MultiTile HoverTile { get; private set; } @@ -608,7 +662,14 @@ public void PointerDown(Point world, MouseEventArgs e) { UpdateHover(); UpdateCursorCell(); - ActiveTool.OnMouseDown(e); + + // 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(); } } @@ -631,7 +692,18 @@ public void PointerUp(Point world, MouseEventArgs e) } else if (e.Button == MouseButtons.Left) { - ActiveTool.OnMouseUp(e); + if (_pickClick) + { + _pickClick = false; + if (HoverTile != null) + { + PickDrawTile(HoverTile.Id); + } + } + else + { + ActiveTool.OnMouseUp(e); + } } Invalidated?.Invoke(); @@ -685,7 +757,7 @@ public void AfterEdit(int? raiseTo = null) } // Tiles removed by the edit (or by undo) are no longer selectable. - if (_selection.RemoveWhere(t => !CompList.Contains(t)) > 0) + if (_selection.RemoveWhere(t => !CompList.Contains(t) || !CompList.IsShown(t)) > 0) { SelectionChanged?.Invoke(); } @@ -706,18 +778,12 @@ public void AfterEdit(int? raiseTo = null) _cursorCell = (int.MinValue, int.MinValue, int.MinValue); UpdateCursorCell(); DocumentChanged?.Invoke(); + LayersChanged?.Invoke(); Invalidated?.Invoke(); } void IEditorContext.RecordRecentTile(ushort id) => TileUsed?.Invoke(id); - void IEditorContext.EndTemporaryTool() - { - _temporaryTool = null; - ToolChanged?.Invoke(); - Invalidated?.Invoke(); - } - // ---------------------------------------------------------------- coordinates /// World position of the top corner of a cell's floor diamond at height z. diff --git a/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs b/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs index 096d5bfd..0b725215 100644 --- a/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs +++ b/UoFiddler.Plugin.MultiEditor/Rendering/SceneRenderer.cs @@ -123,7 +123,10 @@ public void Draw(EditorSession session, Camera2D camera, Size viewport) } // Tool overlay: sprites first (ghost tiles), then the lines on top of them. - session.ActiveTool.PaintOverlay(this); + if (!session.PickingWithAlt) + { + session.ActiveTool.PaintOverlay(this); + } LastSpriteCount += _sprites.Count; _sprites.Flush(_atlas, camera, viewport); _lines.Flush(camera, viewport); diff --git a/UoFiddler.Plugin.MultiEditor/Tools/EditorTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/EditorTool.cs index 38c5bbe7..356e1f13 100644 --- a/UoFiddler.Plugin.MultiEditor/Tools/EditorTool.cs +++ b/UoFiddler.Plugin.MultiEditor/Tools/EditorTool.cs @@ -83,7 +83,8 @@ internal interface IEditorContext void ToggleSelected(MultiTile tile); - void SetDrawTile(ushort id); + /// Makes a tile picked on the canvas the draw tile; the pick tool then hands over to the draw tool used last. + void PickDrawTile(ushort id); /// /// Call after an edit: refreshes the height slider, minimap and hover. With @@ -92,9 +93,6 @@ internal interface IEditorContext void AfterEdit(int? raiseTo = null); void RecordRecentTile(ushort id); - - /// Leaves a temporary tool (paste) for the tool chosen before it. - void EndTemporaryTool(); } /// diff --git a/UoFiddler.Plugin.MultiEditor/Tools/HousePartTools.cs b/UoFiddler.Plugin.MultiEditor/Tools/HousePartTools.cs index 1706cb80..80547dc7 100644 --- a/UoFiddler.Plugin.MultiEditor/Tools/HousePartTools.cs +++ b/UoFiddler.Plugin.MultiEditor/Tools/HousePartTools.cs @@ -195,7 +195,7 @@ protected override (List Remove, List<(ushort Id, int X, int Y, int Z foreach (MultiTile tile in list.GetTilesAt(x, y)) { - if (Context.HouseStyles.TryGetRole(tile.Id, out HouseStyle owner, out _) && owner.Kind == HousePartKind.Roof) + if (list.IsShown(tile) && Context.HouseStyles.TryGetRole(tile.Id, out HouseStyle owner, out _) && owner.Kind == HousePartKind.Roof) { remove.Add(tile); } @@ -212,7 +212,7 @@ protected override (List Remove, List<(ushort Id, int X, int Y, int Z { foreach (MultiTile tile in list.GetTilesAt(x, y)) { - if (IsCap(tile.Id)) + if (IsCap(tile.Id) && list.IsShown(tile)) { remove.Add(tile); } diff --git a/UoFiddler.Plugin.MultiEditor/Tools/PasteTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/PasteTool.cs index c1ef7675..86bdde18 100644 --- a/UoFiddler.Plugin.MultiEditor/Tools/PasteTool.cs +++ b/UoFiddler.Plugin.MultiEditor/Tools/PasteTool.cs @@ -98,12 +98,13 @@ public static List Parse(string text) } /// - /// Temporary tool after Ctrl+V: shows the clipboard under the cursor and places it on click. - /// Esc or a right click leaves it. + /// Temporary tool for a paste, a blueprint or a duplicate: shows the tiles under the cursor and + /// places them on every click, each click its own undo step. Esc or a right click leaves it. /// internal sealed class PasteTool : EditorTool { private IReadOnlyList _tiles = new List(); + private string _action = "Paste"; public PasteTool(IEditorContext context) : base(context) { @@ -111,17 +112,19 @@ public PasteTool(IEditorContext context) : base(context) public override bool TracksCursorCell => true; - public void Begin(IReadOnlyList tiles) + /// The tiles to place. + /// Name of the undo step each placement makes. + public void Begin(IReadOnlyList tiles, string action) { _tiles = tiles; + _action = action; } public override void OnMouseUp(MouseEventArgs e) { Context.CellAt(Context.MouseLoc, out int x, out int y, out int z); - Context.CompList.TileAddBatch(_tiles.Select(t => (t.Id, x + t.Dx, y + t.Dy, z + t.Dz, t.Invisible, t.Extra)).ToList()); + Context.CompList.TileAddBatch(_tiles.Select(t => (t.Id, x + t.Dx, y + t.Dy, z + t.Dz, t.Invisible, t.Extra)).ToList(), _action); Context.AfterEdit(); - Context.EndTemporaryTool(); } public override void PaintOverlay(IToolOverlay overlay) diff --git a/UoFiddler.Plugin.MultiEditor/Tools/RepeatPreviewTool.cs b/UoFiddler.Plugin.MultiEditor/Tools/RepeatPreviewTool.cs new file mode 100644 index 00000000..4bd8aa02 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/Tools/RepeatPreviewTool.cs @@ -0,0 +1,52 @@ +/*************************************************************************** + * + * "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.Tools +{ + /// + /// Temporary tool while the repeat dialog is open: shows the copies it would add. Clicks do nothing. + /// + internal sealed class RepeatPreviewTool : EditorTool + { + /// Most tiles shown as ghosts; a larger repeat is still made, only not previewed. + public const int MaxGhosts = 20000; + + private IReadOnlyList<(ushort id, int x, int y, int z, bool invisible, int extra)> _tiles = + new List<(ushort, int, int, int, bool, int)>(); + + public RepeatPreviewTool(IEditorContext context) : base(context) + { + } + + public void Show(IReadOnlyList<(ushort id, int x, int y, int z, bool invisible, int extra)> tiles) + { + _tiles = tiles; + } + + public override void PaintOverlay(IToolOverlay overlay) + { + if (_tiles.Count > MaxGhosts) + { + return; + } + + foreach ((ushort id, int x, int y, int z, _, _) in _tiles) + { + overlay.Ghost(id, x, y, z); + } + } + + public override void Cancel() + { + _tiles = new List<(ushort, int, int, int, bool, int)>(); + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/Tools/TileClickTools.cs b/UoFiddler.Plugin.MultiEditor/Tools/TileClickTools.cs index 7875ef69..e8a9506e 100644 --- a/UoFiddler.Plugin.MultiEditor/Tools/TileClickTools.cs +++ b/UoFiddler.Plugin.MultiEditor/Tools/TileClickTools.cs @@ -40,7 +40,7 @@ public override void OnMouseUp(MouseEventArgs e) } /// - /// Makes the hovered tile the draw tile. + /// Makes the hovered tile the draw tile and returns to the draw tool used last. /// internal sealed class PipetteTool : EditorTool { @@ -52,7 +52,7 @@ public override void OnMouseUp(MouseEventArgs e) { if (Context.HoverTile != null) { - Context.SetDrawTile(Context.HoverTile.Id); + Context.PickDrawTile(Context.HoverTile.Id); } } } diff --git a/UoFiddler.Plugin.MultiEditor/UI/DocumentIO.cs b/UoFiddler.Plugin.MultiEditor/UI/DocumentIO.cs index 9ce48f3d..c54b49f3 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/DocumentIO.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/DocumentIO.cs @@ -269,7 +269,8 @@ public static string DesignTitle(UoaDesign design) /// Asks for a file name and format and writes the design. True when written. /// Z of the design's first floor, written as the base height of a UO House Editor design. - public static bool ExportToFile(IWin32Window owner, MultiEditorComponentList list, string suggestedName, int firstFloorZ = 7) + /// False leaves the tiles on hidden layers out of the file. + public static bool ExportToFile(IWin32Window owner, MultiEditorComponentList list, string suggestedName, int firstFloorZ = 7, bool includeHidden = true) { if (list == null) { @@ -318,7 +319,7 @@ public static bool ExportToFile(IWin32Window owner, MultiEditorComponentList lis try { - MultiComponentList sdkList = list.ConvertToSdk(); + MultiComponentList sdkList = list.ConvertToSdk(includeHidden); switch (type) { case Multis.ImportType.TXT: @@ -378,7 +379,8 @@ public static bool ExportToFile(IWin32Window owner, MultiEditorComponentList lis /// /// Asks for the multi id and stores the design into the client table. Returns the id, or null when cancelled. /// - public static int? SaveToClient(IWin32Window owner, MultiEditorComponentList list, int? suggestedId) + /// False leaves the tiles on hidden layers out of the client's multi. + public static int? SaveToClient(IWin32Window owner, MultiEditorComponentList list, int? suggestedId, bool includeHidden = true) { if (list == null) { @@ -392,7 +394,7 @@ public static bool ExportToFile(IWin32Window owner, MultiEditorComponentList lis return null; } - list.AddToSdkComponentList(dialog.SelectedId); // marks Multis changed and fires MultiChangeEvent + list.AddToSdkComponentList(dialog.SelectedId, includeHidden); // marks Multis changed and fires MultiChangeEvent if (dialog.WriteFormat is { } format) { WriteMultiFiles(owner, format); diff --git a/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.Designer.cs index df3307c4..7a5b6d59 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.Designer.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.Designer.cs @@ -85,6 +85,7 @@ private void InitializeComponent() selectionColumnWhere = new System.Windows.Forms.ColumnHeader(); selectionColumnName = new System.Windows.Forms.ColumnHeader(); _hint = new System.Windows.Forms.Label(); + _layers = new UoFiddler.Plugin.MultiEditor.UI.LayersPanel(); floorsBox.SuspendLayout(); floorsPage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)_firstFloor).BeginInit(); @@ -681,9 +682,18 @@ private void InitializeComponent() _hint.Text = "Nothing selected"; _hint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // + // _layers + // + _layers.Dock = System.Windows.Forms.DockStyle.Top; + _layers.Location = new System.Drawing.Point(0, 316); + _layers.Name = "_layers"; + _layers.Size = new System.Drawing.Size(150, 170); + _layers.TabIndex = 2; + // // InspectorPanel - // + // Controls.Add(selectionBox); + Controls.Add(_layers); Controls.Add(floorsBox); Name = "InspectorPanel"; floorsBox.ResumeLayout(false); @@ -764,5 +774,6 @@ private void InitializeComponent() private System.Windows.Forms.ColumnHeader selectionColumnWhere; private System.Windows.Forms.ColumnHeader selectionColumnName; private System.Windows.Forms.Label _hint; + private UoFiddler.Plugin.MultiEditor.UI.LayersPanel _layers; } } diff --git a/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.cs b/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.cs index aff3c252..3985436f 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/InspectorPanel.cs @@ -340,6 +340,7 @@ public void Bind(EditorSession session) _session.ViewChanged += Session_ViewChanged; } + _layers.Bind(_session); RebuildLevels(); RefreshSelection(); RefreshView(); diff --git a/UoFiddler.Plugin.MultiEditor/UI/LayersPanel.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/LayersPanel.Designer.cs new file mode 100644 index 00000000..dc19ed4c --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/LayersPanel.Designer.cs @@ -0,0 +1,181 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class LayersPanel + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + layersBox = new System.Windows.Forms.GroupBox(); + _list = new System.Windows.Forms.ListView(); + columnName = new System.Windows.Forms.ColumnHeader(); + columnCount = new System.Windows.Forms.ColumnHeader(); + _strip = new System.Windows.Forms.ToolStrip(); + _addButton = new System.Windows.Forms.ToolStripButton(); + _duplicateButton = new System.Windows.Forms.ToolStripButton(); + _deleteButton = new System.Windows.Forms.ToolStripButton(); + _mergeButton = new System.Windows.Forms.ToolStripButton(); + _upButton = new System.Windows.Forms.ToolStripButton(); + _downButton = new System.Windows.Forms.ToolStripButton(); + layersBox.SuspendLayout(); + _strip.SuspendLayout(); + SuspendLayout(); + // + // layersBox + // + layersBox.Controls.Add(_list); + layersBox.Controls.Add(_strip); + layersBox.Dock = System.Windows.Forms.DockStyle.Fill; + layersBox.Location = new System.Drawing.Point(0, 0); + layersBox.Name = "layersBox"; + layersBox.Size = new System.Drawing.Size(240, 170); + layersBox.TabIndex = 0; + layersBox.TabStop = false; + layersBox.Text = "Layers"; + // + // _list + // + _list.CheckBoxes = true; + _list.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { columnName, columnCount }); + _list.Dock = System.Windows.Forms.DockStyle.Fill; + _list.FullRowSelect = true; + _list.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; + _list.HideSelection = false; + _list.LabelEdit = true; + _list.Location = new System.Drawing.Point(3, 19); + _list.MultiSelect = false; + _list.Name = "_list"; + _list.Size = new System.Drawing.Size(234, 123); + _list.TabIndex = 0; + _list.UseCompatibleStateImageBehavior = false; + _list.View = System.Windows.Forms.View.Details; + _list.AfterLabelEdit += List_AfterLabelEdit; + _list.BeforeLabelEdit += List_BeforeLabelEdit; + _list.ItemChecked += List_ItemChecked; + _list.SelectedIndexChanged += List_SelectedIndexChanged; + _list.DoubleClick += List_DoubleClick; + _list.KeyDown += List_KeyDown; + _list.MouseUp += List_MouseUp; + _list.Resize += List_Resize; + // + // columnName + // + columnName.Text = "Layer"; + columnName.Width = 150; + // + // columnCount + // + columnCount.Text = "Tiles"; + columnCount.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; + columnCount.Width = 56; + // + // _strip + // + _strip.Dock = System.Windows.Forms.DockStyle.Bottom; + _strip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; + _strip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { _addButton, _duplicateButton, _deleteButton, _mergeButton, _upButton, _downButton }); + _strip.Location = new System.Drawing.Point(3, 142); + _strip.Name = "_strip"; + _strip.Size = new System.Drawing.Size(234, 25); + _strip.TabIndex = 1; + // + // _addButton + // + _addButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; + _addButton.Name = "_addButton"; + _addButton.Text = "New"; + _addButton.ToolTipText = "Add a new layer on top (Ctrl+Shift+N)"; + _addButton.Click += AddButton_Click; + // + // _duplicateButton + // + _duplicateButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; + _duplicateButton.Name = "_duplicateButton"; + _duplicateButton.Text = "Dup"; + _duplicateButton.ToolTipText = "Duplicate the active layer with its tiles"; + _duplicateButton.Click += DuplicateButton_Click; + // + // _deleteButton + // + _deleteButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; + _deleteButton.Name = "_deleteButton"; + _deleteButton.Text = "Del"; + _deleteButton.ToolTipText = "Delete the active layer and its tiles"; + _deleteButton.Click += DeleteButton_Click; + // + // _mergeButton + // + _mergeButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; + _mergeButton.Name = "_mergeButton"; + _mergeButton.Text = "Merge"; + _mergeButton.ToolTipText = "Merge the active layer into the one below"; + _mergeButton.Click += MergeButton_Click; + // + // _upButton + // + _upButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; + _upButton.Name = "_upButton"; + _upButton.Text = "▲"; + _upButton.ToolTipText = "Move the active layer up"; + _upButton.Click += UpButton_Click; + // + // _downButton + // + _downButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; + _downButton.Name = "_downButton"; + _downButton.Text = "▼"; + _downButton.ToolTipText = "Move the active layer down"; + _downButton.Click += DownButton_Click; + // + // LayersPanel + // + AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + Controls.Add(layersBox); + Name = "LayersPanel"; + Size = new System.Drawing.Size(240, 170); + layersBox.ResumeLayout(false); + layersBox.PerformLayout(); + _strip.ResumeLayout(false); + _strip.PerformLayout(); + ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.GroupBox layersBox; + private System.Windows.Forms.ListView _list; + private System.Windows.Forms.ColumnHeader columnName; + private System.Windows.Forms.ColumnHeader columnCount; + private System.Windows.Forms.ToolStrip _strip; + private System.Windows.Forms.ToolStripButton _addButton; + private System.Windows.Forms.ToolStripButton _duplicateButton; + private System.Windows.Forms.ToolStripButton _deleteButton; + private System.Windows.Forms.ToolStripButton _mergeButton; + private System.Windows.Forms.ToolStripButton _upButton; + private System.Windows.Forms.ToolStripButton _downButton; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/LayersPanel.cs b/UoFiddler.Plugin.MultiEditor/UI/LayersPanel.cs new file mode 100644 index 00000000..4ff1331f --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/LayersPanel.cs @@ -0,0 +1,388 @@ +/*************************************************************************** + * + * "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.Drawing; +using System.Windows.Forms; +using UoFiddler.Plugin.MultiEditor.Classes; +using UoFiddler.Plugin.MultiEditor.Editing; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// The layers of the design, top layer first: visibility, the active layer, tile counts and + /// the layer operations of the session. + /// + internal sealed partial class LayersPanel : UserControl + { + private readonly Font _boldFont; + private EditorSession _session; + private bool _updating; + private bool _editing; + private ContextMenuStrip _menu; + + public LayersPanel() + { + InitializeComponent(); + + _boldFont = new Font(Font, FontStyle.Bold); + Disposed += LayersPanel_Disposed; + + Bind(null); + } + + private void LayersPanel_Disposed(object sender, EventArgs e) + { + if (_session != null) + { + _session.LayersChanged -= Session_LayersChanged; + _session = null; + } + + _menu?.Dispose(); + _boldFont.Dispose(); + } + + /// Attaches to a session; null detaches and shows the empty state. + public void Bind(EditorSession session) + { + if (_session != null) + { + _session.LayersChanged -= Session_LayersChanged; + } + + _session = session; + + if (_session != null) + { + _session.LayersChanged += Session_LayersChanged; + } + + Refill(); + } + + private void Session_LayersChanged() + { + RefreshRows(); + } + + private void List_Resize(object sender, EventArgs e) + { + columnName.Width = Math.Max(40, _list.ClientSize.Width - columnCount.Width); + } + + private void List_ItemChecked(object sender, ItemCheckedEventArgs e) + { + if (_updating || _session == null || e.Item.Tag is not TileLayer layer) + { + return; + } + + _session.SetLayerVisible(layer, e.Item.Checked); + } + + private void List_SelectedIndexChanged(object sender, EventArgs e) + { + if (_updating || _session == null) + { + return; + } + + if (_list.SelectedItems.Count == 0) + { + // Nothing selected is also what the list reports on the way from one row to the + // next, so the active row is put back only once the click is over and still none is. + BeginInvoke(() => + { + if (!IsDisposed && _session != null && _list.SelectedItems.Count == 0) + { + RefreshRows(); + } + }); + return; + } + + if (_list.SelectedItems[0].Tag is TileLayer layer) + { + _session.ActiveLayer = layer; + } + } + + private void List_DoubleClick(object sender, EventArgs e) + { + Rename(); + } + + private void List_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.F2) + { + Rename(); + e.Handled = e.SuppressKeyPress = true; + } + } + + private void List_BeforeLabelEdit(object sender, LabelEditEventArgs e) + { + _editing = true; + } + + private void List_AfterLabelEdit(object sender, LabelEditEventArgs e) + { + _editing = false; + if (e.Label == null) + { + return; + } + + if (_session == null || string.IsNullOrWhiteSpace(e.Label) || _list.Items[e.Item].Tag is not TileLayer layer) + { + e.CancelEdit = true; + return; + } + + e.CancelEdit = !_session.RenameLayer(layer, e.Label); + } + + private void List_MouseUp(object sender, MouseEventArgs e) + { + if (e.Button != MouseButtons.Right || _session == null || _list.GetItemAt(e.X, e.Y) is not { Tag: TileLayer layer } item) + { + return; + } + + item.Selected = true; + ShowMenu(layer, item, e.Location); + } + + private void AddButton_Click(object sender, EventArgs e) + { + _session?.AddLayer(); + } + + private void DuplicateButton_Click(object sender, EventArgs e) + { + Duplicate(_session?.ActiveLayer); + } + + private void DeleteButton_Click(object sender, EventArgs e) + { + Delete(_session?.ActiveLayer); + } + + private void MergeButton_Click(object sender, EventArgs e) + { + MergeDown(_session?.ActiveLayer); + } + + private void UpButton_Click(object sender, EventArgs e) + { + if (_session?.ActiveLayer != null) + { + _session.MoveLayer(_session.ActiveLayer, 1); + } + } + + private void DownButton_Click(object sender, EventArgs e) + { + if (_session?.ActiveLayer != null) + { + _session.MoveLayer(_session.ActiveLayer, -1); + } + } + + // ---------------------------------------------------------------- actions + + private void Rename() + { + if (_session != null && _list.SelectedItems.Count > 0) + { + _list.SelectedItems[0].BeginEdit(); + } + } + + private void Duplicate(TileLayer layer) + { + if (layer != null) + { + _session.DuplicateLayer(layer); + } + } + + private void MergeDown(TileLayer layer) + { + if (layer != null) + { + _session.MergeLayerDown(layer); + } + } + + private void Delete(TileLayer layer) + { + if (_session == null || layer == null || _session.Layers.Count < 2) + { + return; + } + + int count = _session.CompList.LayerTileCount(layer); + if (count > 0) + { + string text = $"Delete layer '{layer.Name}' with its {count:N0} tiles?\r\n\r\nYou can undo this."; + if (MessageBox.Show(this, text, "Delete layer", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK) + { + return; + } + } + + _session.RemoveLayer(layer); + } + + private void ShowMenu(TileLayer layer, ListViewItem item, Point location) + { + _menu?.Dispose(); + _menu = new ContextMenuStrip(); + bool bottom = _session.Layers.Count > 0 && _session.Layers[0] == layer; + _menu.Items.Add("Rename", null, (_, _) => item.BeginEdit()); + _menu.Items.Add("Duplicate", null, (_, _) => Duplicate(layer)); + _menu.Items.Add("Delete", null, (_, _) => Delete(layer)).Enabled = _session.Layers.Count > 1; + _menu.Items.Add("Merge down", null, (_, _) => MergeDown(layer)).Enabled = !bottom; + _menu.Items.Add(new ToolStripSeparator()); + _menu.Items.Add("Show only this layer", null, (_, _) => _session.SoloLayer(layer)); + _menu.Items.Add("Select tiles on this layer", null, (_, _) => _session.SelectLayer(layer)); + _menu.Items.Add("Move selection to this layer", null, (_, _) => _session.MoveSelectionToLayer(layer)).Enabled = _session.Selection.Count > 0; + _menu.Show(_list, location); + } + + // ---------------------------------------------------------------- list + + /// Updates the rows in place when the layers are the same ones in the same order, else rebuilds. + private void RefreshRows() + { + int count = _session?.Layers.Count ?? 0; + bool same = _list.Items.Count == count; + for (int i = 0; same && i < count; ++i) + { + same = ReferenceEquals(_list.Items[i].Tag, _session.Layers[count - 1 - i]); + } + + if (!same) + { + Refill(); + return; + } + + bool previous = _updating; + _updating = true; + try + { + UpdateRows(); + UpdateButtons(); + } + finally + { + _updating = previous; + } + } + + private void Refill() + { + bool previous = _updating; + _updating = true; + try + { + _list.BeginUpdate(); + _list.Items.Clear(); + if (_session != null) + { + for (int i = _session.Layers.Count - 1; i >= 0; --i) + { + var item = new ListViewItem(string.Empty) { Tag = _session.Layers[i] }; + item.SubItems.Add(string.Empty); + _list.Items.Add(item); + } + + UpdateRows(); + } + + _list.EndUpdate(); + UpdateButtons(); + } + finally + { + _updating = previous; + } + } + + // Caller holds _updating. + private void UpdateRows() + { + Dictionary counts = _session.CompList.LayerTileCounts(); + foreach (ListViewItem item in _list.Items) + { + var layer = (TileLayer)item.Tag; + bool active = layer == _session.ActiveLayer; + + if (item.Text != layer.Name && !_editing) + { + item.Text = layer.Name; + } + + string tiles = counts.GetValueOrDefault(layer).ToString("N0"); + if (item.SubItems[1].Text != tiles) + { + item.SubItems[1].Text = tiles; + } + + if (item.Checked != layer.Visible) + { + item.Checked = layer.Visible; + } + + Font font = active ? _boldFont : _list.Font; + if (!ReferenceEquals(item.Font, font)) + { + item.Font = font; + } + + if (item.Selected != active) + { + item.Selected = active; + } + } + } + + private void UpdateButtons() + { + bool has = _session != null; + int count = _session?.Layers.Count ?? 0; + int index = has ? IndexOfActive() : -1; + + _addButton.Enabled = has; + _duplicateButton.Enabled = has; + _deleteButton.Enabled = has && count > 1; + _mergeButton.Enabled = has && index > 0; + _downButton.Enabled = has && index > 0; + _upButton.Enabled = has && index >= 0 && index < count - 1; + } + + private int IndexOfActive() + { + for (int i = 0; i < _session.Layers.Count; ++i) + { + if (_session.Layers[i] == _session.ActiveLayer) + { + return i; + } + } + + return -1; + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs index 185d338d..007ed9df 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/MultiEditorControl.cs @@ -34,6 +34,9 @@ private sealed class EditorDocument public EditorSession Session; public Camera2D Camera = new Camera2D(); public int? ClientId; + + /// The design file the document was opened from or last saved to, or null. + public string FilePath; } private readonly ArtMasks _masks = new ArtMasks(); @@ -112,7 +115,7 @@ public void ExtractFromMap(Map map, Point location) NewDocument(width, height, "Map extract"); } - Session.BeginPaste(tiles); + Session.BeginPaste(tiles, "Map extract"); _canvas.Focus(); } @@ -255,7 +258,7 @@ private void EnsureBuilt() _browser.TileChosen += id => { Session?.SetDrawTile(id); - if (Session != null && !IsTileTool(Session.Tool)) + if (Session != null && !EditorSession.IsTileTool(Session.Tool)) { Session.Tool = ToolKind.Draw; } @@ -289,7 +292,7 @@ private void EnsureBuilt() NewDocument(tiles.Max(t => t.Dx) + 1, tiles.Max(t => t.Dy) + 1, DocumentIO.DesignTitle(design)); } - Session.BeginPaste(tiles); + Session.BeginPaste(tiles, "Design"); _canvas.Focus(); }; _browser.HouseStyleChosen += ChooseHouseStyle; @@ -321,7 +324,7 @@ private void EnsureBuilt() }; _browser.BlueprintChosen += tiles => { - Session?.BeginPaste(tiles); + Session?.BeginPaste(tiles, "Blueprint"); _canvas.Focus(); }; @@ -443,14 +446,16 @@ private EditorCommand Command(string group, string text, Action execute, Keys sh }); } + private EditorCommand _openDesign, _saveDesign, _saveDesignAs; private EditorCommand _new, _open, _import, _importFolder, _saveClient, _export, _saveBlueprint, _resize, _close, _closeAll; - private EditorCommand _undo, _redo, _cut, _copy, _paste, _delete; + private EditorCommand _undo, _redo, _cut, _copy, _paste, _duplicate, _repeat, _delete; private EditorCommand _selectAll, _invert, _selectConnected, _selectSameId, _replaceId; private EditorCommand _rotateLeft, _rotateRight, _mirrorX, _mirrorY, _swapStyle, _hide, _showHidden; private EditorCommand _grid, _hideWalls, _walkable, _doubleSurface, _hideAbove, _levelUp, _levelDown; private EditorCommand _fit, _center, _zoomIn, _zoomOut, _zoomReset, _shortcuts; private EditorCommand _zUp, _zDown, _planeUp, _planeDown, _cyclePlacement, _escape; private EditorCommand _drawWithSelected, _workPlane; + private MultiTile _menuTile; private ContextMenuStrip _canvasMenu; private ToolStripMenuItem _canvasMenuTitle; private EditorCommand _preview, _moveReference, _planView, _allFloors, _showBrowser, _showInspector; @@ -463,6 +468,7 @@ private EditorCommand Command(string group, string text, Action execute, Keys sh private PerformancePanel _performancePanel; private bool _performanceShown; private EditorCommand _savePattern; + private EditorCommand _newLayer, _moveToLayer, _selectLayer; private bool _openingHousePage; private readonly List _terrainCommands = new List(); private ContextMenuStrip _previewMenu; @@ -476,6 +482,9 @@ private void DefineCommands() _open = Command("File", "Open from client...", OpenFromClient, Keys.Control | Keys.O, glyph: Glyphs.Open); _import = Command("File", "Import files...", ImportFile, Keys.Control | Keys.I); _importFolder = Command("File", "Import from folder...", ImportFolder, Keys.Control | Keys.Shift | Keys.I); + _openDesign = Command("File", "Open design file...", OpenDesignFile, Keys.Control | Keys.Shift | Keys.O); + _saveDesign = Command("File", "Save design file", () => SaveDesignFile(saveAs: false), Keys.Control | Keys.Shift | Keys.S, hasDoc); + _saveDesignAs = Command("File", "Save design file as...", () => SaveDesignFile(saveAs: true), can: hasDoc); _saveClient = Command("File", "Save to client...", SaveToClient, Keys.Control | Keys.S, hasDoc, glyph: Glyphs.Save); _export = Command("File", "Export file...", ExportFile, Keys.Control | Keys.E, hasDoc); _saveBlueprint = Command("File", "Save as blueprint...", SaveBlueprint, can: hasDoc); @@ -492,6 +501,8 @@ private void DefineCommands() _cut = Command("Edit", "Cut", () => Session.Cut(), Keys.Control | Keys.X, hasSelection, glyph: Glyphs.Cut); _copy = Command("Edit", "Copy", () => Session.Copy(), Keys.Control | Keys.C, hasSelection, glyph: Glyphs.Copy); _paste = Command("Edit", "Paste", () => Session.Paste(), Keys.Control | Keys.V, hasDoc, glyph: Glyphs.Paste); + _duplicate = Command("Edit", "Duplicate selection", () => Session.Duplicate(), Keys.Control | Keys.D, hasSelection); + _repeat = Command("Edit", "Repeat selection...", RepeatSelectionPrompt, Keys.Control | Keys.Shift | Keys.D, hasSelection); _delete = Command("Edit", "Delete selection", () => Session.DeleteSelection(), Keys.Delete, hasSelection, glyph: Glyphs.Delete); _selectAll = Command("Select", "Select all", () => Session.SelectAll(), Keys.Control | Keys.A, hasDoc); @@ -511,6 +522,11 @@ private void DefineCommands() _hide = Command("Arrange", "Hide selection", () => Session.HideSelection(), Keys.H, hasSelection); _showHidden = Command("Arrange", "Show hidden tiles", () => Session.ShowHiddenTiles(), Keys.Shift | Keys.H, hasDoc); + _newLayer = Command("Layers", "New layer", () => Session.AddLayer(), Keys.Control | Keys.Shift | Keys.N, hasDoc); + _moveToLayer = Command("Layers", "Move selection to the active layer", () => Session.MoveSelectionToLayer(Session.ActiveLayer), + Keys.Control | Keys.Shift | Keys.M, hasSelection); + _selectLayer = Command("Layers", "Select tiles on the active layer", () => Session.SelectLayer(Session.ActiveLayer), can: hasDoc); + _workPlane = Command("View", "Work plane", () => Session.ShowWorkPlane = !Session.ShowWorkPlane, Keys.F, hasDoc, () => Session?.ShowWorkPlane == true); _grid = Command("View", "Grid", () => Session.ShowGrid = !Session.ShowGrid, Keys.G, hasDoc, () => Session?.ShowGrid == true, Glyphs.Grid); @@ -583,7 +599,7 @@ private void DefineCommands() } _escape = Command("Tools", "Cancel tool, then clear selection", Escape, Keys.Escape, hasDoc); _shortcuts = Command("Help", "Keyboard shortcuts", ShowShortcuts, Keys.F1, glyph: Glyphs.Help); - _drawWithSelected = Command("Tools", "Draw with this tile", DrawWithSelected, can: () => Session?.SelectedTile != null); + _drawWithSelected = Command("Tools", "Draw with this tile", DrawWithSelected, can: () => (_menuTile ?? Session?.SelectedTile) != null); } private void AddTool(ToolKind kind, string text, Keys key, string glyph) @@ -592,11 +608,6 @@ private void AddTool(ToolKind kind, string text, Keys key, string glyph) () => Session != null && !Session.Pasting && Session.Tool == kind, glyph); } - private static bool IsTileTool(ToolKind kind) - { - return kind is ToolKind.Draw or ToolKind.RectFill or ToolKind.Line; - } - private static bool IsHouseTool(ToolKind kind) { return kind is ToolKind.Wall or ToolKind.Floor or ToolKind.Door or ToolKind.Stair or ToolKind.Roof or ToolKind.Foundation; @@ -739,10 +750,44 @@ private void SaveBlueprint() private void DrawWithSelected() { - Session.SetDrawTile(Session.SelectedTile.Id); + Session.SetDrawTile((_menuTile ?? Session.SelectedTile).Id); Session.Tool = ToolKind.Draw; } + /// + /// Asks how often and how far apart to copy the selection, showing the copies on the canvas + /// while the numbers change. + /// + private void RepeatSelectionPrompt() + { + EditorSession session = Session; + int width = session.Selection.Max(t => t.X) - session.Selection.Min(t => t.X) + 1; + using var dialog = new RepeatSelectionDialog(width); + + void Preview() + { + (int added, int skipped) = session.PreviewRepeat(dialog.Copies, dialog.StepX, dialog.StepY, dialog.StepZ); + dialog.SetSummary(added == 0 && skipped == 0 ? "Set a step to place the copies." + : $"Adds {added:N0} tiles" + (skipped > 0 ? $" ({skipped:N0} outside the multi are skipped)" : string.Empty) + + (added > RepeatPreviewTool.MaxGhosts ? ". Too many to preview." : ".")); + } + + dialog.ValuesChanged += Preview; + Preview(); + try + { + if (dialog.ShowDialog(this) == DialogResult.OK) + { + session.RepeatSelection(dialog.Copies, dialog.StepX, dialog.StepY, dialog.StepZ); + } + } + finally + { + session.EndRepeatPreview(); + _canvas.Focus(); + } + } + private void BuildCanvasMenu() { _canvasMenu = new ContextMenuStrip(); @@ -757,13 +802,13 @@ private void BuildCanvasMenu() _canvasMenu.Items.Add(brushMenu); _canvasMenu.Items.Add(new ToolStripSeparator()); - foreach (EditorCommand command in new[] { _cut, _copy, _paste, _delete }) + foreach (EditorCommand command in new[] { _cut, _copy, _paste, _duplicate, _repeat, _delete }) { _canvasMenu.Items.Add(_commands.MenuItem(command)); } _canvasMenu.Items.Add(new ToolStripSeparator()); - foreach (EditorCommand command in new[] { _zUp, _zDown, _rotateLeft, _rotateRight, _hide, _showHidden }) + foreach (EditorCommand command in new[] { _zUp, _zDown, _rotateLeft, _rotateRight, _hide, _showHidden, _moveToLayer }) { _canvasMenu.Items.Add(_commands.MenuItem(command)); } @@ -833,6 +878,9 @@ private void ShowCanvasMenu(Point location) session.SetSelection(new[] { hover }, add: false); } + // "Draw with this tile" means the tile under the cursor, also inside a larger selection. + _menuTile = hover; + MultiTile single = session.SelectedTile; int count = session.Selection.Count; _canvasMenuTitle.Text = single != null ? $"0x{single.Id:X4} {TileName(single.Id)} (Z {single.Z})" @@ -1147,9 +1195,10 @@ private void BuildMainStrip() { ToolStrip strip = _mainStrip; - Menu(_fileMenu, _new, _open, _import, _importFolder, null, _saveClient, _export, _saveBlueprint, _savePattern, null, _resize, _settingsCommand, null, _close, _closeAll); - Menu(_editMenu, _undo, _redo, null, _cut, _copy, _paste, _delete, null, - _rotateLeft, _rotateRight, _mirrorX, _mirrorY, _swapStyle, null, _zUp, _zDown, _hide, _showHidden); + Menu(_fileMenu, _new, _open, _openDesign, _import, _importFolder, null, _saveDesign, _saveDesignAs, _saveClient, _export, _saveBlueprint, _savePattern, null, _resize, _settingsCommand, null, _close, _closeAll); + Menu(_editMenu, _undo, _redo, null, _cut, _copy, _paste, _duplicate, _repeat, _delete, null, + _rotateLeft, _rotateRight, _mirrorX, _mirrorY, _swapStyle, null, _zUp, _zDown, _hide, _showHidden, + null, _newLayer, _moveToLayer, _selectLayer); Menu(_selectMenu, _selectAll, _invert, _selectConnected, _selectSameId, null, _replaceId); ToolStripDropDownButton view = Menu(_viewMenu, _preview, _planView, null, _workPlane, _grid, _hideWalls, _hideAbove, _walkable, _doubleSurface, null, _allFloors, _levelUp, _levelDown, _planeUp, _planeDown, null, _showBrowser, _showInspector, null, _fit, _center, _zoomIn, _zoomOut, _zoomReset, null, _moveReference, null, _performanceInfo); @@ -1466,6 +1515,14 @@ private void AddDocument(OpenedMulti opened) { EditorDocument document = CreateDocument(opened.Title, opened.ClientId); document.Session.Load(opened.Components); + + // A multi from the client gets back the layers it was saved with, when it is still that multi. + (int X, int Y) origin = (opened.Components.Center.X, opened.Components.Center.Y); + if (opened.ClientId is { } clientId && + LayerStore.Load(clientId, document.Session.CompList.Fingerprint(origin)) is { } saved) + { + document.Session.RestoreLayers(saved.Layers, saved.Active, origin); + } ShowDocument(document); } @@ -1513,12 +1570,28 @@ private void ShowDocument(EditorDocument document) private void SaveToClient() { - int? id = DocumentIO.SaveToClient(this, Session.CompList, _active.ClientId); + if (AskIncludeHiddenLayers("Leaves them out of the client's multi. They stay in the editor's layers and come back when you open it here.") is not { } includeHidden) + { + return; + } + + MultiEditorComponentList list = Session.CompList; + int? id = DocumentIO.SaveToClient(this, list, _active.ClientId, includeHidden); if (id == null) { return; } + try + { + LayerStore.Save(id.Value, list.SaveLayers(includeHidden), list.Layers.ToList().IndexOf(list.ActiveLayer), list.Fingerprint(list.SaveOrigin, includeHidden)); + } + catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException or ArgumentException or System.Xml.XmlException) + { + MessageBox.Show(this, $"The multi was saved, but its layers could not be written:\r\n{ex.Message}", "Multi Editor", + MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + _active.ClientId = id; Session.Title = $"Multi 0x{id:X4}"; Session.MarkSaved(); @@ -1526,12 +1599,134 @@ private void SaveToClient() private void ExportFile() { - if (DocumentIO.ExportToFile(this, Session.CompList, Session.Title, Session.FirstFloorZ)) + if (AskIncludeHiddenLayers("Leaves them out of the file. Exported files do not keep layers.") is not { } includeHidden) + { + return; + } + + if (DocumentIO.ExportToFile(this, Session.CompList, Session.Title, Session.FirstFloorZ, includeHidden)) { Session.MarkSaved(); } } + /// + /// Before a save: asks whether tiles on hidden layers go into it. True without asking when + /// no hidden layer has tiles; null when the save is cancelled. + /// + private bool? AskIncludeHiddenLayers(string whenLeftOut) + { + MultiEditorComponentList list = Session.CompList; + int hidden = list.HiddenLayerTileCount; + if (hidden == 0) + { + return true; + } + + string names = string.Join(", ", list.Layers.Where(l => !l.Visible && list.LayerTileCount(l) > 0).Select(l => l.Name)); + DialogResult answer = MessageBox.Show(this, + $"{hidden:N0} tile(s) are on hidden layers ({names}).\r\n\r\nInclude them in the save?\r\n\r\nYes: saved with the rest.\r\nNo: {whenLeftOut}", + "Hidden layers", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); + if (answer == DialogResult.No && hidden == list.TileCount) + { + MessageBox.Show(this, "Every tile is on a hidden layer, so nothing would be saved. Show a layer first, or include the hidden layers.", + "Hidden layers", MessageBoxButtons.OK, MessageBoxIcon.Information); + return null; + } + + return answer == DialogResult.Cancel ? null : answer == DialogResult.Yes; + } + + /// Opens design files (the editor's own format, with layers and floors), each in its own tab. + private void OpenDesignFile() + { + using var dialog = new OpenFileDialog + { + Title = "Open design file", + Filter = DesignFile.Filter, + InitialDirectory = Options.OutputPath, + Multiselect = true + }; + if (dialog.ShowDialog(this) != DialogResult.OK || !ConfirmOpenMany(dialog.FileNames.Length)) + { + return; + } + + foreach (string path in dialog.FileNames) + { + // A file that is open already is shown, not opened a second time. + EditorDocument open = _documents.Find(d => string.Equals(d.FilePath, path, StringComparison.OrdinalIgnoreCase)); + if (open != null) + { + _docTabs.SelectedIndex = _documents.IndexOf(open); + continue; + } + + try + { + DesignData design = DesignFile.Load(path); + string title = string.IsNullOrWhiteSpace(design.Name) ? System.IO.Path.GetFileNameWithoutExtension(path) : design.Name; + EditorDocument document = CreateDocument(title, null); + document.FilePath = path; + document.Session.LoadDesign(design); + ShowDocument(document); + } + catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException or System.IO.InvalidDataException) + { + MessageBox.Show(this, $"{System.IO.Path.GetFileName(path)} could not be opened:\r\n{ex.Message}", "Open design file", + MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + } + + /// + /// Saves the design with its layers and floors to its design file, asking for a name the + /// first time or with . Hidden layers are always saved. + /// + private void SaveDesignFile(bool saveAs) + { + string path = _active.FilePath; + if (saveAs || path == null) + { + using var dialog = new SaveFileDialog + { + Title = "Save design file", + Filter = DesignFile.Filter, + DefaultExt = DesignFile.Extension, + AddExtension = true, + OverwritePrompt = true, + InitialDirectory = path != null ? System.IO.Path.GetDirectoryName(path) : Options.OutputPath, + FileName = path != null ? System.IO.Path.GetFileName(path) : SafeFileName(Session.Title) + }; + if (dialog.ShowDialog(this) != DialogResult.OK) + { + return; + } + + path = dialog.FileName; + } + + try + { + DesignFile.Save(path, Session.ToDesign()); + } + catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException or ArgumentException) + { + MessageBox.Show(this, $"The design could not be saved:\r\n{ex.Message}", "Save design file", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + _active.FilePath = path; + Session.MarkSaved(); + _statusHint.Text = $"Saved {path}"; + } + + private static string SafeFileName(string title) + { + string name = string.Concat((title ?? string.Empty).Split(System.IO.Path.GetInvalidFileNameChars())).Trim(); + return name.Length > 0 ? name : "design"; + } + private void ResizePrompt() { int[] size = Prompt.Numbers(this, "Resize multi", @@ -1571,7 +1766,7 @@ private void CloseDocument(EditorDocument document, bool ask = true) } if (ask && document.Session.Modified && MessageBox.Show(this, - $"\"{document.Session.Title}\" has changes that were not saved to the client or exported.\r\nClose it anyway?", + $"\"{document.Session.Title}\" has changes that were not saved to a design file or the client, or exported.\r\nClose it anyway?", "Multi Editor", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK) { return; @@ -1918,7 +2113,7 @@ private void SyncOptions() return; } - _toolLabel.Text = session.Pasting ? "Paste" : _toolCommands[session.Tool].Text; + _toolLabel.Text = session.Pasting ? session.StampLabel : _toolCommands[session.Tool].Text; int zIndex = _zStepCombo.IndexOf(session.ZStep.ToString()); _zStepCombo.SelectedIndex = Math.Max(0, zIndex); @@ -1983,7 +2178,8 @@ private void UpdateStatus() } _statusHint.Text = session.PreviewMode ? "Preview: editing is off. Right click picks the ground. F5 returns to the editor." - : session.Pasting ? "Click to place the tiles. Esc or right click cancels." + : session.PreviewingRepeat ? "The copies are shown as they would be placed." + : session.Pasting ? "Click to place the tiles, as often as you like. Esc or right click stops." : ToolHint(session.Tool); (int x, int y, int z) = session.CursorCell; @@ -2006,13 +2202,13 @@ private static string ToolHint(ToolKind kind) { ToolKind.Select => "Click a tile to select, Ctrl+click adds, drag a box over tiles, drag the selection to move it.", ToolKind.Lasso => "Draw an outline around tiles to select them. Ctrl adds to the selection.", - ToolKind.Draw => "Click or drag to place the chosen tile. Placement mode (M) decides the Z.", + ToolKind.Draw => "Click to place the chosen tile. Placement mode (M) decides the Z. Alt+click picks a tile.", ToolKind.Remove => "Click a tile to remove it, drag to remove an area.", ToolKind.Altitude => "Click raises the tile by the Z step, Shift+click lowers it.", - ToolKind.Pipette => "Click a tile to draw with it.", + ToolKind.Pipette => "Click a tile to draw with it; the draw tool comes back.", ToolKind.Transparent => "Click a tile to see through it, click again to restore.", - ToolKind.RectFill => "Drag a rectangle to fill with the chosen tile.", - ToolKind.Line => "Drag a line of the chosen tile.", + ToolKind.RectFill => "Drag a rectangle to fill with the chosen tile. Alt+click picks a tile.", + ToolKind.Line => "Drag a line of the chosen tile. Alt+click picks a tile.", ToolKind.Wall => "Drag along the cells to build walls in the chosen style. Corners and posts are picked for you.", ToolKind.Floor => "Drag an area to lay the chosen floor style.", ToolKind.Door => "Click a wall cell to hang the chosen door.", diff --git a/UoFiddler.Plugin.MultiEditor/UI/RepeatSelectionDialog.Designer.cs b/UoFiddler.Plugin.MultiEditor/UI/RepeatSelectionDialog.Designer.cs new file mode 100644 index 00000000..997c9d03 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/RepeatSelectionDialog.Designer.cs @@ -0,0 +1,188 @@ +namespace UoFiddler.Plugin.MultiEditor.UI +{ + partial class RepeatSelectionDialog + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + _copiesLabel = new System.Windows.Forms.Label(); + _copiesBox = new System.Windows.Forms.NumericUpDown(); + _stepXLabel = new System.Windows.Forms.Label(); + _stepXBox = new System.Windows.Forms.NumericUpDown(); + _stepYLabel = new System.Windows.Forms.Label(); + _stepYBox = new System.Windows.Forms.NumericUpDown(); + _stepZLabel = new System.Windows.Forms.Label(); + _stepZBox = new System.Windows.Forms.NumericUpDown(); + _summaryLabel = new System.Windows.Forms.Label(); + _okButton = new System.Windows.Forms.Button(); + _cancelButton = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)_copiesBox).BeginInit(); + ((System.ComponentModel.ISupportInitialize)_stepXBox).BeginInit(); + ((System.ComponentModel.ISupportInitialize)_stepYBox).BeginInit(); + ((System.ComponentModel.ISupportInitialize)_stepZBox).BeginInit(); + SuspendLayout(); + // + // _copiesLabel + // + _copiesLabel.Location = new System.Drawing.Point(12, 16); + _copiesLabel.Name = "_copiesLabel"; + _copiesLabel.Size = new System.Drawing.Size(120, 15); + _copiesLabel.TabIndex = 0; + _copiesLabel.Text = "Copies:"; + // + // _copiesBox + // + _copiesBox.Location = new System.Drawing.Point(140, 13); + _copiesBox.Maximum = new decimal(new int[] { 200, 0, 0, 0 }); + _copiesBox.Minimum = new decimal(new int[] { 1, 0, 0, 0 }); + _copiesBox.Name = "_copiesBox"; + _copiesBox.Size = new System.Drawing.Size(100, 23); + _copiesBox.TabIndex = 1; + _copiesBox.Value = new decimal(new int[] { 1, 0, 0, 0 }); + // + // _stepXLabel + // + _stepXLabel.Location = new System.Drawing.Point(12, 48); + _stepXLabel.Name = "_stepXLabel"; + _stepXLabel.Size = new System.Drawing.Size(120, 15); + _stepXLabel.TabIndex = 2; + _stepXLabel.Text = "Step X (cells):"; + // + // _stepXBox + // + _stepXBox.Location = new System.Drawing.Point(140, 45); + _stepXBox.Maximum = new decimal(new int[] { 255, 0, 0, 0 }); + _stepXBox.Minimum = new decimal(new int[] { 255, 0, 0, int.MinValue }); + _stepXBox.Name = "_stepXBox"; + _stepXBox.Size = new System.Drawing.Size(100, 23); + _stepXBox.TabIndex = 3; + // + // _stepYLabel + // + _stepYLabel.Location = new System.Drawing.Point(12, 80); + _stepYLabel.Name = "_stepYLabel"; + _stepYLabel.Size = new System.Drawing.Size(120, 15); + _stepYLabel.TabIndex = 4; + _stepYLabel.Text = "Step Y (cells):"; + // + // _stepYBox + // + _stepYBox.Location = new System.Drawing.Point(140, 77); + _stepYBox.Maximum = new decimal(new int[] { 255, 0, 0, 0 }); + _stepYBox.Minimum = new decimal(new int[] { 255, 0, 0, int.MinValue }); + _stepYBox.Name = "_stepYBox"; + _stepYBox.Size = new System.Drawing.Size(100, 23); + _stepYBox.TabIndex = 5; + // + // _stepZLabel + // + _stepZLabel.Location = new System.Drawing.Point(12, 112); + _stepZLabel.Name = "_stepZLabel"; + _stepZLabel.Size = new System.Drawing.Size(120, 15); + _stepZLabel.TabIndex = 6; + _stepZLabel.Text = "Step Z:"; + // + // _stepZBox + // + _stepZBox.Location = new System.Drawing.Point(140, 109); + _stepZBox.Maximum = new decimal(new int[] { 127, 0, 0, 0 }); + _stepZBox.Minimum = new decimal(new int[] { 127, 0, 0, int.MinValue }); + _stepZBox.Name = "_stepZBox"; + _stepZBox.Size = new System.Drawing.Size(100, 23); + _stepZBox.TabIndex = 7; + // + // _summaryLabel + // + _summaryLabel.Location = new System.Drawing.Point(12, 146); + _summaryLabel.Name = "_summaryLabel"; + _summaryLabel.Size = new System.Drawing.Size(236, 48); + _summaryLabel.TabIndex = 8; + // + // _okButton + // + _okButton.DialogResult = System.Windows.Forms.DialogResult.OK; + _okButton.Location = new System.Drawing.Point(84, 206); + _okButton.Name = "_okButton"; + _okButton.Size = new System.Drawing.Size(76, 23); + _okButton.TabIndex = 9; + _okButton.Text = "OK"; + // + // _cancelButton + // + _cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; + _cancelButton.Location = new System.Drawing.Point(168, 206); + _cancelButton.Name = "_cancelButton"; + _cancelButton.Size = new System.Drawing.Size(76, 23); + _cancelButton.TabIndex = 10; + _cancelButton.Text = "Cancel"; + // + // RepeatSelectionDialog + // + AcceptButton = _okButton; + AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + CancelButton = _cancelButton; + ClientSize = new System.Drawing.Size(260, 242); + Controls.Add(_copiesLabel); + Controls.Add(_copiesBox); + Controls.Add(_stepXLabel); + Controls.Add(_stepXBox); + Controls.Add(_stepYLabel); + Controls.Add(_stepYBox); + Controls.Add(_stepZLabel); + Controls.Add(_stepZBox); + Controls.Add(_summaryLabel); + Controls.Add(_okButton); + Controls.Add(_cancelButton); + FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + MaximizeBox = false; + MinimizeBox = false; + Name = "RepeatSelectionDialog"; + ShowInTaskbar = false; + StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + Text = "Repeat selection"; + ((System.ComponentModel.ISupportInitialize)_copiesBox).EndInit(); + ((System.ComponentModel.ISupportInitialize)_stepXBox).EndInit(); + ((System.ComponentModel.ISupportInitialize)_stepYBox).EndInit(); + ((System.ComponentModel.ISupportInitialize)_stepZBox).EndInit(); + ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.Label _copiesLabel; + private System.Windows.Forms.NumericUpDown _copiesBox; + private System.Windows.Forms.Label _stepXLabel; + private System.Windows.Forms.NumericUpDown _stepXBox; + private System.Windows.Forms.Label _stepYLabel; + private System.Windows.Forms.NumericUpDown _stepYBox; + private System.Windows.Forms.Label _stepZLabel; + private System.Windows.Forms.NumericUpDown _stepZBox; + private System.Windows.Forms.Label _summaryLabel; + private System.Windows.Forms.Button _okButton; + private System.Windows.Forms.Button _cancelButton; + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/RepeatSelectionDialog.cs b/UoFiddler.Plugin.MultiEditor/UI/RepeatSelectionDialog.cs new file mode 100644 index 00000000..f38defc9 --- /dev/null +++ b/UoFiddler.Plugin.MultiEditor/UI/RepeatSelectionDialog.cs @@ -0,0 +1,67 @@ +/*************************************************************************** + * + * "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.Windows.Forms; + +namespace UoFiddler.Plugin.MultiEditor.UI +{ + /// + /// Asks for the number of copies and the step between them for the "Repeat selection" command. + /// The caller shows a live preview and updates it from . + /// + internal partial class RepeatSelectionDialog : Form + { + public RepeatSelectionDialog() + { + InitializeComponent(); + + foreach (NumericUpDown box in new[] { _copiesBox, _stepXBox, _stepYBox, _stepZBox }) + { + box.ValueChanged += (_, _) => ValuesChanged?.Invoke(); + box.KeyUp += OnBoxKeyUp; + } + } + + public RepeatSelectionDialog(int stepX) + : this() + { + _stepXBox.Value = Math.Clamp(stepX, (int)_stepXBox.Minimum, (int)_stepXBox.Maximum); + } + + public int Copies => (int)_copiesBox.Value; + + public int StepX => (int)_stepXBox.Value; + + public int StepY => (int)_stepYBox.Value; + + public int StepZ => (int)_stepZBox.Value; + + /// Raised when any of the four numbers changes, also while typing or spinning. + public event Action ValuesChanged; + + /// Sets the summary line under the boxes. + public void SetSummary(string text) + { + _summaryLabel.Text = text; + } + + private static void OnBoxKeyUp(object sender, KeyEventArgs e) + { + // Only text that already reads as the number: setting Value rewrites the text, and a + // rewrite of "05" or "-" would move the caret under the typing. + var box = (NumericUpDown)sender; + if (int.TryParse(box.Text, out int parsed) && parsed.ToString() == box.Text && + parsed >= box.Minimum && parsed <= box.Maximum && parsed != box.Value) + { + box.Value = parsed; + } + } + } +} diff --git a/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.cs b/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.cs index 2699fb70..9d1c172b 100644 --- a/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.cs +++ b/UoFiddler.Plugin.MultiEditor/UI/ShortcutsForm.cs @@ -50,7 +50,8 @@ public void ShowCommands(IEnumerable commands) ("Pan", "Right or middle drag, Space + drag"), ("Zoom at the cursor", "Wheel"), ("Step through the floors", "Shift + wheel"), - ("Context menu, or cancel a drag or paste", "Right click"), + ("Place a paste, blueprint or duplicate, as often as you like", "Click"), + ("Context menu, or stop a drag, paste or blueprint", "Right click"), ("Select the tile under the cursor (any tool)", "Middle click"), ("Move the selection one cell", "Arrow keys"), ("Pan one cell", "Ctrl + arrow keys")); @@ -59,6 +60,7 @@ public void ShowCommands(IEnumerable commands) ("Move the selection (Select)", "Drag a selected tile"), ("Add a tile to the selection or take it out (Select)", "Ctrl + click"), ("Add to the selection (Select, Lasso)", "Ctrl + drag"), + ("Pick the tile under the cursor (Draw, Rectangle, Line)", "Alt + click"), ("Keep the line straight (Line)", "Shift + drag"), ("One straight wall instead of a room (Walls)", "Shift + drag"), ("Erase walls (Walls)", "Ctrl + drag"), diff --git a/UoFiddler/Forms/AboutBoxForm.resx b/UoFiddler/Forms/AboutBoxForm.resx index 46f51168..af807984 100644 --- a/UoFiddler/Forms/AboutBoxForm.resx +++ b/UoFiddler/Forms/AboutBoxForm.resx @@ -118,7 +118,22 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - Version 4.28.1 + Version 4.28.2 +- Animations: the animation edit body list opens anim.mul in a fraction of a second and the editor closes at once; body and action rows show tooltips +- Animations: center editing can apply relative offsets and cover all directions or all actions at once +- Animations: the frame size shows next to the zoom while a frame rectangle is drawn +- Animations: export to .vd at a chosen scale, and in another body type's action layout with a source action picked per slot; sea monster bodies export as 22-action files +- Animations: .vd imports refuse files with fewer entries than the body needs +- Animations: an overlaid body of another type plays its closest action, so a mount under a rider walks, runs and stands +- Animations: frames pack to one PNG per frame with a frames XML, at a chosen size; unpack and bulk unpack read it too +- Multi Editor: pasted tiles and blueprints stay on the cursor and place on every click until Esc or right click +- Multi Editor: Duplicate selection (Ctrl+D) puts a copy on the cursor; Repeat selection (Ctrl+Shift+D) adds copies a chosen step apart, previewed on the canvas +- Multi Editor: Alt+click picks the tile under the cursor while drawing, the Pick tile tool returns to the draw tool, and Draw with this tile uses the tile under the cursor +- Multi Editor: layers group the tiles of a design; they can be hidden, renamed, duplicated, merged, reordered and deleted, with undo, and new tiles go on the active layer +- Multi Editor: a multi saved to the client gets its layers back when it is opened again; Save to client and Export ask whether to include hidden layers +- Multi Editor: design files (*.uomd) keep a design as drawn, with its size, layers and floors (File > Open/Save design file) + +Version 4.28.1 - Multi Editor: prefabs are now blueprints, kept in MultiEditorBlueprints; an existing MultiEditorPrefabs folder is moved there on first use - Multi Editor: save picked multis and UO Architect designs as blueprints in bulk from Open from client, Import files, Import from folder and the Designs page - Multi Editor: blueprints keep their name in the file and show their footprint; the Blueprints page has a group drop-down and favorite groups diff --git a/UoFiddler/UoFiddler.csproj b/UoFiddler/UoFiddler.csproj index 91bd1aae..f34840a6 100644 --- a/UoFiddler/UoFiddler.csproj +++ b/UoFiddler/UoFiddler.csproj @@ -9,9 +9,9 @@ UoFiddler UoFiddler Copyright © 2026 - 4.28.1 - 4.28.1 - 4.28.1 + 4.28.2 + 4.28.2 + 4.28.2 true