commit e14d8d82f387b4fb2c463eb15a4d057ec5675ae2 Author: Deukhoofd Date: Mon Aug 18 14:16:34 2025 +0200 Initial port diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cc28fcc --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +bin/ +obj/ +/packages/ +riderModule.iml +/_ReSharper.Caches/ +.idea +*.DotSettings.user +artifacts \ No newline at end of file diff --git a/Atomorph.NET.Demo/Atomorph.NET.Demo.csproj b/Atomorph.NET.Demo/Atomorph.NET.Demo.csproj new file mode 100644 index 0000000..83cc6ee --- /dev/null +++ b/Atomorph.NET.Demo/Atomorph.NET.Demo.csproj @@ -0,0 +1,23 @@ + + + + Exe + net9.0 + enable + enable + + + + + + + + + + + + + + + + diff --git a/Atomorph.NET.Demo/Options.cs b/Atomorph.NET.Demo/Options.cs new file mode 100644 index 0000000..1d022a6 --- /dev/null +++ b/Atomorph.NET.Demo/Options.cs @@ -0,0 +1,347 @@ +using System.CommandLine; +using System.CommandLine.Parsing; + +namespace Atomorph.NET.Demo; + + +public class Options +{ + public bool Verbose { get; set; } + public bool BlendBlobs { get; set; } = false; + public uint Feather { get; set; } = 1; + public byte BlobRgbaWeight { get; set; } = 1; + public byte BlobSizeWeight { get; set; } = 1; + public byte BlobXyWeight { get; set; } = 1; + public ulong BlobNumber { get; set; } = 1; + public bool BlobsAsTexture { get; set; } = true; + public bool BlobsAsAverage { get; set; } = false; + public bool BlobsAsDistinct { get; set; } = false; + public bool BlobsByRgb { get; set; } = false; + public bool BlobsByHsp { get; set; } = true; + public ulong BlobMaxSize { get; set; } = ulong.MaxValue; + public ulong BlobMinSize { get; set; } = 1; + public ushort BlobBoxGrip { get; set; } = ushort.MaxValue; + public ulong BlobBoxSamples { get; set; } = 100; + public double BlobThreshold { get; set; } = 1.0; + public bool Brief { get; set; } = true; + public uint CycleLength { get; set; } = 100000; + public ulong Degenerate { get; set; } = 10000; + public ushort Density { get; set; } = 2; + public bool FadingNone { get; set; } = false; + public bool FadingLinear { get; set; } = false; + public bool FadingCosine { get; set; } = false; + public bool FadingPerlin { get; set; } = true; + public string File { get; set; } = "untitled_morph"; + public bool Finite { get; set; } = false; + public uint Fluid { get; set; } = 0; + public uint FramesOut { get; set; } = 0; + public bool Help { get; set; } = false; + public string Indir { get; set; } = "."; + public bool KeepBackground { get; set; } = false; + public uint MatchTime { get; set; } = 0; + public uint MorphTime { get; set; } = 0; + public bool MotionNone { get; set; } = false; + public bool MotionLinear { get; set; } = false; + public bool MotionSpline { get; set; } = true; + public string Outdir { get; set; } = "."; + public uint Seed { get; set; } = 0; + public uint Threads { get; set; } = 8; + public bool Version { get; set; } = false; + + public ShowBlobs ShowBlobs { get; set; } = ShowBlobs.Texture; + public ColorMethod DifferBlobs { get; set; } = ColorMethod.HSP; + public InterpolationMethod Motion { get; set; } = InterpolationMethod.Spline; + public InterpolationMethod Fading { get; set; } = InterpolationMethod.Perlin; + public int ExitFlag { get; set; } = 0; + public string Name { get; set; } = ""; + public int Height { get; set; } = 0; + public int Width { get; set; } = 0; + + public bool FramesOutDefined { get; set; } = false; + + public List Files { get; set; } = []; + + public static Options Parse(string[] args) + { + var options = new Options(); + + var filesArgument = new Argument("files") + { + Arity = ArgumentArity.ZeroOrMore, + Description = "Input files to morph." + }; + + var verboseOption = new Option("--verbose") + { + Description = "Print verbose messages.", + }; + var blendBlobsOption = new Option("--blend-blobs") + { + Description = "Blob intersections are blended together.", + }; + var blobFeatherOption = new Option("--blob-feather", "-E") + { + Description = "Number of gradually transparent outer layers.", + }; + var blobRgbaWeightOption = new Option("--blob-rgba-weight", "-c") + { + Description = "Importance of a blob's color when matching [0-255].", + }; + var blobSizeWeightOption = new Option("--blob-size-weight", "-z") + { + Description = "Importance of a blob's size when matching [0-255].", + }; + var blobXyWeightOption = new Option("--blob-xy-weight", "-p") + { + Description = "Importance of a blob's location when matching [0-255].", + }; + var blobsOption = new Option("--blobs", "-b") + { + Description = "Preferred number of blobs to keep.", + }; + var blobsAsTextureOption = new Option("--blobs-as-texture") + { + Description = "A blob is textured by its pixels (default).", + Arity = ArgumentArity.Zero, + }; + var blobsAsAverageOption = new Option("--blobs-as-average") + { + Description = "A blob has the average color of its pixels.", + }; + var blobsAsDistinctOption = new Option("--blobs-as-distinct") + { + Description = "A blob has a random color.", + }; + var blobsByRgbOption = new Option("--blobs-by-rgb") + { + Description = "Differentiate blobs by RGB distance.", + }; + var blobsByHspOption = new Option("--blobs-by-hsp") + { + Description = "Differentiate blobs by HSP distance (default).", + }; + var blobsMaxSizeOption = new Option("--blobs-max-size", "-B") + { + Description = "Maximum size of a single blob in pixels.", + CustomParser = HandleNegativeValues, + }; + var blobsMinSizeOption = new Option("--blobs-min-size", "-m") + { + Description = "Minimum size of a single blob in pixels.", + CustomParser = HandleNegativeValues, + }; + var blobsBoxGripOption = new Option("--blobs-box-grip", "-g") + { + Description = "Unifying grip bounds for undersized blobs.", + }; + var blobsBoxSamplesOption = new Option("--blobs-box-samples", "-S") + { + Description = "Number of samples to take for each dust box.", + }; + var blobsThresholdOption = new Option("--blobs-threshold", "-t") + { + Description = "Maximum color difference for merging blobs [0-255].", + }; + var briefOption = new Option("--brief") + { + Description = "Print brief messages (default).", + }; + var cycleLengthOption = new Option("--cycle-length", "-C") + { + Description = "Number of iterations per morph cycle.", + }; + var degenerateOption = new Option("--degenerate", "-d") + { + Description = "Degeneration period for energy minimzation.", + }; + var densityOption = new Option("--density", "-D") + { + Description = "Number of atoms per pixel at minimum.", + }; + var fadingNoneOption = new Option("--fading-none") + { + Description = "Colours are not interpolated.", + }; + var fadingLinearOption = new Option("--fading-linear") + { + Description = "Colours are interpolated linearly.", + }; + var fadingCosineOption = new Option("--fading-cosine") + { + Description = "Colours are cosine interpolated.", + }; + var fadingPerlinOption = new Option("--fading-perlin") + { + Description = "Use Perlin noise colour transition (default).", + }; + var fileOption = new Option("--file", "-f") + { + Description = "Output files with prefix.", + Arity = ArgumentArity.ExactlyOne, + }; + var finiteOption = new Option("--finite") + { + Description = "Morph will not repeat itself seamlessly.", + }; + var fluidOption = new Option("--fluid", "-L") + { + Description = "Number of fluid simulation steps per frame.", + }; + var framesOption = new Option("--frames", "-F") + { + Description = "Number of frames to generate.", + }; + var helpOption = new Option("--help", "-h") + { + Description = "Display this usage information.", + }; + var indirOption = new Option("--indir", "-i") + { + Description = "Read input from this directory.", + Arity = ArgumentArity.ExactlyOne, + }; + var keepBackgroundOption = new Option("--keep-background") + { + Description = "Morph background is cross-dissolved.", + }; + var matchTimeOption = new Option("--match-time", "-M") + { + Description = "Time in seconds given for blob matching.", + }; + var morphTimeOption = new Option("--morph-time", "-O") + { + Description = "Time in seconds given for atom morphing.", + }; + var motionNoneOption = new Option("--motion-none") + { + Description = "Positions are not interpolated.", + }; + var motionLinearOption = new Option("--motion-linear") + { + Description = "Positions are linearly interpolated.", + }; + var motionSplineOption = new Option("--motion-spline") + { + Description = "Uses Catmull-Rom splines (default).", + }; + var outdirOption = new Option("--outdir", "-o") + { + Description = "Write output to this directory.", + }; + var seedOption = new Option("--seed", "-s") + { + Description = "Seed for the random number generator.", + }; + var threadsOption = new Option("--threads", "-T") + { + Description = "Number of worker threads to spawn.", + }; + var versionOption = new Option("--version", "-v") + { + Description = "Show version information.", + }; + + var rootCommand = new RootCommand("Atomorph.NET morphing application") + { + filesArgument, + verboseOption, + blendBlobsOption, + blobFeatherOption, + blobRgbaWeightOption, + blobSizeWeightOption, + blobXyWeightOption, + blobsOption, + blobsAsTextureOption, + blobsAsAverageOption, + blobsAsDistinctOption, + blobsByRgbOption, + blobsByHspOption, + blobsMaxSizeOption, + blobsMinSizeOption, + blobsBoxGripOption, + blobsBoxSamplesOption, + blobsThresholdOption, + briefOption, + cycleLengthOption, + degenerateOption, + densityOption, + fadingNoneOption, + fadingLinearOption, + fadingCosineOption, + fadingPerlinOption, + fileOption, + finiteOption, + fluidOption, + framesOption, + helpOption, + indirOption, + keepBackgroundOption, + matchTimeOption, + morphTimeOption, + motionNoneOption, + motionLinearOption, + motionSplineOption, + outdirOption, + seedOption, + threadsOption, + versionOption + }; + + var parseResult = rootCommand.Parse(args); + options.Files = parseResult.GetValue(filesArgument)?.ToList() ?? []; + options.Verbose = parseResult.GetValue(verboseOption); + options.BlendBlobs = parseResult.GetValue(blendBlobsOption); + options.Feather = parseResult.GetValue(blobFeatherOption); + options.BlobRgbaWeight = parseResult.GetValue(blobRgbaWeightOption); + options.BlobSizeWeight = parseResult.GetValue(blobSizeWeightOption); + options.BlobXyWeight = parseResult.GetValue(blobXyWeightOption); + options.BlobNumber = parseResult.GetValue(blobsOption); + options.BlobsAsTexture = parseResult.GetValue(blobsAsTextureOption); + options.BlobsAsAverage = parseResult.GetValue(blobsAsAverageOption); + options.BlobsAsDistinct = parseResult.GetValue(blobsAsDistinctOption); + options.BlobsByRgb = parseResult.GetValue(blobsByRgbOption); + options.BlobsByHsp = parseResult.GetValue(blobsByHspOption); + options.BlobMaxSize = parseResult.GetValue(blobsMaxSizeOption); + options.BlobMinSize = parseResult.GetValue(blobsMinSizeOption); + options.BlobBoxGrip = parseResult.GetValue(blobsBoxGripOption); + options.BlobBoxSamples = parseResult.GetValue(blobsBoxSamplesOption); + options.BlobThreshold = parseResult.GetValue(blobsThresholdOption); + options.Brief = parseResult.GetValue(briefOption); + options.CycleLength = parseResult.GetValue(cycleLengthOption); + options.Degenerate = parseResult.GetValue(degenerateOption); + options.Density = parseResult.GetValue(densityOption); + options.FadingNone = parseResult.GetValue(fadingNoneOption); + options.FadingLinear = parseResult.GetValue(fadingLinearOption); + options.FadingCosine = parseResult.GetValue(fadingCosineOption); + options.FadingPerlin = parseResult.GetValue(fadingPerlinOption); + options.File = parseResult.GetValue(fileOption) ?? "untitled_morph"; + options.Finite = parseResult.GetValue(finiteOption); + options.Fluid = parseResult.GetValue(fluidOption); + options.FramesOut = parseResult.GetValue(framesOption); + options.FramesOutDefined = options.FramesOut > 0; + options.Help = parseResult.GetValue(helpOption); + options.Indir = parseResult.GetValue(indirOption) ?? "."; + options.KeepBackground = parseResult.GetValue(keepBackgroundOption); + options.MatchTime = parseResult.GetValue(matchTimeOption); + options.MorphTime = parseResult.GetValue(morphTimeOption); + options.MotionNone = parseResult.GetValue(motionNoneOption); + options.MotionLinear = parseResult.GetValue(motionLinearOption); + options.MotionSpline = parseResult.GetValue(motionSplineOption); + options.Outdir = parseResult.GetValue(outdirOption) ?? "."; + options.Seed = parseResult.GetValue(seedOption); + options.Threads = parseResult.GetValue(threadsOption); + options.Version = parseResult.GetValue(versionOption); + + return options; + } + + private static ulong HandleNegativeValues(ArgumentResult result) + { + // Handle negative values as max size + if (result.Tokens.Count > 0 && long.TryParse(result.Tokens[0].Value, out var value) && value < 0) + { + return (ulong.MaxValue - (ulong)(-value)); + } + return ulong.TryParse(result.Tokens[0].Value, out var size) ? size : 1; + } +} \ No newline at end of file diff --git a/Atomorph.NET.Demo/Program.cs b/Atomorph.NET.Demo/Program.cs new file mode 100644 index 0000000..f926672 --- /dev/null +++ b/Atomorph.NET.Demo/Program.cs @@ -0,0 +1,274 @@ +using System.Text; +using Atomorph; +using Atomorph.Models; +using Atomorph.NET.Demo; +using BigGustave; +using Pixel = Atomorph.Models.Pixel; + +public static class Program +{ + public static int Main(string[] args) + { + var options = Options.Parse(args); + if (options.ExitFlag != 0) + return 0; + var programStart = DateTime.UtcNow; + + var morph = new Morph(); + morph.SetBlobDelimiter(ColorMethod.HSP); + morph.SetBlobMaxSize(ulong.MaxValue); + morph.SetBlobMinSize(1); + morph.SetBlobBoxGrip(ushort.MaxValue); + morph.SetBlobBoxSamples(100); + morph.SetBlobThreshold(1.0); + morph.SetBlobNumber(1); + morph.SetSeed(0); + morph.SetBlobRgbaWeight(1); + morph.SetBlobSizeWeight(0); + morph.SetBlobXyWeight(0); + morph.SetDegeneration(10000); + morph.SetDensity(2); // Higher than 1 sets fluid to 0. + morph.SetMotion(InterpolationMethod.Spline); + morph.SetFading(InterpolationMethod.Perlin); + morph.SetThreads(8); + morph.SetCycleLength(100000); + morph.SetFeather(0); + morph.SetKeepBackground(false); + morph.SetFinite(true); + morph.SetShowBlobs(ShowBlobs.Texture); + morph.SetFluid(0); // Higher than 0 sets density to 1. + + if (!LoadFiles(morph, options)) + return -1; + + MainLoop(morph, options); + SaveFiles(morph, options); + var programEnd = DateTime.UtcNow; + + if (options.Verbose) + { + var duration = programEnd - programStart; + Console.WriteLine($"Program completed in {duration.TotalSeconds:0.00} seconds."); + } + + return 0; + // Add your main logic here + } + + private static bool LoadFiles(Morph morph, Options options) + { + StringBuilder buf; + int width, height, error; + int max_width = 0, max_height = 0; + + // Load input image files: + for (var i = 0; i < options.Files.Count; ++i) + { + buf = new(options.Indir); + buf.Append('/'); + buf.Append(options.Files[i]); + + if (options.Verbose) + Console.WriteLine($"Loading {buf} ..."); + using var file = File.OpenRead(buf.ToString()); + var png = Png.Open(file); + width = png.Width; + height = png.Height; + + max_width = Math.Max(max_width, width); + max_height = Math.Max(max_height, height); + + if (options.Verbose) + Console.WriteLine($"{width}x{height} image decoded."); + + if (!FillMorph(morph, (ulong)i, png, (uint)width) && options.Verbose) + { + Console.WriteLine($"Unable to fill {i}th frame."); + } + } + + if (morph.GetFrameCount() == 0) + { + Console.WriteLine("Error. Morph does not contain any key frames."); + return false; + } + + width = max_width; + height = max_height; + morph.SetResolution((ushort)width, (ushort)height); + + return true; + } + + private static bool FillMorph(Morph morph, ulong frame, Png png, uint width) + { + ulong pixel = 0; + bool empty = true; + + if (width > ushort.MaxValue) + return false; + for (var x = 0; x < png.Width; ++x) + { + for (var y = 0; y < png.Height; ++y) + { + var p = png.GetPixel(x, y); + var r = p.R; + var g = p.G; + var b = p.B; + var a = p.A; + + if (a == 0) + continue; + + morph.AddPixel(frame, + new Pixel() + { + X = (ushort)(x), Y = (ushort)(y), Color = new Color(r, g, b, a), + }); + pixel++; + empty = false; + } + } + + if (empty) + morph.AddFrame(frame); + + return true; + } + + private static void MainLoop(Morph morph, Options options) + { + if (options.Verbose) + { + Console.WriteLine($"Blobifying {morph.GetWidth()}x{morph.GetHeight()} morph."); + } + + var start = DateTime.UtcNow; + + ulong blob_count = 0; + ulong largest_frame = 0; + double last_energy = 0.0; + ulong match_blobs = 0; + ulong morph_atoms = 0; + var fs = options.Files.Count; + + while (true) + { + morph.Suspend(); + morph.Synchronize(); + morph.Compute(); + + blob_count = 0; + for (ulong i = 0; i < (ulong)fs; ++i) + { + ulong bc = morph.GetBlobCount(i); + if (bc >= blob_count) + { + blob_count = bc; + largest_frame = i; + } + } + + var morph_state = morph.State; + + var end = DateTime.UtcNow; + if ((end - start).TotalMilliseconds > 1000) + { + if (morph_state is MorphState.BlobDetection or MorphState.BlobUnification) + { + if (options.Verbose) + { + Console.WriteLine( + $"{blob_count}/{morph.GetBlobCount()} blob{(blob_count == 1 ? "" : "s")} remaining on frame {largest_frame}."); + } + } + else if (morph_state == MorphState.BlobMatching) + { + if (options.Verbose) + { + double e = morph.GetEnergy(); + if (last_energy < e) + Console.WriteLine($"Matching blobs, absolute energy was {e:30.10f}."); + else + Console.WriteLine($"Matching blobs, energy decreased by {last_energy - e:30.10f}."); + last_energy = e; + } + if (++match_blobs >= options.MatchTime) + { + morph.NextState(); + last_energy = 0.0; + } + } + else if (morph_state == MorphState.AtomMorphing) + { + if (options.Verbose) + { + double e = morph.GetEnergy(); + if (last_energy < e) + Console.WriteLine($"Matching atoms, absolute energy was {e:30.10f}."); + else + Console.WriteLine($"Matching atoms, energy decreased by {last_energy - e:30.10f}."); + last_energy = e; + } + if (++morph_atoms >= options.MorphTime) + { + morph.NextState(); + } + } + else if (morph_state == MorphState.Done) + { + if (options.Verbose) + Console.WriteLine("All done!\n"); + break; + } + else + { + if (options.Verbose) + Console.WriteLine("Unknown state!\n"); + break; + } + start = DateTime.UtcNow; + } + Thread.Sleep(100); + } + + if (options.Verbose) + { + Console.WriteLine("Frame %lu had the most blobs (%lu).\n", largest_frame, blob_count); + } + + return; + } + + private static void SaveFiles(Morph morph, Options options) + { + for (var i = 0; i < options.FramesOut; ++i) + { + WriteImage(morph, options, (ulong)i, morph.GetWidth(), morph.GetHeight()); + } + } + + private static void WriteImage(Morph morph, Options options, ulong frame_out, uint width, uint height) + { + double t = morph.GetTime(frame_out, options.FramesOut); + + var buf = $"{options.Outdir}/{options.File}_{frame_out + 1:0000}.png"; + if (options.Verbose) + Console.WriteLine($"Rendering {frame_out + 1:0000}. frame ..."); + + var png = PngBuilder.Create((int)width, (int)height, true); + + var pixels = new List(); + morph.GetPixels(t, pixels); + foreach (var pixel in pixels) + { + png.SetPixel(new BigGustave.Pixel(pixel.Color.R, pixel.Color.G, pixel.Color.B, pixel.Color.A, false), + pixel.X, pixel.Y); + } + + if (options.Verbose) + Console.WriteLine($"Writing {buf} ... "); + using var file = File.Create(buf); + png.Save(file); + } +} \ No newline at end of file diff --git a/Atomorph.NET.Demo/Tests/data/RGB_1.png b/Atomorph.NET.Demo/Tests/data/RGB_1.png new file mode 100755 index 0000000..62e1fa2 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/RGB_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/RGB_2.png b/Atomorph.NET.Demo/Tests/data/RGB_2.png new file mode 100755 index 0000000..3f9c398 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/RGB_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/RGB_3.png b/Atomorph.NET.Demo/Tests/data/RGB_3.png new file mode 100755 index 0000000..97d33fd Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/RGB_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/RGB_4.png b/Atomorph.NET.Demo/Tests/data/RGB_4.png new file mode 100755 index 0000000..6948987 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/RGB_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-0.png b/Atomorph.NET.Demo/Tests/data/armors/a-0.png new file mode 100755 index 0000000..efa7153 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-0.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-1.png b/Atomorph.NET.Demo/Tests/data/armors/a-1.png new file mode 100755 index 0000000..1d0e5de Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-10.png b/Atomorph.NET.Demo/Tests/data/armors/a-10.png new file mode 100755 index 0000000..d11250c Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-10.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-11.png b/Atomorph.NET.Demo/Tests/data/armors/a-11.png new file mode 100755 index 0000000..0127c40 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-11.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-12.png b/Atomorph.NET.Demo/Tests/data/armors/a-12.png new file mode 100755 index 0000000..0eaeb52 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-12.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-13.png b/Atomorph.NET.Demo/Tests/data/armors/a-13.png new file mode 100755 index 0000000..3df94db Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-13.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-14.png b/Atomorph.NET.Demo/Tests/data/armors/a-14.png new file mode 100755 index 0000000..69503e5 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-14.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-15.png b/Atomorph.NET.Demo/Tests/data/armors/a-15.png new file mode 100755 index 0000000..6bbee1b Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-15.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-16.png b/Atomorph.NET.Demo/Tests/data/armors/a-16.png new file mode 100755 index 0000000..ba93484 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-16.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-17.png b/Atomorph.NET.Demo/Tests/data/armors/a-17.png new file mode 100755 index 0000000..a272fa1 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-17.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-18.png b/Atomorph.NET.Demo/Tests/data/armors/a-18.png new file mode 100755 index 0000000..b8e434c Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-18.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-19.png b/Atomorph.NET.Demo/Tests/data/armors/a-19.png new file mode 100755 index 0000000..a3f20c0 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-19.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-2.png b/Atomorph.NET.Demo/Tests/data/armors/a-2.png new file mode 100755 index 0000000..e3e2138 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-3.png b/Atomorph.NET.Demo/Tests/data/armors/a-3.png new file mode 100755 index 0000000..2a61788 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-4.png b/Atomorph.NET.Demo/Tests/data/armors/a-4.png new file mode 100755 index 0000000..782bb39 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-5.png b/Atomorph.NET.Demo/Tests/data/armors/a-5.png new file mode 100755 index 0000000..8bcb113 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-6.png b/Atomorph.NET.Demo/Tests/data/armors/a-6.png new file mode 100755 index 0000000..d1f6280 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-6.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-7.png b/Atomorph.NET.Demo/Tests/data/armors/a-7.png new file mode 100755 index 0000000..cd1e11b Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-7.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-8.png b/Atomorph.NET.Demo/Tests/data/armors/a-8.png new file mode 100755 index 0000000..8349955 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-8.png differ diff --git a/Atomorph.NET.Demo/Tests/data/armors/a-9.png b/Atomorph.NET.Demo/Tests/data/armors/a-9.png new file mode 100755 index 0000000..cb8d65a Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/armors/a-9.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/body_1.png b/Atomorph.NET.Demo/Tests/data/battlelord/body_1.png new file mode 100755 index 0000000..f797fe8 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/body_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/body_2.png b/Atomorph.NET.Demo/Tests/data/battlelord/body_2.png new file mode 100755 index 0000000..05aa02a Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/body_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/body_3.png b/Atomorph.NET.Demo/Tests/data/battlelord/body_3.png new file mode 100755 index 0000000..342ae16 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/body_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/body_4.png b/Atomorph.NET.Demo/Tests/data/battlelord/body_4.png new file mode 100755 index 0000000..5251ed3 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/body_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/body_5.png b/Atomorph.NET.Demo/Tests/data/battlelord/body_5.png new file mode 100755 index 0000000..6509e4f Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/body_5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/body_6.png b/Atomorph.NET.Demo/Tests/data/battlelord/body_6.png new file mode 100755 index 0000000..36fbd5f Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/body_6.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/head_1.png b/Atomorph.NET.Demo/Tests/data/battlelord/head_1.png new file mode 100755 index 0000000..9d96d53 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/head_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/head_2.png b/Atomorph.NET.Demo/Tests/data/battlelord/head_2.png new file mode 100755 index 0000000..70d8890 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/head_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/head_3.png b/Atomorph.NET.Demo/Tests/data/battlelord/head_3.png new file mode 100755 index 0000000..d7b35d6 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/head_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/head_4.png b/Atomorph.NET.Demo/Tests/data/battlelord/head_4.png new file mode 100755 index 0000000..856903c Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/head_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/head_5.png b/Atomorph.NET.Demo/Tests/data/battlelord/head_5.png new file mode 100755 index 0000000..c583bc9 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/head_5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/head_6.png b/Atomorph.NET.Demo/Tests/data/battlelord/head_6.png new file mode 100755 index 0000000..8b218c4 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/head_6.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_1.png b/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_1.png new file mode 100755 index 0000000..45bf66d Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_2.png b/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_2.png new file mode 100755 index 0000000..61c88dc Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_3.png b/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_3.png new file mode 100755 index 0000000..731c149 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_4.png b/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_4.png new file mode 100755 index 0000000..010f01c Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_5.png b/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_5.png new file mode 100755 index 0000000..0259745 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_6.png b/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_6.png new file mode 100755 index 0000000..3c80f40 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/lfoot_6.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/lleg_1.png b/Atomorph.NET.Demo/Tests/data/battlelord/lleg_1.png new file mode 100755 index 0000000..6aa1fe3 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/lleg_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/lleg_2.png b/Atomorph.NET.Demo/Tests/data/battlelord/lleg_2.png new file mode 100755 index 0000000..9aae410 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/lleg_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/lleg_3.png b/Atomorph.NET.Demo/Tests/data/battlelord/lleg_3.png new file mode 100755 index 0000000..2bcf5c7 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/lleg_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/lleg_4.png b/Atomorph.NET.Demo/Tests/data/battlelord/lleg_4.png new file mode 100755 index 0000000..b590fb9 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/lleg_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/lleg_5.png b/Atomorph.NET.Demo/Tests/data/battlelord/lleg_5.png new file mode 100755 index 0000000..39f9cde Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/lleg_5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/lleg_6.png b/Atomorph.NET.Demo/Tests/data/battlelord/lleg_6.png new file mode 100755 index 0000000..01603da Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/lleg_6.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rarm_1.png b/Atomorph.NET.Demo/Tests/data/battlelord/rarm_1.png new file mode 100755 index 0000000..ebf12fe Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rarm_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rarm_2.png b/Atomorph.NET.Demo/Tests/data/battlelord/rarm_2.png new file mode 100755 index 0000000..c8e3739 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rarm_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rarm_3.png b/Atomorph.NET.Demo/Tests/data/battlelord/rarm_3.png new file mode 100755 index 0000000..113c118 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rarm_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rarm_4.png b/Atomorph.NET.Demo/Tests/data/battlelord/rarm_4.png new file mode 100755 index 0000000..fdbe970 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rarm_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rarm_5.png b/Atomorph.NET.Demo/Tests/data/battlelord/rarm_5.png new file mode 100755 index 0000000..a3397c4 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rarm_5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rarm_6.png b/Atomorph.NET.Demo/Tests/data/battlelord/rarm_6.png new file mode 100755 index 0000000..04ac3ec Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rarm_6.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_1.png b/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_1.png new file mode 100755 index 0000000..d68bbb5 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_2.png b/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_2.png new file mode 100755 index 0000000..a911129 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_3.png b/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_3.png new file mode 100755 index 0000000..3019e73 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_4.png b/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_4.png new file mode 100755 index 0000000..44f4ca3 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_5.png b/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_5.png new file mode 100755 index 0000000..618b3c2 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_6.png b/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_6.png new file mode 100755 index 0000000..decf705 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rfoot_6.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rhand_1.png b/Atomorph.NET.Demo/Tests/data/battlelord/rhand_1.png new file mode 100755 index 0000000..4a541c6 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rhand_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rhand_2.png b/Atomorph.NET.Demo/Tests/data/battlelord/rhand_2.png new file mode 100755 index 0000000..2495c84 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rhand_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rhand_3.png b/Atomorph.NET.Demo/Tests/data/battlelord/rhand_3.png new file mode 100755 index 0000000..caae23c Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rhand_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rhand_4.png b/Atomorph.NET.Demo/Tests/data/battlelord/rhand_4.png new file mode 100755 index 0000000..1cd519f Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rhand_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rhand_5.png b/Atomorph.NET.Demo/Tests/data/battlelord/rhand_5.png new file mode 100755 index 0000000..13d8517 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rhand_5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rhand_6.png b/Atomorph.NET.Demo/Tests/data/battlelord/rhand_6.png new file mode 100755 index 0000000..7bd4944 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rhand_6.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rleg_1.png b/Atomorph.NET.Demo/Tests/data/battlelord/rleg_1.png new file mode 100755 index 0000000..d6b1d3e Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rleg_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rleg_2.png b/Atomorph.NET.Demo/Tests/data/battlelord/rleg_2.png new file mode 100755 index 0000000..63be968 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rleg_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rleg_3.png b/Atomorph.NET.Demo/Tests/data/battlelord/rleg_3.png new file mode 100755 index 0000000..8a3bb45 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rleg_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rleg_4.png b/Atomorph.NET.Demo/Tests/data/battlelord/rleg_4.png new file mode 100755 index 0000000..b186288 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rleg_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rleg_5.png b/Atomorph.NET.Demo/Tests/data/battlelord/rleg_5.png new file mode 100755 index 0000000..bad70e3 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rleg_5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord/rleg_6.png b/Atomorph.NET.Demo/Tests/data/battlelord/rleg_6.png new file mode 100755 index 0000000..6f83213 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord/rleg_6.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord_1.png b/Atomorph.NET.Demo/Tests/data/battlelord_1.png new file mode 100755 index 0000000..8fe53b6 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord_2.png b/Atomorph.NET.Demo/Tests/data/battlelord_2.png new file mode 100755 index 0000000..a06c5d4 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord_3.png b/Atomorph.NET.Demo/Tests/data/battlelord_3.png new file mode 100755 index 0000000..c7d9fa8 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord_4.png b/Atomorph.NET.Demo/Tests/data/battlelord_4.png new file mode 100755 index 0000000..6fa5e99 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord_5.png b/Atomorph.NET.Demo/Tests/data/battlelord_5.png new file mode 100755 index 0000000..60e9a30 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord_5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/battlelord_6.png b/Atomorph.NET.Demo/Tests/data/battlelord_6.png new file mode 100755 index 0000000..62c6517 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/battlelord_6.png differ diff --git a/Atomorph.NET.Demo/Tests/data/cat_1.png b/Atomorph.NET.Demo/Tests/data/cat_1.png new file mode 100755 index 0000000..b647582 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/cat_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/cat_2.png b/Atomorph.NET.Demo/Tests/data/cat_2.png new file mode 100755 index 0000000..de486c5 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/cat_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/cat_3.png b/Atomorph.NET.Demo/Tests/data/cat_3.png new file mode 100755 index 0000000..17673a5 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/cat_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/cat_4.png b/Atomorph.NET.Demo/Tests/data/cat_4.png new file mode 100755 index 0000000..a45c7b4 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/cat_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/cat_5.png b/Atomorph.NET.Demo/Tests/data/cat_5.png new file mode 100755 index 0000000..95e6feb Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/cat_5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/cat_6.png b/Atomorph.NET.Demo/Tests/data/cat_6.png new file mode 100755 index 0000000..59af76e Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/cat_6.png differ diff --git a/Atomorph.NET.Demo/Tests/data/cd_1.png b/Atomorph.NET.Demo/Tests/data/cd_1.png new file mode 100755 index 0000000..07643a8 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/cd_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/cd_2.png b/Atomorph.NET.Demo/Tests/data/cd_2.png new file mode 100755 index 0000000..24c81be Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/cd_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/cd_3.png b/Atomorph.NET.Demo/Tests/data/cd_3.png new file mode 100755 index 0000000..8832368 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/cd_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/cd_4.png b/Atomorph.NET.Demo/Tests/data/cd_4.png new file mode 100755 index 0000000..0d61991 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/cd_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/dots_1.png b/Atomorph.NET.Demo/Tests/data/dots_1.png new file mode 100755 index 0000000..af0ca01 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/dots_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/dots_2.png b/Atomorph.NET.Demo/Tests/data/dots_2.png new file mode 100755 index 0000000..b9c878f Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/dots_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/dots_3.png b/Atomorph.NET.Demo/Tests/data/dots_3.png new file mode 100755 index 0000000..842b2f9 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/dots_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/dots_4.png b/Atomorph.NET.Demo/Tests/data/dots_4.png new file mode 100755 index 0000000..363bf8c Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/dots_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/empty.png b/Atomorph.NET.Demo/Tests/data/empty.png new file mode 100755 index 0000000..64d75fc Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/empty.png differ diff --git a/Atomorph.NET.Demo/Tests/data/flowers.png b/Atomorph.NET.Demo/Tests/data/flowers.png new file mode 100755 index 0000000..397da83 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/flowers.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/berry_1.png b/Atomorph.NET.Demo/Tests/data/food/berry_1.png new file mode 100755 index 0000000..db0760f Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/berry_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/berry_2.png b/Atomorph.NET.Demo/Tests/data/food/berry_2.png new file mode 100755 index 0000000..85a80e3 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/berry_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/berry_3.png b/Atomorph.NET.Demo/Tests/data/food/berry_3.png new file mode 100755 index 0000000..b98057e Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/berry_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/berry_4.png b/Atomorph.NET.Demo/Tests/data/food/berry_4.png new file mode 100755 index 0000000..17f5bd6 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/berry_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/berry_5.png b/Atomorph.NET.Demo/Tests/data/food/berry_5.png new file mode 100755 index 0000000..68d2c87 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/berry_5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/berry_6.png b/Atomorph.NET.Demo/Tests/data/food/berry_6.png new file mode 100755 index 0000000..46ef864 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/berry_6.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/fruit_1.png b/Atomorph.NET.Demo/Tests/data/food/fruit_1.png new file mode 100755 index 0000000..82fd836 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/fruit_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/fruit_2.png b/Atomorph.NET.Demo/Tests/data/food/fruit_2.png new file mode 100755 index 0000000..5a3e51f Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/fruit_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/fruit_3.png b/Atomorph.NET.Demo/Tests/data/food/fruit_3.png new file mode 100755 index 0000000..e4ff8b2 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/fruit_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/lettuce_1.png b/Atomorph.NET.Demo/Tests/data/food/lettuce_1.png new file mode 100755 index 0000000..42b81de Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/lettuce_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/lettuce_2.png b/Atomorph.NET.Demo/Tests/data/food/lettuce_2.png new file mode 100755 index 0000000..78d553a Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/lettuce_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/lettuce_3.png b/Atomorph.NET.Demo/Tests/data/food/lettuce_3.png new file mode 100755 index 0000000..0299a7b Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/lettuce_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/lettuce_4.png b/Atomorph.NET.Demo/Tests/data/food/lettuce_4.png new file mode 100755 index 0000000..9a9d7f5 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/lettuce_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/lettuce_5.png b/Atomorph.NET.Demo/Tests/data/food/lettuce_5.png new file mode 100755 index 0000000..35fa577 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/lettuce_5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/lettuce_6.png b/Atomorph.NET.Demo/Tests/data/food/lettuce_6.png new file mode 100755 index 0000000..8ec0a02 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/lettuce_6.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/spice_1.png b/Atomorph.NET.Demo/Tests/data/food/spice_1.png new file mode 100755 index 0000000..b1c7fda Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/spice_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/spice_2.png b/Atomorph.NET.Demo/Tests/data/food/spice_2.png new file mode 100755 index 0000000..7201f54 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/spice_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/spice_3.png b/Atomorph.NET.Demo/Tests/data/food/spice_3.png new file mode 100755 index 0000000..4d5f1ef Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/spice_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/spice_4.png b/Atomorph.NET.Demo/Tests/data/food/spice_4.png new file mode 100755 index 0000000..6223950 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/spice_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/spice_5.png b/Atomorph.NET.Demo/Tests/data/food/spice_5.png new file mode 100755 index 0000000..dbbf5d5 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/spice_5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/food/spice_6.png b/Atomorph.NET.Demo/Tests/data/food/spice_6.png new file mode 100755 index 0000000..0b4a80a Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/food/spice_6.png differ diff --git a/Atomorph.NET.Demo/Tests/data/mage_1.png b/Atomorph.NET.Demo/Tests/data/mage_1.png new file mode 100755 index 0000000..98342dd Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/mage_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/mage_2.png b/Atomorph.NET.Demo/Tests/data/mage_2.png new file mode 100755 index 0000000..00c24cd Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/mage_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/mage_3.png b/Atomorph.NET.Demo/Tests/data/mage_3.png new file mode 100755 index 0000000..fd7993c Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/mage_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/mage_4.png b/Atomorph.NET.Demo/Tests/data/mage_4.png new file mode 100755 index 0000000..5e3b9bb Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/mage_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/mage_5.png b/Atomorph.NET.Demo/Tests/data/mage_5.png new file mode 100755 index 0000000..5c1728d Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/mage_5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/merilin.png b/Atomorph.NET.Demo/Tests/data/merilin.png new file mode 100755 index 0000000..36ffab3 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/merilin.png differ diff --git a/Atomorph.NET.Demo/Tests/data/monsters/baron.png b/Atomorph.NET.Demo/Tests/data/monsters/baron.png new file mode 100755 index 0000000..ad2d72a Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/monsters/baron.png differ diff --git a/Atomorph.NET.Demo/Tests/data/monsters/cd.png b/Atomorph.NET.Demo/Tests/data/monsters/cd.png new file mode 100755 index 0000000..36d3ac7 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/monsters/cd.png differ diff --git a/Atomorph.NET.Demo/Tests/data/monsters/cg.png b/Atomorph.NET.Demo/Tests/data/monsters/cg.png new file mode 100755 index 0000000..5b2613c Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/monsters/cg.png differ diff --git a/Atomorph.NET.Demo/Tests/data/monsters/d.png b/Atomorph.NET.Demo/Tests/data/monsters/d.png new file mode 100755 index 0000000..bf35a08 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/monsters/d.png differ diff --git a/Atomorph.NET.Demo/Tests/data/monsters/hero.png b/Atomorph.NET.Demo/Tests/data/monsters/hero.png new file mode 100755 index 0000000..eeb3189 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/monsters/hero.png differ diff --git a/Atomorph.NET.Demo/Tests/data/monsters/hk.png b/Atomorph.NET.Demo/Tests/data/monsters/hk.png new file mode 100755 index 0000000..399afd3 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/monsters/hk.png differ diff --git a/Atomorph.NET.Demo/Tests/data/monsters/imp.png b/Atomorph.NET.Demo/Tests/data/monsters/imp.png new file mode 100755 index 0000000..ca83b8b Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/monsters/imp.png differ diff --git a/Atomorph.NET.Demo/Tests/data/monsters/mc.png b/Atomorph.NET.Demo/Tests/data/monsters/mc.png new file mode 100755 index 0000000..bab962c Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/monsters/mc.png differ diff --git a/Atomorph.NET.Demo/Tests/data/monsters/pain.png b/Atomorph.NET.Demo/Tests/data/monsters/pain.png new file mode 100755 index 0000000..b529878 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/monsters/pain.png differ diff --git a/Atomorph.NET.Demo/Tests/data/monsters/revenant.png b/Atomorph.NET.Demo/Tests/data/monsters/revenant.png new file mode 100755 index 0000000..fa7e428 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/monsters/revenant.png differ diff --git a/Atomorph.NET.Demo/Tests/data/monsters/sg.png b/Atomorph.NET.Demo/Tests/data/monsters/sg.png new file mode 100755 index 0000000..ed80458 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/monsters/sg.png differ diff --git a/Atomorph.NET.Demo/Tests/data/monsters/spider.png b/Atomorph.NET.Demo/Tests/data/monsters/spider.png new file mode 100755 index 0000000..d7aaa3b Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/monsters/spider.png differ diff --git a/Atomorph.NET.Demo/Tests/data/monsters/vile.png b/Atomorph.NET.Demo/Tests/data/monsters/vile.png new file mode 100755 index 0000000..a145cdc Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/monsters/vile.png differ diff --git a/Atomorph.NET.Demo/Tests/data/monsters/zm.png b/Atomorph.NET.Demo/Tests/data/monsters/zm.png new file mode 100755 index 0000000..bb4a020 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/monsters/zm.png differ diff --git a/Atomorph.NET.Demo/Tests/data/otu_1.png b/Atomorph.NET.Demo/Tests/data/otu_1.png new file mode 100755 index 0000000..68c14d6 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/otu_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/otu_2.png b/Atomorph.NET.Demo/Tests/data/otu_2.png new file mode 100755 index 0000000..1d41467 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/otu_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/otu_3.png b/Atomorph.NET.Demo/Tests/data/otu_3.png new file mode 100755 index 0000000..a4037f4 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/otu_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/regenmorph_clouds.png b/Atomorph.NET.Demo/Tests/data/regenmorph_clouds.png new file mode 100755 index 0000000..801147f Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/regenmorph_clouds.png differ diff --git a/Atomorph.NET.Demo/Tests/data/regenmorph_face.png b/Atomorph.NET.Demo/Tests/data/regenmorph_face.png new file mode 100755 index 0000000..2a6778b Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/regenmorph_face.png differ diff --git a/Atomorph.NET.Demo/Tests/data/shape_1.png b/Atomorph.NET.Demo/Tests/data/shape_1.png new file mode 100755 index 0000000..dfd8124 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/shape_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/shape_2.png b/Atomorph.NET.Demo/Tests/data/shape_2.png new file mode 100755 index 0000000..e6cedf5 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/shape_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/shape_3.png b/Atomorph.NET.Demo/Tests/data/shape_3.png new file mode 100755 index 0000000..403c286 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/shape_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/shape_4.png b/Atomorph.NET.Demo/Tests/data/shape_4.png new file mode 100755 index 0000000..53edbc7 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/shape_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/shape_5.png b/Atomorph.NET.Demo/Tests/data/shape_5.png new file mode 100755 index 0000000..3fb16d7 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/shape_5.png differ diff --git a/Atomorph.NET.Demo/Tests/data/shape_6.png b/Atomorph.NET.Demo/Tests/data/shape_6.png new file mode 100755 index 0000000..8cde1ed Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/shape_6.png differ diff --git a/Atomorph.NET.Demo/Tests/data/squares_1.png b/Atomorph.NET.Demo/Tests/data/squares_1.png new file mode 100755 index 0000000..9715e33 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/squares_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/squares_2.png b/Atomorph.NET.Demo/Tests/data/squares_2.png new file mode 100755 index 0000000..2fdf8ac Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/squares_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/squares_3.png b/Atomorph.NET.Demo/Tests/data/squares_3.png new file mode 100755 index 0000000..9ecff44 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/squares_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/squares_4.png b/Atomorph.NET.Demo/Tests/data/squares_4.png new file mode 100755 index 0000000..09e0f81 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/squares_4.png differ diff --git a/Atomorph.NET.Demo/Tests/data/transformer_1.png b/Atomorph.NET.Demo/Tests/data/transformer_1.png new file mode 100755 index 0000000..fc1d780 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/transformer_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/transformer_2.png b/Atomorph.NET.Demo/Tests/data/transformer_2.png new file mode 100755 index 0000000..c159a5f Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/transformer_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/volatile_1.png b/Atomorph.NET.Demo/Tests/data/volatile_1.png new file mode 100755 index 0000000..143c062 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/volatile_1.png differ diff --git a/Atomorph.NET.Demo/Tests/data/volatile_2.png b/Atomorph.NET.Demo/Tests/data/volatile_2.png new file mode 100755 index 0000000..dc2f5d4 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/volatile_2.png differ diff --git a/Atomorph.NET.Demo/Tests/data/volatile_3.png b/Atomorph.NET.Demo/Tests/data/volatile_3.png new file mode 100755 index 0000000..b41277a Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/volatile_3.png differ diff --git a/Atomorph.NET.Demo/Tests/data/volatile_4.png b/Atomorph.NET.Demo/Tests/data/volatile_4.png new file mode 100755 index 0000000..eeeca92 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/data/volatile_4.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0001.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0001.png new file mode 100644 index 0000000..c1a5e9a Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0001.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0002.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0002.png new file mode 100644 index 0000000..fb6779e Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0002.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0003.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0003.png new file mode 100644 index 0000000..4da4ea6 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0003.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0004.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0004.png new file mode 100644 index 0000000..196c96d Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0004.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0005.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0005.png new file mode 100644 index 0000000..95bb06b Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0005.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0006.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0006.png new file mode 100644 index 0000000..c9a63fd Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0006.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0007.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0007.png new file mode 100644 index 0000000..7d1cfc3 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0007.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0008.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0008.png new file mode 100644 index 0000000..7b9fd9d Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0008.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0009.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0009.png new file mode 100644 index 0000000..a03100c Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0009.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0010.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0010.png new file mode 100644 index 0000000..c99271d Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0010.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0011.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0011.png new file mode 100644 index 0000000..bf22410 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0011.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0012.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0012.png new file mode 100644 index 0000000..2335699 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0012.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0013.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0013.png new file mode 100644 index 0000000..3763894 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0013.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0014.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0014.png new file mode 100644 index 0000000..6367dd8 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0014.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0015.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0015.png new file mode 100644 index 0000000..0aa7539 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0015.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0016.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0016.png new file mode 100644 index 0000000..8f9ab7a Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0016.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0017.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0017.png new file mode 100644 index 0000000..cc26904 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0017.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0018.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0018.png new file mode 100644 index 0000000..87408db Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0018.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0019.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0019.png new file mode 100644 index 0000000..75e1034 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0019.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0020.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0020.png new file mode 100644 index 0000000..411cdb4 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0020.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0021.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0021.png new file mode 100644 index 0000000..68f9b66 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0021.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0022.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0022.png new file mode 100644 index 0000000..f4a4778 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0022.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0023.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0023.png new file mode 100644 index 0000000..19525a3 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0023.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0024.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0024.png new file mode 100644 index 0000000..a30ee9d Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0024.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0025.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0025.png new file mode 100644 index 0000000..cdaf7c7 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0025.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0026.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0026.png new file mode 100644 index 0000000..a2919f2 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0026.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0027.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0027.png new file mode 100644 index 0000000..91010d9 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0027.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0028.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0028.png new file mode 100644 index 0000000..6f57aa7 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0028.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0029.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0029.png new file mode 100644 index 0000000..868d74e Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0029.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0030.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0030.png new file mode 100644 index 0000000..43cfbda Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0030.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0031.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0031.png new file mode 100644 index 0000000..db0d50a Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0031.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0032.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0032.png new file mode 100644 index 0000000..5ee9fc4 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0032.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0033.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0033.png new file mode 100644 index 0000000..0940035 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0033.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0034.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0034.png new file mode 100644 index 0000000..48268f9 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0034.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0035.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0035.png new file mode 100644 index 0000000..1fc605c Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0035.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0036.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0036.png new file mode 100644 index 0000000..0140bfb Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0036.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0037.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0037.png new file mode 100644 index 0000000..4be096f Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0037.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0038.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0038.png new file mode 100644 index 0000000..e7e7aab Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0038.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0039.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0039.png new file mode 100644 index 0000000..f62a0b9 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0039.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0040.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0040.png new file mode 100644 index 0000000..8a9f9fd Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0040.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0041.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0041.png new file mode 100644 index 0000000..13f0280 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0041.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0042.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0042.png new file mode 100644 index 0000000..7142e0c Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0042.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0043.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0043.png new file mode 100644 index 0000000..35c87e1 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0043.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0044.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0044.png new file mode 100644 index 0000000..d76f4fa Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0044.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0045.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0045.png new file mode 100644 index 0000000..aa0f8b2 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0045.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0046.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0046.png new file mode 100644 index 0000000..86aefd5 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0046.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0047.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0047.png new file mode 100644 index 0000000..9840ccb Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0047.png differ diff --git a/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0048.png b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0048.png new file mode 100644 index 0000000..0280824 Binary files /dev/null and b/Atomorph.NET.Demo/Tests/output/test_${TITLE}_0048.png differ diff --git a/Atomorph.NET.Demo/Tests/test_battlelord.sh b/Atomorph.NET.Demo/Tests/test_battlelord.sh new file mode 100755 index 0000000..398a5c5 --- /dev/null +++ b/Atomorph.NET.Demo/Tests/test_battlelord.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# ImageMagick is needed for these tests to run properly. +set -e + +mkdir -p output +cd output + +# TEST: Battle Lord +TITLE="battlelord" +dotnet run --project ../../Atomorph.NET.Demo.csproj -- -f test_${TITLE} -i ../data --blobs-as-texture battlelord_1.png battlelord_2.png battlelord_3.png battlelord_4.png battlelord_5.png battlelord_6.png -F 48 --verbose -m -1 -O 60 -D 2 +convert -channel A -threshold 99% -delay 10 -loop 0 -dispose background test_${TITLE}_*.png test_${TITLE}.gif +montage test_${TITLE}_*.png -tile 8x6 -geometry 64x64+1+1 -frame 3 -background white -bordercolor white montage_${TITLE}.png +rm test_${TITLE}_*.png +convert montage_${TITLE}.png -background white -flatten -quality 50 montage_${TITLE}.jpg +rm montage_${TITLE}.png + diff --git a/Atomorph.NET.sln b/Atomorph.NET.sln new file mode 100644 index 0000000..998436c --- /dev/null +++ b/Atomorph.NET.sln @@ -0,0 +1,27 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Atomorph.NET", "Atomorph.NET\Atomorph.NET.csproj", "{5DC71CB8-04ED-4669-BC23-94C9A9CFFC8C}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Demo", "Demo", "{BC8CD2E2-5841-4DA5-8854-A6739E16D65F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Atomorph.NET.Demo", "Atomorph.NET.Demo\Atomorph.NET.Demo.csproj", "{3163204D-DB4B-4EE3-8266-708ADDE05B27}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5DC71CB8-04ED-4669-BC23-94C9A9CFFC8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5DC71CB8-04ED-4669-BC23-94C9A9CFFC8C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5DC71CB8-04ED-4669-BC23-94C9A9CFFC8C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5DC71CB8-04ED-4669-BC23-94C9A9CFFC8C}.Release|Any CPU.Build.0 = Release|Any CPU + {3163204D-DB4B-4EE3-8266-708ADDE05B27}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3163204D-DB4B-4EE3-8266-708ADDE05B27}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3163204D-DB4B-4EE3-8266-708ADDE05B27}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3163204D-DB4B-4EE3-8266-708ADDE05B27}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {3163204D-DB4B-4EE3-8266-708ADDE05B27} = {BC8CD2E2-5841-4DA5-8854-A6739E16D65F} + EndGlobalSection +EndGlobal diff --git a/Atomorph.NET/Atomorph.NET.csproj b/Atomorph.NET/Atomorph.NET.csproj new file mode 100644 index 0000000..88a01a3 --- /dev/null +++ b/Atomorph.NET/Atomorph.NET.csproj @@ -0,0 +1,14 @@ + + + + netstandard2.1 + enable + 12 + Atomorph + + + + + + + diff --git a/Atomorph.NET/AtomorphThread.cs b/Atomorph.NET/AtomorphThread.cs new file mode 100644 index 0000000..dad457a --- /dev/null +++ b/Atomorph.NET/AtomorphThread.cs @@ -0,0 +1,1383 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Atomorph.Models; +using Pcg; + +namespace Atomorph; + +public class AtomorphThread : IDisposable +{ + private Dictionary _frames = new(); + private Dictionary _chains = new(); + + private ushort _pointDensity = 1; + private Blob[][]? _blobMap; + private ulong _blobMapW; + private ulong _blobMapH; + private double _blobMapE; + private double _bestBlobMapE; + + private double _chainMapE; + + private ushort _bBoxX1 = ushort.MaxValue; + private ushort _bBoxY1 = ushort.MaxValue; + private ushort _bBoxX2 = 0; + private ushort _bBoxY2 = 0; + private uint _bBoxD = 0; // Squared diagonal length + + private ColorMethod _blobDelimiter = ColorMethod.HSP; + private double _blobThreshold = 1.0; + private ulong _blobMaxSize = 1000; + private ulong _blobMinSize = 1; + + private ushort _blobBoxGrip = ushort.MaxValue; + private ulong _blobBoxSamples = 10; + private ulong _blobNumber = 1; + private ulong _threadCount = 0; + private ulong _cycleLength = 1; + + private double _blobRgbaWeight = 0.33; + private double _blobSizeWeight = 0.33; + private double _blobXyWeight = 0.34; + + private bool _skipState = false; + private ulong _degenerate = 0; + private ulong _counter = 0; + private double _bestE; + private bool _deviant; + + private PcgRandom _random = new(); + + private ulong _iterations; + private double _seconds; + + private volatile bool _signalStop; + private volatile bool _signalPause; + private volatile bool _running; + private volatile bool _paused = true; + private Thread? _stepThread; + private ulong _identifier = ulong.MaxValue; + + public MorphState State { get; private set; } = MorphState.BlobDetection; + public uint Seed { get; private set; } = 0; + + public ulong Identifier + { + get => _identifier; + internal set + { + if (_paused) + _identifier = value; + } + } + + // Constructors + public AtomorphThread() + { + Clear(); + } + + // Public methods + public void NextState() + { + _skipState = true; + } + + + public Frame? GetFrame(ulong nr) => _frames.GetValueOrDefault(nr); + public IReadOnlyDictionary Chains => _chains; + + public void SetFrame(ulong nr, Frame framePt) + { + if (_running && !_paused) return; + + if (!_frames.TryGetValue(nr, out var f)) + { + f = new Frame(); + _frames[nr] = f; + } + + foreach (var fPixel in framePt.Pixels) + { + f.Pixels[fPixel.Key] = fPixel.Value; + } + f.X = framePt.X; + f.Y = framePt.Y; + f.R = framePt.R; + f.G = framePt.G; + f.B = framePt.B; + f.A = framePt.A; + f.FirstExpansion = 0; + f.FirstDust = 0; + + // Refresh frame indexes: + ulong index = 0; + foreach (var frame in _frames) + { + frame.Value.Index = index++; + } + } + + public ulong GetBlobCount(ulong f) + { + if (!HasFrame(f)) return 0; + return (ulong)_frames[f].Blobs.Count; + } + + public ulong GetBlobCount() + { + ulong count = 0; + foreach (var it in _frames) + { + count += GetBlobCount(it.Key); + } + return count; + } + + public void SetBbox(ushort x1, ushort y1, ushort x2, ushort y2) + { + if (_running && !_paused) return; + if (x1 > x2 || y1 > y2) return; + + _bBoxX1 = x1; + _bBoxX2 = x2; + _bBoxY1 = y1; + _bBoxY2 = y2; + + int dx = _bBoxX2 - _bBoxX1; + int dy = _bBoxY2 - _bBoxY1; + _bBoxD = (uint)(dx * dx + dy * dy); + } + + public void SetBlobWeights(byte rgba, byte size, byte xy) + { + if (_running && !_paused) return; + double sum = rgba * rgba + size * size + xy * xy; + if (sum == 0.0) return; + + _blobRgbaWeight = rgba * rgba / sum; + _blobSizeWeight = size * size / sum; + _blobXyWeight = 1.0 - (_blobRgbaWeight + _blobSizeWeight); + } + + public bool Clear() + { + if (_running && !_paused) return false; + + _blobMap = null; + _blobMapW = 0; + _blobMapH = 0; + _blobMapE = 0.0; + _bestBlobMapE = 0.0; + + _bestE = double.PositiveInfinity; + _chainMapE = double.PositiveInfinity; + _deviant = false; + + _frames.Clear(); + _chains.Clear(); + + State = MorphState.BlobDetection; + Identifier = ulong.MaxValue; + _counter = 1; + + _bBoxX1 = ushort.MaxValue; + _bBoxY1 = ushort.MaxValue; + _bBoxX2 = 0; + _bBoxY2 = 0; + _bBoxD = 0; + + return true; + } + + public void SetSeed(uint seed) + { + if (_running && !_paused) return; + Seed = seed; + _random = new PcgRandom((int)Convert.ChangeType(seed, typeof(int))); + } + + public void SetBlobDelimiter(ColorMethod d) + { + if (_paused) _blobDelimiter = d; + } + + public void SetBlobThreshold(double t) + { + if (_paused) _blobThreshold = t; + } + + public void SetBlobMaxSize(ulong s) + { + if (_paused) _blobMaxSize = s; + } + + public void SetBlobMinSize(ulong s) + { + if (_paused) _blobMinSize = s; + } + + public void SetBlobBoxGrip(ushort g) + { + if (_paused) _blobBoxGrip = g; + } + + public void SetBlobBoxSamples(ulong s) + { + if (_paused) _blobBoxSamples = s; + } + + public void SetBlobNumber(ulong n) + { + if (_paused) _blobNumber = n; + } + + public void SetDegeneration(ulong d) + { + if (_paused) _degenerate = d; + } + + public void SetDensity(ushort d) + { + if (_paused) _pointDensity = d; + } + + public void SetThreads(ulong n) + { + if (_paused) _threadCount = n; + } + + public void SetCycleLength(ulong l) + { + if (_paused) _cycleLength = l; + } + + public bool IsRunning() => _running; + public bool IsPaused() => _paused; + + public void Stop() + { + _signalStop = true; + while (_running) Thread.Sleep(0); + _stepThread?.Join(); + } + + public void Start() + { + _running = true; + _stepThread = new Thread(Run) { Name = "AtomorphThread", }; + _stepThread.Start(); + } + + public void Pause() + { + _signalPause = true; + } + + public void Resume() + { + _paused = false; + } + + public void Start(ulong iterations) + { + if (!IsPaused()) return; + _iterations = iterations; + Resume(); + } + + public void Resume(ulong iterations) + { + if (!IsPaused()) return; + _iterations = iterations; + Resume(); + } + + public void Start(double seconds) + { + if (!IsPaused()) return; + _seconds = seconds; + Resume(); + } + + public void Resume(double seconds) + { + if (!IsPaused()) return; + _seconds = seconds; + Resume(); + } + + // Private methods + private double BlobDistance(Blob? b1, Blob? b2) + { + ulong sz1 = (ulong)b1.Surface.Count; + ulong sz2 = (ulong)b2.Surface.Count; + ulong szs = sz1 + sz2; + double pix_dist = 0.0; + double col_dist = 0.0; + double siz_dist = 0.0; + + if (szs > 0) + { + siz_dist = Math.Abs((double)(sz1) - sz2) / szs; + } + + if (sz1 > 0 && sz2 > 0) + { + var p1 = new Pixel() + { + X = (ushort)b1.X, Y = (ushort)b1.Y, Color = ColorUtilities.CreateColor(b1.R, b1.G, b1.B, b1.A), + }; + var p2 = new Pixel() + { + X = (ushort)b2.X, Y = (ushort)b2.Y, Color = ColorUtilities.CreateColor(b2.R, b2.G, b2.B, b2.A), + }; + + pix_dist = Math.Sqrt((double)(AtomorphUtilities.PixelDistance(p1, p2)) / _bBoxD); + col_dist = ColorUtilities.ColorDistance(p1.Color, p2.Color); + } + + return (_blobXyWeight * pix_dist + _blobRgbaWeight * col_dist + _blobSizeWeight * siz_dist); + } + + private Pixel GetPixel(ulong frame, ulong position) + { + if (!HasPixel(frame, position)) + return new Pixel(); + return _frames[frame].Pixels[position]; + } + + private bool Blobify() + { + bool done = true; + foreach (var frame in _frames) + { + done &= BlobifyFrame(frame.Key); + } + + return done; + } + + private bool Unify() + { + bool done = true; + foreach (var frame in _frames) + { + done &= UnifyFrame(frame.Key); + } + + return done; + } + + private bool Match() + { + if (_blobMap == null) + { + // Find the frame with the largest number of blobs. + ulong blob_count = 0; + ulong frame_count = 0; + foreach (var it in _frames) + { + var f = it.Value; + if (blob_count < (ulong)f.Blobs.Count) + { + blob_count = (ulong)f.Blobs.Count; + } + frame_count++; + } + + _blobMapW = blob_count; + _blobMapH = frame_count; + + ulong i = 0; + _blobMap = new Blob[_blobMapW][]; + if (_blobMap is not null) + { + for (i = 0; i < _blobMapW; ++i) + { + _blobMap[i] = new Blob[_blobMapH]; + } + + // Fill blob map with pointers to real blobs. + ulong f = 0; + foreach (var it in _frames) + { + var fp = it.Value; + + // Add empty blobs if needed. + while ((ulong)fp.Blobs.Count < blob_count) + { + var new_blob = new Blob() + { + X = fp.X, + Y = fp.Y, + R = fp.R, + G = fp.G, + B = fp.B, + A = fp.A, + Unified = true, + Index = (ulong)fp.Blobs.Count, + }; + fp.Blobs.Add(new_blob); + } + + ulong blobs = (ulong)fp.Blobs.Count; + + fp.Blobs.RandomShuffle(_random); + + for (ulong b = 0; b < blobs; ++b) + { + _blobMap[b][f] = fp.Blobs[(int)b]; + fp.Blobs[(int)b].Group = b; + fp.Blobs[(int)b].Index = b; + } + ++f; + } + + _blobMapE = GetEnergy(_blobMap!); + } + + return false; + } + + if (_blobMapH == 0 || _blobMapW <= 1) return true; + + // Pick 2 blobs randomly and swap them if it would decrease the energy. + ulong x1, x2; + ulong y = (ulong)_random.Next(0, (int)(_blobMapH - 1)); + ulong y_next = (y + 1) % _blobMapH; + ulong y_prev = (y > 0 ? y - 1 : _blobMapH - 1); + + x1 = (ulong)_random.Next(0, (int)(_blobMapW - 1)); + do + { + x2 = (ulong)_random.Next(0, (int)(_blobMapW - 1)); + } while (x1 == x2); + + var x1_y_prev = _blobMap[x1][y_prev]; + var x2_y_prev = _blobMap[x2][y_prev]; + var x1_y = _blobMap[x1][y]; + var x2_y = _blobMap[x2][y]; + var x1_y_next = _blobMap[x1][y_next]; + var x2_y_next = _blobMap[x2][y_next]; + + bool x1_volatile = !x1_y.Surface.Any(); + bool x2_volatile = !x2_y.Surface.Any(); + + if (x1_volatile && x2_volatile) + { + return false; // No point to swap empty blobs. + } + + double x1_e_before = BlobDistance(x1_y_prev, x1_y) + BlobDistance(x1_y, x1_y_next); + double x2_e_before = BlobDistance(x2_y_prev, x2_y) + BlobDistance(x2_y, x2_y_next); + double x1_e_after = BlobDistance(x2_y_prev, x1_y) + BlobDistance(x1_y, x2_y_next); + double x2_e_after = BlobDistance(x1_y_prev, x2_y) + BlobDistance(x2_y, x1_y_next); + + double c1 = x1_e_before + x2_e_before; + double c2 = x1_e_after + x2_e_after; + + if (c1 >= c2 || (_degenerate != 0 && (_counter % _degenerate) == 0)) + { + var buf = _blobMap[x2][y]; + _blobMap[x2][y] = _blobMap[x1][y]; + _blobMap[x1][y] = buf; + double gain = c1 - c2; + + _blobMapE -= gain; + if (_blobMapE < 0.0) _blobMapE = 0.0; + + if (_blobMapE < _bestE) + { + _bestE = _blobMapE; + _bestBlobMapE = _bestE; + _counter = 0; + + if (_deviant) + { + // Refresh all groups. + for (ulong j = 0; j < _blobMapH; ++j) + { + for (ulong i = 0; i < _blobMapW; ++i) + { + _blobMap[i][j].Group = i; + } + } + } + else + { + _blobMap[x1][y].Group = x1; + _blobMap[x2][y].Group = x2; + } + _deviant = false; + } + else _deviant = true; + } + + if (_bestE == 0.0) return true; + + return false; + } +#if ATOMORPH_OPENCV + // TODO: Implement Morphing using OpenCV + private bool Morph() + { + } + +#else + private static object morph_mutex = new object(); + + private static void MorphAsync(Point[][] map, ulong width, ulong height, ulong repeat, uint rngSeed, + ref double gain) + { + var random = new PcgRandom((int)rngSeed); + + ulong y = (ulong)random.Next(0, (int)(height - 1)); + ulong y_next = (y + 1) % (height); + ulong y_prev = (y > 0 ? y - 1 : height - 1); + + for (ulong i = 0; i < repeat; ++i) + { + ulong x1, x2; + x1 = (ulong)random.Next(0, (int)(width - 1)); + do + { + x2 = (ulong)random.Next(0, (int)(width - 1)); + } while (x1 == x2); + + var x1_y_prev = map[x1][y_prev]; + var x2_y_prev = map[x2][y_prev]; + var x1_y = map[x1][y]; + var x2_y = map[x2][y]; + var x1_y_next = map[x1][y_next]; + var x2_y_next = map[x2][y_next]; + + double x1_e_before = AtomorphUtilities.PointDistance(x1_y_prev, x1_y) + + AtomorphUtilities.PointDistance(x1_y, x1_y_next); + double x2_e_before = AtomorphUtilities.PointDistance(x2_y_prev, x2_y) + + AtomorphUtilities.PointDistance(x2_y, x2_y_next); + double x1_e_after = AtomorphUtilities.PointDistance(x2_y_prev, x1_y) + + AtomorphUtilities.PointDistance(x1_y, x2_y_next); + double x2_e_after = AtomorphUtilities.PointDistance(x1_y_prev, x2_y) + + AtomorphUtilities.PointDistance(x2_y, x1_y_next); + + double c1 = x1_e_before + x2_e_before; + double c2 = x1_e_after + x2_e_after; + + if (c1 >= c2) + { + lock (morph_mutex) + { + if (map[x1][y].Word != x1_y.Word || map[x2][y].Word != x2_y.Word) + continue; + var buf = map[x2][y]; + map[x2][y] = map[x1][y]; + map[x1][y] = buf; + gain += c1 - c2; + } + } + } + } + + private bool Morph() + { + var ch = _chains[_counter % _blobMapW]; + if (ch.Width <= 1) return false; + + var map = ch.Points; + + double gain = 0.0; + if (_threadCount == 0) + { + MorphAsync(map, ch.Width, ch.Height, _cycleLength, (uint)_random.Next(), ref gain); + } + else + { + List workers = []; + for (ulong i = 0; i < _threadCount; ++i) + { + var thread = new Thread(() => + MorphAsync(map, ch.Width, ch.Height, _cycleLength, (uint)_random.Next(), ref gain)); + thread.Name = $"MorphThread-{i}"; + thread.Start(); + workers.Add(thread); + } + + while (workers.Any()) + { + workers.Last().Join(); + workers.RemoveAt(workers.Count - 1); + } + } + _chainMapE -= gain; + + return false; + } +#endif + + private bool BlobifyFrame(ulong frameKey) + { + var f = _frames[frameKey]; + ulong sz = (ulong)f.Blobs.Count; + ulong pos, toPos, x, y, b; + + if (sz == 0) + { + // First step is to interpret all pixels as atomic blobs. + foreach (var it in f.Pixels) + { + pos = it.Key; + var newBlob = new Blob + { + X = it.Value.X, + Y = it.Value.Y, + R = (it.Value.Color.R / 255.0), + G = (it.Value.Color.G / 255.0), + B = (it.Value.Color.B / 255.0), + A = (it.Value.Color.A / 255.0), + Group = pos, + }; + newBlob.Surface.Add(pos); + x = pos % (ushort.MaxValue + 1); + y = pos / (ushort.MaxValue + 1); + + // Add reasonable border. + if (x < ushort.MaxValue && + HasPixel(frameKey, toPos = AtomorphUtilities.XY2Pos((ushort)(x + 1), (ushort)y))) + newBlob.Border.Add(toPos); + if (x > 0 && HasPixel(frameKey, (toPos = AtomorphUtilities.XY2Pos((ushort)(x - 1), (ushort)y)))) + newBlob.Border.Add(toPos); + if (y < ushort.MaxValue && + HasPixel(frameKey, (toPos = AtomorphUtilities.XY2Pos((ushort)x, (ushort)(y + 1))))) + newBlob.Border.Add(toPos); + if (y > 0 && HasPixel(frameKey, (toPos = AtomorphUtilities.XY2Pos((ushort)x, (ushort)(y - 1))))) + newBlob.Border.Add(toPos); + + f.Blobs.Add(newBlob); + f.Owners[pos] = newBlob; + } + + f.Blobs.RandomShuffle(_random); + sz = (ulong)f.Blobs.Count; + + for (ushort bb = 0; bb < sz; ++bb) + { + f.Blobs[bb]!.Index = bb; + } + + if (f.Blobs.Count == 0 || _blobMaxSize == 1) return true; + + return false; + } + + Again: // For popping all sequential nullptrs from the end of the vector. + sz = (ulong)f.Blobs.Count; + b = 0; + if (sz > 1) + { + // Always take the last blob from the initially shuffled vector + // because popping the last element is fast. + b = sz - 1; + } + else return true; + + var bl = (f.Blobs[(int)b]); + + if (bl is null || bl.Surface.Count == 0) + { + // This blob is empty, remove it. + f.Blobs.RemoveAt((int)b); + goto Again; + } + + if ((ulong)f.Blobs.Count <= _blobNumber) return true; + + List erasedBorder = new(); + HashSet checkedBlobs = new(); + bool bestFound = false; + double bestDist = 0.0; + Blob? bestMatch = null; + ulong bestEqual = 0; + + if ((ulong)bl.Surface.Count >= _blobMinSize) + { + // This blob has met its minimum size, prevent it from being unified later. + bl.Unified = true; + } + + bool checkThreshold = true; + bool ignoreColourThresholdCond = (ulong)bl.Surface.Count < _blobMaxSize; + IgnoreColourThreshold: + if (ignoreColourThresholdCond) + { + foreach (var it in bl.Border) + { + pos = it; + var ownerPos = f.Owners[pos]; + if (bl.Surface.Count(v => v == pos) != 0 || f.Owners.Count(v => v.Key == pos) == 0 || + checkedBlobs.Count(v => v == ownerPos) != 0 || !HasPixel(frameKey, pos)) + { + // Don't expand into itself and empty positions. + if (checkThreshold && (ulong)bl.Surface.Count >= _blobMinSize) + { + erasedBorder.Add(pos); + } + } + else + { + // Find out which blob currently owns this pixel. + var owner = f.Owners[pos]; + checkedBlobs.Add(owner); + if (owner != bl) + { + double dist; + var c1 = ColorUtilities.CreateColor(owner.R, owner.G, owner.B, owner.A); + var c2 = ColorUtilities.CreateColor(bl.R, bl.G, bl.B, bl.A); + dist = ColorUtilities.ColorDistance(c1, c2); + + if ((dist <= _blobThreshold || !checkThreshold) && (!bestFound || dist <= bestDist)) + { + if (bestFound && dist == bestDist) + { + var rand = _random.Next(0, (int)bestEqual); + bestEqual++; + if (rand != 0) continue; + } + else + { + bestEqual = 1; + } + bestFound = true; + bestMatch = owner; + bestDist = dist; + } + } + } + } + } + + MainHandling: + if (bestFound) + { + // Merge with this blob. + var surface1 = bl.Surface.Count; + var surface2 = bestMatch.Surface.Count; + var weight = (surface2) / (double)(surface1 + surface2); + + bl.X = ((1.0 - weight) * bl.X + weight * bestMatch.X); + bl.Y = ((1.0 - weight) * bl.Y + weight * bestMatch.Y); + bl.R = ((1.0 - weight) * bl.R + weight * bestMatch.R); + bl.G = ((1.0 - weight) * bl.G + weight * bestMatch.G); + bl.B = ((1.0 - weight) * bl.B + weight * bestMatch.B); + bl.A = ((1.0 - weight) * bl.A + weight * bestMatch.A); + + foreach (var it in bestMatch.Surface) + { + f.Owners[it] = bl; + bl.Surface.Add(it); + } + + foreach (var it in bestMatch.Border) + { + bl.Border.Add(it); + } + + bestMatch.Surface.Clear(); + bestMatch.Border.Clear(); + + var blobIndex = bestMatch.Index; + f.Blobs[(int)blobIndex] = bl; + bl.Index = blobIndex; + bl.Unified = (bl.Unified || bestMatch.Unified); + + f.Blobs.RemoveAt(f.Blobs.Count - 1); + } + else + { + var bb = f.FirstExpansion; + + if ((ulong)bl.Surface.Count < _blobMinSize && bl.Border.Count > 0 && checkThreshold) + { + // This outlier has neighbours but it is undersized. Discard colour threshold constraint. + checkThreshold = false; + checkedBlobs.Clear(); + ignoreColourThresholdCond = true; + goto IgnoreColourThreshold; + } + + bl.Border.Clear(); // Don't attempt to expand any more. + + if (bb < sz) + { + // Swap it with last random blob. + var other = f.Blobs[(int)bb]; + if (other is not null) other.Index = b; + + f.Blobs[(int)b] = other; + f.Blobs[(int)bb] = bl; + bl.Index = bb; + + f.FirstExpansion++; + } + else return true; // None of the remaining blobs can expand any more. + } + + // Remove erased borders. + var esz = (ulong)erasedBorder.Count; + for (ulong i = 0; i < esz; ++i) + { + bl.Border.Remove(erasedBorder[(int)i]); + } + return false; + } + + private bool UnifyFrame(ulong frame_key) + { + var f = _frames[frame_key]; + ulong fexp; // Only unify blobs that cannot expand any more. + ulong sz; + ulong bb; + Blob? bl = null, ubl = null; + Blob? best = null; + ulong score = 0; + ushort ubl_x = 0, ubl_y = 0; + ulong samples; + bool done = true; + ulong blobs_before = 0; + + // Remove all sequential nullptrs from the end of blobs. + while (f.Blobs.Any() && f.Blobs.Last() == null) + { + f.Blobs.RemoveAt(f.Blobs.Count - 1); + } + + blobs_before = (ulong)f.Blobs.Count; + if (_blobBoxSamples == 0 || blobs_before <= _blobNumber) return true; + + Again: + samples = 0; + + NotEnoughSamples: + sz = (ulong)f.Blobs.Count; + fexp = f.FirstExpansion; + + for (bb = f.FirstDust; bb < fexp; ++bb) + { + if ((bl = f.Blobs[(int)bb]) == null) continue; + + if (bl == ubl) + { + // Cycle has ended. + if (!Samples(f, out samples, ref best, ref done, ref ubl, ref bb, ref sz, ref fexp)) + return false; + else + continue; + } + + if (bl.Unified) + { + var fd = f.FirstDust; + if (bb != fd) + { + // Swap this already unified blob with current first dust + // and increase the first dust index by 1. + var fdb = f.Blobs[(int)fd]; + if (fdb is not null) fdb.Index = bb; + bl.Index = fd; + f.Blobs[(int)fd] = bl; + f.Blobs[(int)bb] = fdb; + } + f.FirstDust++; + goto Again; + } + + if (samples >= _blobBoxSamples) + { + if (!Samples(f, out samples, ref best, ref done, ref ubl, ref bb, ref sz, ref fexp)) + return false; + else + continue; + } + + if (ubl == null) + { + ubl = bl; + ubl_x = (ushort)Math.Round(ubl.X); + ubl_y = (ushort)Math.Round(ubl.Y); + continue; + } + + samples++; + + var bounds_x = (Math.Min(ubl_x, (ushort)Math.Round(bl.X)), Math.Max(ubl_x, (ushort)Math.Round(bl.X))); + var bounds_y = (Math.Min(ubl_y, (ushort)Math.Round(bl.Y)), Math.Max(ubl_y, (ushort)Math.Round(bl.Y))); + + if (bounds_x.Item1 + _blobBoxGrip >= bounds_x.Item2 && bounds_y.Item1 + _blobBoxGrip >= bounds_y.Item2) + { + ulong dx, dy, current_score; + dx = (ulong)(bounds_x.Item2 - bounds_x.Item1); + dy = (ulong)(bounds_y.Item2 - bounds_y.Item1); + current_score = dx * dx + dy * dy; + + if (best == null || current_score < score) + { + best = bl; + score = current_score; + continue; + } + } + } + if (samples > 0 && ubl is not null) + { + goto NotEnoughSamples; + } + + return done; + } + + private bool Samples(Frame f, out ulong samples, ref Blob? best, ref bool done, ref Blob? ubl, ref ulong bb, + ref ulong sz, ref ulong fexp) + { + samples = 0; + if (best == null) + { + // Nothing suitable for merging. + if (done) + { + ubl.Unified = true; + } + bb = ubl.Index; + ubl = null; + return true; + } + else + { + // Enough samples gathered, now merge with the best one. + var bi = best.Index; + + var surface_1 = ubl.Surface.Count; + var surface_2 = best.Surface.Count; + double weight = (surface_2) / (double)(surface_1 + surface_2); + + ubl.X = ((1.0 - weight) * ubl.X + weight * best.X); + ubl.Y = ((1.0 - weight) * ubl.Y + weight * best.Y); + ubl.R = ((1.0 - weight) * ubl.R + weight * best.R); + ubl.G = ((1.0 - weight) * ubl.G + weight * best.G); + ubl.B = ((1.0 - weight) * ubl.B + weight * best.B); + ubl.A = ((1.0 - weight) * ubl.A + weight * best.A); + + foreach (var it in best.Surface) + { + f.Owners[it] = ubl; + ubl.Surface.Add(it); + } + + best.Surface.Clear(); + best.Border.Clear(); + ubl.Border.Clear(); // Not needed because it's a pixel dust cloud anyway. + + f.Blobs[(int)bi] = null; + + best = null; + + if (sz == fexp) + { + // sz should always equal to fexp if everything + // has been properly blobified before unifying. + // This optimization is only then possible. + var last = f.Blobs.LastOrDefault(); + if (last is not null) + { + // Last element is not nullptr, swap it with blobs[bi] + // so that the latter can be safely popped later. + var last_index = last.Index; + f.Blobs[(int)bi] = last; + f.Blobs[(int)bi].Index = bi; + f.Blobs[(int)last_index] = null; + } + + while (f.Blobs.Any() && f.Blobs.Last() is null) + { + f.Blobs.RemoveAt(f.Blobs.Count - 1); + sz--; + fexp--; + f.FirstExpansion--; + } + } + done = false; + + if (sz <= _blobNumber) + { + ubl.Unified = true; + return false; + } + } + bb = ubl.Index; // Next, take a blob right after ubl. + ubl = null; + return true; + } + + private bool InitMorph() + { + ulong i = 0, j = 0; + + if (!_chains.Any() && _blobMap is not null) + { + _chainMapE = 0.0; + + // Refresh blob map according to groups. + // Needed in case deviant was left TRUE so + // that the blob map might be messed up. + ulong frameIndex = 0; + foreach (var it in _frames) + { + ulong blobCount = (ulong)it.Value.Blobs.Count; + for (i = 0; i < blobCount; ++i) + { + _blobMap[it.Value.Blobs[(int)i].Group][frameIndex] = it.Value.Blobs[(int)i]; + } + frameIndex++; + } + + // Make sure that volatile blobs have their positions averaged. + List toBeFixed = new(); + for (i = 0; i < _blobMapW; ++i) + { + for (j = 0; j < _blobMapH; ++j) + { + toBeFixed.Add(_blobMap[i][j]); + } + FixVolatiles(toBeFixed); + toBeFixed.Clear(); + } + + for (i = 0; i < _blobMapW; ++i) + { + ulong maxSize = 0; + // Find out the largest blob. + for (j = 0; j < _blobMapH; ++j) + { + if ((ulong)_blobMap[i][j].Surface.Count > maxSize) + { + maxSize = (ulong)_blobMap[i][j].Surface.Count; + } + } + ulong pointCount = maxSize * _pointDensity; + + // Then create a blob chain that includes all the blobs that share the same group. + for (j = 0; j < _blobMapH; ++j) + { + if (!_chains.TryGetValue(i, out var cha) || cha.Points == null) + { + cha ??= _chains[i] = new Chain(); + if (!AtomorphUtilities.RenewChain(cha, pointCount, _blobMapH)) + { + _chains.Remove(i); + return false; + } + } + + // Remember the maximum surface area this blob can take: + _chains[i].MaxSurface = maxSize; + + // Initialize the points in this chain at key frame j. + Pixel px = new Pixel(); + ulong p = 0, pos = 0; + List points = new(); + var bl = _blobMap[i][j]; + Point? pt = null; + ulong frameKey; + + frameKey = _frames.Keys.Skip((int)j).FirstOrDefault(); + + p = 0; + foreach (var it in bl.Surface) + { + pos = it; + px = GetPixel(frameKey, pos); + + ref var v = ref _chains[i].Points[p][j]; + v.X = px.X; + v.Y = px.Y; + v.Flags = PointFlags.HasPixel | PointFlags.HasFluid; + v.XFract = 0; + v.YFract = 0; + points.Add(v); + + ++p; + } + + if (!points.Any()) + { + Point volatilePoint = new() + { + X = (ushort)Math.Round(bl.X), + Y = (ushort)Math.Round(bl.Y), + Flags = + PointFlags.HasFluid, // This is still needed for the trajectories of fluid particles. + XFract = 0, + YFract = 0, + }; + + _chains[i].Points[p][j] = volatilePoint; + points.Add(volatilePoint); + ++p; + } + + points.RandomShuffle(_random); + ulong psz = (ulong)points.Count; + + for (; p < _chains[i].Width; ++p) + { + ref var v = ref _chains[i].Points[p][j]; + v.X = points[(int)(p % psz)].X; + v.Y = points[(int)(p % psz)].Y; + v.Flags = points[(int)(p % psz)].Flags; + v.Flags &= ~PointFlags.HasFluid; // Duplicates must not represent fluid particles. + v.XFract = (byte)_random.Next(0, byte.MaxValue); + v.YFract = (byte)_random.Next(0, byte.MaxValue); + } + +#if ATOMORPH_OPENCV + // TODO: Implement OpenCV +#endif + _chains[i].Energy = GetEnergy(_chains[i]); + _chainMapE += _chains[i].Energy; + } + } + if (!_chains.Any()) return false; + } + + // These extra checks are done here in advance to have the morph + // function as fast as possible, without wasting any time on the + // sanity checks. + if (_blobMapH == 0 || _blobMapW == 0) return false; + + ulong maxW = 0; + for (i = 0; i < _blobMapW; ++i) + { + var ch = _chains[i]; + if (ch.Height == 0) return false; + if (ch.Width > maxW) maxW = ch.Width; + } + + if (maxW <= 1) return false; + + return true; + } + + public double GetEnergy() + { + if (!_paused) return double.PositiveInfinity; + return State switch + { + MorphState.BlobMatching => _bestBlobMapE, + MorphState.AtomMorphing => _chainMapE, + _ => -1.0, + }; + } + + private double GetEnergy(Blob[][] map) + { + if (_blobMapH == 0 || _blobMapW == 0) return 0.0; + + double e = 0.0; + + for (ulong i = 0; i < _blobMapW; ++i) + { + var pframeBlob = map[i][_blobMapH - 1]; + + for (ulong j = 0; j < _blobMapH; ++j) + { + var cframeBlob = map[i][j]; + + e += BlobDistance(pframeBlob, cframeBlob); + + pframeBlob = cframeBlob; + } + } + + return e; + } + + private double GetEnergy(Chain ch) + { + var w = ch.Width; + var h = ch.Height; + + if (w <= 1 || h == 0) return 0.0; + + var map = ch.Points; + double e = 0.0; + for (ulong i = 0; i < w; ++i) + { + for (ulong j = 0; j < h; ++j) + { + var next = (j + 1) % h; + e += AtomorphUtilities.PointDistance(map[i][j], map[i][next]); + } + } + + return e; + } + + private void FixVolatiles(List toBeFixed) + { + ulong sz = (ulong)toBeFixed.Count; + + if (sz <= 1) return; + + ulong i = 0; + bool started = false; + List volatiles = []; + + Blob? first_static = null; + Blob? previous_static = null; + + while (true) + { + i = (i + 1) % sz; + Blob bl = toBeFixed[(int)i]; + bool empty = !bl.Surface.Any(); + + if (!started) + { + if (empty) + { + if (i == 0) break; // All are empty. + continue; + } + started = true; + first_static = bl; + previous_static = bl; + continue; + } + + if (empty) + { + volatiles.Add(bl); + continue; + } + + if (volatiles.Any()) + { + // Fix the range between previous_static and bl. + ulong vsz = (ulong)volatiles.Count; + for (ulong v = 0; v < vsz; ++v) + { + double t = (v + 1.0) / (double)(vsz + 1.0); + volatiles[(int)v].X = t * bl.X + (1.0 - t) * previous_static.X; + volatiles[(int)v].Y = t * bl.Y + (1.0 - t) * previous_static.Y; + } + volatiles.Clear(); + } + previous_static = bl; + if (previous_static == first_static) break; // Cycle has ended. + } + } + + private bool HasFrame(ulong f) => _frames.ContainsKey(f); + private bool HasPixel(ulong f, ulong pos) => HasFrame(f) && _frames[f].Pixels.ContainsKey(pos); + private bool HasBlob(ulong f, ulong b) => HasFrame(f) && _frames[f].Blobs.Count > (int)b; + + private bool CanExpand(ulong frame, ulong fromPos, ulong toPos) + { + if (!HasPixel(frame, toPos)) return false; + + var p1 = GetPixel(frame, fromPos); + var p2 = GetPixel(frame, toPos); + + return ColorUtilities.ColorDistance(p1.Color, p2.Color) <= _blobThreshold; + } + + private void Run() + { + var start = DateTime.UtcNow; + + while (!_signalStop) + { + if (!_signalPause && !_paused) + { + Step(); + if (_iterations > 0 && --_iterations == 0) + { + // When the defined number of steps have been made, automatically pause the thread. + _signalPause = true; + } + + if (_seconds > 0.0) + { + // When worked more than the defined number of seconds, automatically pause the thread. + var end = DateTime.UtcNow; + if ((end - start).TotalSeconds > _seconds) + { + _signalPause = true; + _seconds = 0.0; + } + } + } + else + { + _paused = true; + _signalPause = false; + Thread.Sleep(0); + start = DateTime.UtcNow; + } + } + _running = false; + _signalStop = false; + _signalPause = false; + _paused = true; + } + + private void Step() + { + // ReSharper disable once SwitchStatementHandlesSomeKnownEnumValuesWithDefault + switch (State) + { + case MorphState.BlobDetection: + if (Blobify()) + { + State = MorphState.BlobUnification; + _counter = 0; + } + break; + case MorphState.BlobUnification: + if (Unify()) + { + State = MorphState.BlobMatching; + _counter = 0; + } + break; + case MorphState.BlobMatching: + if (_skipState || Match()) + { + State = !InitMorph() ? MorphState.Done : MorphState.AtomMorphing; + _counter = 0; + } + break; + case MorphState.AtomMorphing: + if (_skipState || Morph()) + { + State = MorphState.Done; + _counter = 0; + } + break; + default: + break; + } + _skipState = false; + _counter++; + } + + /// + public void Dispose() + { + Pause(); + Stop(); + Clear(); + } +} \ No newline at end of file diff --git a/Atomorph.NET/AtomorphUtilities.cs b/Atomorph.NET/AtomorphUtilities.cs new file mode 100644 index 0000000..29219ac --- /dev/null +++ b/Atomorph.NET/AtomorphUtilities.cs @@ -0,0 +1,82 @@ +using System; +using System.Runtime.CompilerServices; +using Atomorph.GLNemo; +using Atomorph.Models; + +namespace Atomorph; + +public static class AtomorphUtilities +{ + public static ulong XY2Pos(ushort x, ushort y) => (ulong)(y * (ushort.MaxValue + 1) + x); + + public static void Point2XY(Point pt, out float x, out float y) + { + x = pt.X + pt.XFract/(float)(byte.MaxValue+1); + y = pt.Y + pt.YFract/(float)(byte.MaxValue+1); + } + + public static ulong PointDistance(Point p1, Point p2) + { + var xd = (ulong)Math.Abs(((byte.MaxValue+1)*p1.X+p1.XFract) - ((byte.MaxValue+1)*p2.X+p2.XFract)); + var yd = (ulong)Math.Abs(((byte.MaxValue+1)*p1.Y+p1.YFract) - ((byte.MaxValue+1)*p2.Y+p2.YFract)); + + return (xd*xd + yd*yd); + } + + public static ulong PixelDistance(Pixel p1, Pixel p2) + { + var xd = p1.X-p2.X; + var yd = p1.Y-p2.Y; + + return (ulong)(xd*xd+yd*yd); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool PointHasPixel(this Point p) => p.Flags.HasFlag(PointFlags.HasPixel); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool PointHasFluid(this Point p) => p.Flags.HasFlag(PointFlags.HasFluid); + + + public static bool ClearChain(Chain c) + { + c.Points = null; + c.Places = null; + c.Splines = null; +#if ATOMORPH_OPENCV + // TODO: clear kdtrees + features +#endif + c.Width = 0; + c.Height = 0; + c.Energy = 0.0; + c.MaxSurface = 0; + return true; + } + + public static bool RenewChain(Chain c, ulong width, ulong height) + { + ClearChain(c); + c.Points = new Point[width][]; + for (ulong k = 0; k < width; ++k) + { + c.Points[k] = new Point[height]; + } + + c.Places = new ulong[width][]; + for (ulong k = 0; k < width; ++k) + { + c.Places[k] = new ulong[height]; + } + + c.Splines = new Spline[width]; + +#if ATOMORPH_OPENCV + // TODO: Renew opencv +#endif + + c.Width = width; + c.Height = height; + + return true; + } +} \ No newline at end of file diff --git a/Atomorph.NET/ColorMethod.cs b/Atomorph.NET/ColorMethod.cs new file mode 100644 index 0000000..699f37a --- /dev/null +++ b/Atomorph.NET/ColorMethod.cs @@ -0,0 +1,7 @@ +namespace Atomorph; + +public enum ColorMethod +{ + RGB, + HSP, +} \ No newline at end of file diff --git a/Atomorph.NET/FluidModel/FluidModel.cs b/Atomorph.NET/FluidModel/FluidModel.cs new file mode 100644 index 0000000..2b50ccf --- /dev/null +++ b/Atomorph.NET/FluidModel/FluidModel.cs @@ -0,0 +1,522 @@ +using System; +using System.Collections.Generic; +using Pcg; + +namespace Atomorph.FluidModel; + +internal class FluidModel : IDisposable +{ + private Particle[]? _particles; + private uint _gSizeX; + private uint _gSizeY; + private uint _particleCount; + private Node[] _active; + private uint _activeCount; + private Material _water; + + private bool _pressed; + private bool _pressedPrev; + + private double _mx; + private double _my; + private double _mxPrev; + private double _myPrev; + + private Node[][] _grid; + private Line[] _lines; + + public IReadOnlyList Lines => _lines; + public Material Material => _water; + public IReadOnlyList Particles => _particles; + private PcgRandom _random = new PcgRandom(); + + public uint ParticleCount => _particleCount; + + public FluidModel(uint gSizeX, uint gSizeY, uint particleCount) + { + _gSizeX = gSizeX; + _gSizeY = gSizeY; + _particleCount = particleCount; + + _water = new Material(1.0, 1.0, 1.0, 1.0, 1.0, 1.0); + + _grid = new Node[gSizeX][]; + for (uint i = 0; i < gSizeX; i++) + _grid[i] = new Node[gSizeY]; + for (uint j = 0; j < gSizeY; j++) + { + for (uint i = 0; i < gSizeX; i++) + { + _grid[i][j] = new Node() { Pos = (int)(j * gSizeX + i), }; + } + } + _active = new Node[gSizeX * gSizeY]; + _particles = new Particle[particleCount]; + for (uint i = 0; i < particleCount; i++) + { + _particles[i] = new Particle(_water, gSizeX / 2.0, gSizeY / 2.0, 0.0, 0.0); + } + _lines = new Line[particleCount]; + } + + public void SetPressed(bool b) => _pressed = b; + + public void SetMovePos(double x, double y) + { + _mx = x; + _my = y; + } + + + public void Step(ulong stepsLeft, double freedomRadius, double t) + { + if (_particles is null) + throw new InvalidOperationException("Particles not initialized."); + + var drag = false; + var mdx = 0.0; + var mdy = 0.0; + if (_pressed && _pressedPrev) + { + drag = true; + mdx = _mx - _mxPrev; + mdy = _my - _myPrev; + } + _pressedPrev = _pressed; + _mxPrev = _mx; + _myPrev = _my; + foreach (var node in _active) + node.Clear(); + _activeCount = 0; + + double phi; + double x, y; + double fx = 0.0, fy = 0.0; + + Particle p; + Node n; + + for (uint index = 0; index < _particleCount; ++index) + { + p = _particles[index]; + if (!p.Active) + continue; + p.Cx = (uint)(p.X - 0.5); + p.Cy = (uint)(p.Y - 0.5); + + x = p.Cx - p.X; + + p.Px[0] = (0.5 * x * x + 1.5 * x + 1.125); + p.Gx[0] = (x + 1.5); + x += 1.0; + p.Px[1] = (-x * x + 0.75); + p.Gx[1] = (-2.0 * x); + x += 1.0; + p.Px[2] = (0.5 * x * x - 1.5 * x + 1.125); + p.Gx[2] = (x - 1.5); + + y = p.Cy - p.Y; + + p.Py[0] = (0.5 * y * y + 1.5 * y + 1.125); + p.Gy[0] = (y + 1.5); + y += 1.0; + p.Py[1] = (-y * y + 0.75); + p.Gy[1] = (-2.0 * y); + y += 1.0; + p.Py[2] = (0.5 * y * y - 1.5 * y + 1.125); + p.Gy[2] = (y - 1.5); + + for (uint i = 0; i < 3; ++i) + { + for (uint j = 0; j < 3; ++j) + { + n = _grid[p.Cx + i][p.Cy + j]; + if (!n.Active) + { + _active[_activeCount++] = n; + n.Active = true; + } + + phi = p.Px[i] * p.Py[j]; + n.M += phi * p.Material.M; + n.D += phi; + n.Gx += p.Gx[i] * p.Py[j]; + n.Gy += p.Px[i] * p.Gy[j]; + + // CUSTOM: + if (p.Mature && p.Strength > 0.0) + { + double new_w = p.Strength; + double old_w = n.Weight; + double sum_w = new_w + old_w; + n.R = (old_w * n.R + new_w * p.r) / sum_w; + n.G = (old_w * n.G + new_w * p.g) / sum_w; + n.B = (old_w * n.B + new_w * p.b) / sum_w; + n.A = (old_w * n.A + new_w * p.a) / sum_w; + n.Weight = sum_w; + } + // END OF CUSTOM + } + } + } + + uint cx, cy; + uint cxi, cyi; + + double pdx, pdy; + double C20, C02, C30, C03; + double C21, C31, C12, C13, C11; + + double csum1, csum2; + + double u, u2, u3; + double v, v2, v3; + + double vx, vy; + + double density; + double pressure; + double weight; + + Node n01, n02, n11, n12; + + for (uint i = 0; i < _particleCount; ++i) + { + p = _particles[i]; + if (p.Active == false) continue; // CUSTOMIZATION + + cx = (uint)p.X; + cy = (uint)p.Y; + cxi = cx + 1; + cyi = cy + 1; + + n01 = _grid[cx][cy]; + n02 = _grid[cx][cyi]; + n11 = _grid[cxi][cy]; + n12 = _grid[cxi][cyi]; + + pdx = n11.D - n01.D; + pdy = n02.D - n01.D; + C20 = 3.0 * pdx - n11.Gx - 2.0 * n01.Gx; + C02 = 3.0 * pdy - n02.Gy - 2.0 * n01.Gy; + C30 = -2.0 * pdx + n11.Gx + n01.Gx; + C03 = -2.0 * pdy + n02.Gy + n01.Gy; + + csum1 = n01.D + n01.Gy + C02 + C03; + csum2 = n01.D + n01.Gx + C20 + C30; + + C21 = 3.0 * n12.D - 2.0 * n02.Gx - n12.Gx - 3.0 * csum1 - C20; + C31 = -2.0 * n12.D + n02.Gx + n12.Gx + 2.0 * csum1 - C30; + C12 = 3.0 * n12.D - 2.0 * n11.Gy - n12.Gy - 3.0 * csum2 - C02; + C13 = -2.0 * n12.D + n11.Gy + n12.Gy + 2.0 * csum2 - C03; + C11 = n02.Gx - C13 - C12 - n01.Gx; + + u = p.X - cx; + u2 = u * u; + u3 = u * u2; + v = p.Y - cy; + v2 = v * v; + v3 = v * v2; + + density = n01.D + n01.Gx * u + n01.Gy * v + C20 * u2 + C02 * v2 + C30 * u3 + C03 * v3 + C21 * u2 * v + + C31 * u3 * v + C12 * u * v2 + C13 * u * v3 + C11 * u * v; + + pressure = density - 1.0; + if (pressure > 2.0) + { + pressure = 2.0; + } + + fx = fy = 0.0; + + if (p.X < 4.0) + { + fx += p.Material.M * (4.0 - p.X); + } + else if (p.X > _gSizeX - 5) + { + fx += p.Material.M * (_gSizeX - 5 - p.X); + } + + if (p.Y < 4.0) + { + fy += p.Material.M * (4.0 - p.Y); + } + else if (p.Y > _gSizeY - 5) + { + fy += p.Material.M * (_gSizeY - 5 - p.Y); + } + + if (drag) + { + vx = Math.Abs(p.X - _mx); + vy = Math.Abs(p.Y - _my); + + if (vx < 10.0 && vy < 10.0) + { + weight = p.Material.M * (1.0 - vx * 0.1) * (1.0 - vy * 0.1); + fx += weight * (mdx - p.U); + fy += weight * (mdy - p.V); + } + } + + for (uint index = 0; index < 3; ++index) + { + for (uint j = 0; j < 3; ++j) + { + n = _grid[p.Cx + index][p.Cy + j]; + phi = p.Px[index] * p.Py[j]; + n.Ax += -((p.Gx[index] * p.Py[j]) * pressure) + fx * phi; + n.Ay += -((p.Px[index] * p.Gy[j]) * pressure) + fy * phi; + } + } + } + + for (uint i = 0; i < _activeCount; ++i) + { + n = _active[i]; + if (n.M > 0.0) + { + n.Ax /= n.M; + n.Ay /= n.M; + + //ORIGINALLY GRAVITY WAS INDICATED BY THESE: + //n->ay += 0.03; + //n->ax += 0.03; + } + } + + double mu, mv; + + for (uint pi = 0; pi < _particleCount; ++pi) + { + p = _particles[pi]; + if (p.Active == false) continue; // CUSTOMIZATION + + for (uint i = 0; i < 3; ++i) + { + for (uint j = 0; j < 3; ++j) + { + n = _grid[p.Cx + i][p.Cy + j]; + phi = p.Px[i] * p.Py[j]; + + /* CUSTOM STUFF */ + double custom_ax = 0.0; + double custom_ay = 0.0; + { + double x1 = p.X; + double y1 = p.Y; + double x2 = p.GravityX; + double y2 = p.GravityY; + double a = 0.03; + + // Gravitate towards (x2, y2). + double A = Math.Abs(y1 - y2); + double B = Math.Abs(x1 - x2); + double C = Math.Sqrt(A * A + B * B); + + if (a >= C) a = C; + + if (B <= 0.0) + { + if (y2 <= y1) custom_ay -= a; + else custom_ay += a; + } + else if (C > 0.0) + { + double dx = (a * B) / C; + double dy = (A * dx) / B; + + if (x1 <= x2) custom_ax += dx; + else custom_ax -= dx; + + if (y1 <= y2) custom_ay += dy; + else custom_ay -= dy; + } + } + /* END OF CUSTOM STUFF */ + + p.U += phi * (n.Ax + custom_ax); + p.V += phi * (n.Ay + custom_ay); + } + } + mu = p.Material.M * p.U; + mv = p.Material.M * p.V; + if (p.Mature == false) + { + mu *= 0.0; + mv *= 0.0; + } + for (uint i = 0; i < 3; ++i) + { + for (uint j = 0; j < 3; ++j) + { + n = _grid[p.Cx + i][p.Cy + j]; + phi = p.Px[i] * p.Py[j]; + n.U += phi * mu; + n.V += phi * mv; + } + } + } + + for (uint i = 0; i < _activeCount; ++i) + { + n = _active[i]; + if (n.M > 0.0) + { + n.U /= n.M; + n.V /= n.M; + } + } + + double gu, gv; + + for (uint i = 0; i < _particleCount; ++i) + { + p = _particles[i]; + + // CUSTOMIZATION: + if (p.Active == false) continue; + double nR = 0.0, nG = 0.0, nB = 0.0, nA = 0.0; + double weight2 = 0.0; + // END OF CUSTOMIZATION + + gu = 0.0; + gv = 0.0; + for (uint ii = 0; ii < 3; ++ii) + { + for (uint j = 0; j < 3; ++j) + { + n = _grid[p.Cx + ii][p.Cy + j]; + phi = p.Px[ii] * p.Py[j]; + gu += phi * n.U; + gv += phi * n.V; + + if (n.Weight > 0.0) + { + weight2 += n.Weight; + nR += n.R * n.Weight; + nG += n.G * n.Weight; + nB += n.B * n.Weight; + nA += n.A * n.Weight; + } + } + } + + // CUSTOMIZATION: + if (weight2 > 0.0) + { + double wr = 1.0; + double wg = 1.0; + double wb = 1.0; + double wa = 1.0; + nR /= weight2; + wr = Math.Abs(nR - p.R); + nG /= weight2; + wg = Math.Abs(nG - p.G); + nB /= weight2; + wb = Math.Abs(nB - p.B); + nA /= weight2; + wa = Math.Abs(nA - p.A); + + if (p.Mature == false) + { + p.r = nR; + p.g = nG; + p.b = nB; + p.a = nA; + } + else + { + p.r = (1.0 - wr) * p.r + wr * nR; + p.g = (1.0 - wg) * p.g + wg * nG; + p.b = (1.0 - wb) * p.b + wb * nB; + p.a = (1.0 - wa) * p.a + wa * nA; + } + } + // END OF CUSTOMIZATION + + p.X += gu; + p.Y += gv; + + /* CUSTOM STUFF */ + { + double x1 = p.X; + double y1 = p.Y; + double x2 = p.GravityX; + double y2 = p.GravityY; + + // Gravitate towards (x2, y2) if the distance + // is greater than freedom radius. + double A = Math.Abs(y1 - y2); + double B = Math.Abs(x1 - x2); + double C = Math.Sqrt(A * A + B * B); + + double r = freedomRadius * p.FreedomR; + if (C > r) + { + double mx = 0.0; + double my = 0.0; + + double a = C - r; + if (a >= C) a = C; + + if (B <= 0.0) + { + if (y2 <= y1) my -= a; + else my += a; + } + else if (C > 0.0) + { + double dx = (a * B) / C; + double dy = (A * dx) / B; + + if (x1 <= x2) mx += dx; + else mx -= dx; + + if (y1 <= y2) my += dy; + else my -= dy; + } + + double w = 1.0 / (stepsLeft + 1); + + mx *= w; + my *= w; + + p.X += mx; + p.Y += my; + } + } + /* END OF CUSTOM STUFF */ + + p.U += gu - p.U; + p.V += gv - p.B; + if (p.X < 1.0) + { + p.X = 1.0 + _random.NextDouble() * 0.01; + p.U = 0.0; + } + else if (p.X > _gSizeX - 2) + { + p.X = _gSizeX - 2 - _random.NextDouble() * 0.01; + p.U = 0.0; + } + if (p.Y < 1.0) + { + p.Y = 1.0 + _random.NextDouble() * 0.01; + p.V = 0.0; + } + else if (p.Y > _gSizeY - 2) + { + p.Y = _gSizeY - 2 - _random.NextDouble() * 0.01; + p.V = 0.0; + } + } + } + + /// + public void Dispose() + { + + } +} \ No newline at end of file diff --git a/Atomorph.NET/FluidModel/Line.cs b/Atomorph.NET/FluidModel/Line.cs new file mode 100644 index 0000000..05e90c2 --- /dev/null +++ b/Atomorph.NET/FluidModel/Line.cs @@ -0,0 +1,9 @@ +namespace Atomorph.FluidModel; + +internal record struct Line +{ + public double X1 { get; init; } + public double Y1 { get; init; } + public double X2 { get; init; } + public double Y2 { get; init; } +} \ No newline at end of file diff --git a/Atomorph.NET/FluidModel/Material.cs b/Atomorph.NET/FluidModel/Material.cs new file mode 100644 index 0000000..b8b77ec --- /dev/null +++ b/Atomorph.NET/FluidModel/Material.cs @@ -0,0 +1,15 @@ +namespace Atomorph.FluidModel; + +internal record struct Material(double M, double Rd, double K, double V, double D, double G) +{ + /// + /// Mass + /// + public double M { get; } = M; + + public double Rd { get; } = Rd; + public double K { get; } = K; + public double V { get; } = V; + public double D { get; } = D; + public double G { get; } = G; +} \ No newline at end of file diff --git a/Atomorph.NET/FluidModel/Node.cs b/Atomorph.NET/FluidModel/Node.cs new file mode 100644 index 0000000..69652d8 --- /dev/null +++ b/Atomorph.NET/FluidModel/Node.cs @@ -0,0 +1,31 @@ +using Atomorph.Models; + +namespace Atomorph.FluidModel; + +internal class Node +{ + public Node(){} + + public void Clear() + { + M = D = Gx = Gy = U = V = Ax = Ay = R = G = B = A = 0.0; + Weight = 0.0; + Active = false; + } + + public double M { get; set; } + public double D { get; set; } + public double Gx { get; set; } + public double Gy { get; set; } + public double U { get; set; } + public double V { get; set; } + public double Ax { get; set; } + public double Ay { get; set; } + public bool Active { get; set; } + public int Pos { get; set; } + public double R { get; set; } + public double G { get; set; } + public double B { get; set; } + public double A { get; set; } + public double Weight { get; set; } +} \ No newline at end of file diff --git a/Atomorph.NET/FluidModel/Particle.cs b/Atomorph.NET/FluidModel/Particle.cs new file mode 100644 index 0000000..369519e --- /dev/null +++ b/Atomorph.NET/FluidModel/Particle.cs @@ -0,0 +1,92 @@ +using Atomorph.Models; + +namespace Atomorph.FluidModel; + +internal class Particle +{ + public Particle() + { + } + + public Particle(Material mat, double x, double y, double u, double v) + { + Material = mat; + X = x; + Y = y; + U = u; + V = v; + + DuDx = 0.0; + DuDy = 0.0; + DvDx = 0.0; + DvDy = 0.0; + + Cx = 0; + Cy = 0; + } + + public void Clear() + { + U = V = DuDx = DuDy = DvDx = DvDy = 0.0; + Cx = Cy = 0; + Strength = 1.0; + for (int i = 0; i < 3; i++) + { + Px[i] = Py[i] = Gx[i] = Gy[i] = 0.0; + } + SourceOwner = false; + } + + public void CopyFrom(Particle other) + { + X = other.X; + Y = other.Y; + GravityX = other.GravityX; + GravityY = other.GravityY; + FreedomR = other.FreedomR; + } + + public Material Material { get; } + public double X { get; set; } + public double Y { get; set; } + public double U { get; set; } + public double V { get; set; } + + public double DuDx { get; private set; } + public double DuDy { get; private set; } + public double DvDx { get; private set; } + public double DvDy { get; private set; } + public uint Cx { get; set; } + public uint Cy { get; set; } + + public double[] Px { get; } = new double[3]; + public double[] Py { get; } = new double[3]; + public double[] Gx { get; } = new double[3]; + public double[] Gy { get; } = new double[3]; + + // CUSTOM VARIABLES: + public double GravityX { get; set; } + public double GravityY { get; set; } + public double FreedomR { get; set; } // freedom radius multiplier + public bool Active { get; set; } + public bool Mature { get; set; } + // ideal color (does not blend) + public double R { get; set; } // red component + public double G { get; set; } // green component + public double B { get; set; } // blue component + public double A { get; set; } // alpha component + + // current color (blends over time) + public double r { get; set; } // red component + public double g { get; set; } // green component + public double b { get; set; } // blue component + public double a { get; set; } // alpha component + public ulong DestinationPos { get; set; } + public ulong SourcePos { get; set; } + public ulong FrameKey { get; set; } + public double Strength { get; set; } // how easily it regains its color + public bool Hack { get; set; } + + public bool SourceOwner { get; set; } // true when it was first one to occupy the source location. + // END OF CUSTOM VARIABLES +} \ No newline at end of file diff --git a/Atomorph.NET/GLNemo/Spline.cs b/Atomorph.NET/GLNemo/Spline.cs new file mode 100644 index 0000000..8d6b380 --- /dev/null +++ b/Atomorph.NET/GLNemo/Spline.cs @@ -0,0 +1,69 @@ +using System.Collections.Generic; + +namespace Atomorph.GLNemo; + +public class Spline +{ + private List _vp = []; + private double _deltaT; + + public Spline() + { + } + + public Spline(Spline spline) + { + _vp = new List(spline._vp); + _deltaT = spline._deltaT; + } + + /// + /// Static method for computing the Catmull-Rom parametric equation + /// given a time (t) and a vector quadruple (p1,p2,p3,p4). + /// + public static Vec3D Eq(double t, Vec3D p1, Vec3D p2, Vec3D p3, Vec3D p4) + { + var t2 = t * t; + var t3 = t2 * t; + var b1 = 0.5 * (-t3 + 2.0 * t2 - t); + var b2 = 0.5 * (3.0 * t3 - 5.0 * t2 + 2.0); + var b3 = 0.5 * (-3.0 * t3 + 4.0 * t2 + t); + var b4 = 0.5 * (t3 - t2); + return new Vec3D(p1 * b1 + p2 * b2 + p3 * b3 + p4 * b4); + } + + public void AddSplinePoint(Vec3D point) + { + _vp.Add(point); + _deltaT = 1.0 / _vp.Count; + } + + public Vec3D GetInterpolatedSplinePoint(double t) + { + // Find out in which interval we are on the spline + var p = (int)(t / _deltaT); + // Compute local control point indices + var p0 = p - 1; + p0 = p0 < 0 ? _vp.Count - 1 : p0 >= _vp.Count ? p0 - _vp.Count : p0; + var p1 = p; + p1 = p1 < 0 ? _vp.Count - 1 : p1 >= _vp.Count ? p1 - _vp.Count : p1; + var p2 = p + 1; + p2 = p2 < 0 ? _vp.Count - 1 : p2 >= _vp.Count ? p2 - _vp.Count : p2; + var p3 = p + 2; + p3 = p3 < 0 ? _vp.Count - 1 : p3 >= _vp.Count ? p3 - _vp.Count : p3; + // Relative (local) time + var lt = (t - _deltaT * p) / _deltaT; + // Interpolate + return Eq(lt, _vp[p0], _vp[p1], _vp[p2], _vp[p3]); + } + + public int GetNumPoints() => _vp.Count; + + public Vec3D GetNthPoint(int n) => _vp[n]; + + public void ClearCPoints() + { + _vp.Clear(); + _deltaT = 0.0; + } +} \ No newline at end of file diff --git a/Atomorph.NET/GLNemo/Vec3D.cs b/Atomorph.NET/GLNemo/Vec3D.cs new file mode 100644 index 0000000..325f461 --- /dev/null +++ b/Atomorph.NET/GLNemo/Vec3D.cs @@ -0,0 +1,101 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Atomorph.GLNemo; + +public record struct Vec3D +{ + public Vec3D(double x, double y, double z) + { + X = x; + Y = y; + Z = z; + } + + public Vec3D(Vec3D other) + { + X = other.X; + Y = other.Y; + Z = other.Z; + } + + public double X { get; private set; } + public double Y { get; private set; } + public double Z { get; private set; } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Set(double x, double y, double z) + { + X = x; + Y = y; + Z = z; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vec3D operator +(Vec3D a, Vec3D b) => new(a.X + b.X, a.Y + b.Y, a.Z + b.Z); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vec3D operator -(Vec3D a, Vec3D b) => new(a.X - b.X, a.Y - b.Y, a.Z - b.Z); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vec3D operator -(Vec3D a) => new(-a.X, -a.Y, -a.Z); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vec3D operator /(Vec3D a, Vec3D b) => new(a.X / b.X, a.Y / b.Y, a.Z / b.Z); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vec3D operator /(Vec3D a, double b) => new(a.X / b, a.Y / b, a.Z / b); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vec3D operator *(Vec3D a, Vec3D b) => new(a.X * b.X, a.Y * b.Y, a.Z * b.Z); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vec3D operator *(Vec3D a, double b) => new(a.X * b, a.Y * b, a.Z * b); + + public double this[int index] + { + get + { + return index switch + { + 0 => (float)X, + 1 => (float)Y, + 2 => (float)Z, + _ => throw new IndexOutOfRangeException("Index must be 0, 1, or 2.") + }; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public double Dot(Vec3D other) => X * other.X + Y * other.Y + Z * other.Z; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vec3D CrossProduct(Vec3D other) => + new(Y * other.Z - Z * other.Y, Z * other.X - X * other.Z, X * other.Y - Y * other.X); + + public Vec3D RotByMatrix(double[] matrix) + { + if (matrix.Length != 16) + throw new ArgumentException("Matrix must be a 4x4 matrix represented as a 1D array of length 16."); + return new Vec3D(X * matrix[0] + Y * matrix[4] + Z * matrix[8], X * matrix[1] + Y * matrix[5] + Z * matrix[9], + X * matrix[2] + Y * matrix[6] + Z * matrix[10]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public double Magnitude() => Math.Sqrt(X * X + Y * Y + Z * Z); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public double Distance(Vec3D other) => (this - other).Magnitude(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Normalize() + { + var fMag = X * X + Y * Y + Z * Z; + if (fMag < 1e-10) + return; + fMag = 1.0 / Math.Sqrt(fMag); + X *= fMag; + Y *= fMag; + Z *= fMag; + } +} \ No newline at end of file diff --git a/Atomorph.NET/InterpolationMethod.cs b/Atomorph.NET/InterpolationMethod.cs new file mode 100644 index 0000000..63a464a --- /dev/null +++ b/Atomorph.NET/InterpolationMethod.cs @@ -0,0 +1,10 @@ +namespace Atomorph; + +public enum InterpolationMethod +{ + None = 2, + Linear = 3, + Spline = 4, + Cosine = 5, + Perlin = 6, +} \ No newline at end of file diff --git a/Atomorph.NET/Models/Blob.cs b/Atomorph.NET/Models/Blob.cs new file mode 100644 index 0000000..a4d96ed --- /dev/null +++ b/Atomorph.NET/Models/Blob.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; + +namespace Atomorph.Models; + +public class Blob +{ + /// + /// Position in the nest vector + /// + public ulong Index { get; set; } + + /// + /// Pixel positions for surface. + /// + public HashSet Surface { get; init; } = new(); + + /// + /// Pixel positions around surface. + /// + public HashSet Border { get; init; } = new(); + + public ulong Group { get; set; } + public bool Unified { get; set; } + + public double X { get; set; } + public double Y { get; set; } + + public double R { get; set; } + public double G { get; set; } + public double B { get; set; } + public double A { get; set; } +} \ No newline at end of file diff --git a/Atomorph.NET/Models/Chain.cs b/Atomorph.NET/Models/Chain.cs new file mode 100644 index 0000000..8a4a10b --- /dev/null +++ b/Atomorph.NET/Models/Chain.cs @@ -0,0 +1,28 @@ +using System; +using System.Drawing; +using Atomorph.GLNemo; + +namespace Atomorph.Models; + +public class Chain +{ + public ulong Width { get; set; } + public ulong Height { get; set; } + public Point[][]? Points { get; set; } + public ulong[][]? Places { get; set; } + public double Energy { get; set; } + public ulong MaxSurface { get; set; } + public Spline?[] Splines { get; set; } = []; + + public Spline GetSpline(ulong index) + { + if (index >= (ulong)Splines.Length) + throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range of the splines array."); + var s = Splines[index]; + return s ?? (Splines[index] = new Spline()); + } + +#if ATOMORPH_OPENCV + // TODO: kdtrees + features +#endif +} \ No newline at end of file diff --git a/Atomorph.NET/Models/Color.cs b/Atomorph.NET/Models/Color.cs new file mode 100644 index 0000000..c02b594 --- /dev/null +++ b/Atomorph.NET/Models/Color.cs @@ -0,0 +1,221 @@ +using System; + +namespace Atomorph.Models; + +public readonly record struct Color +{ + public Color() + { + } + + public Color(byte r, byte g, byte b, byte a) + { + R = r; + G = g; + B = b; + A = a; + } + + public byte R { get; } + public byte G { get; } + public byte B { get; } + public byte A { get; } +} + +public static class ColorUtilities +{ + public static double ColorDistance(Color c1, Color c2) + { + var rd = c1.R - c2.R; + var gd = c1.G - c2.G; + var bd = c1.B - c2.B; + var ad = c1.A - c2.A; + + return Math.Sqrt(rd * rd + gd * gd + bd * bd + ad * ad) / 510.0; + } + + public static Color CreateColor(double r, double g, double b, double a) + { + return new Color((byte)Math.Round(r * 255.0), (byte)Math.Round(g * 255.0), (byte)Math.Round(b * 255.0), + (byte)Math.Round(a * 255.0)); + } + + public static Color RgbToHsp(Color color) + { + RGBToHSP(color.R / 255.0, color.G / 255.0, color.B / 255.0, out var h, out var s, out var p); + return CreateColor(h, s, p, color.A / 255.0); + } + + public static Color HspToRgb(Color color) + { + HSPtoRGB(color.R / 255.0, color.G / 255.0, color.B / 255.0, out var r, out var g, out var b); + return new Color((byte)Math.Min(Math.Round(r * 255.0), 255), + (byte)Math.Min(Math.Round(g * 255.0), 255), + (byte)Math.Min(Math.Round(b * 255.0), 255), + color.A); + } + + private const double Pr = 0.299; + private const double Pg = 0.587; + private const double Pb = 0.114; + + private static void RGBToHSP(double R, double G, double B, out double H, out double S, out double P) + { + // Calculate the Perceived brightness. + P = Math.Sqrt(R * R * Pr + G * G * Pg + B * B * Pb); + + // Calculate the Hue and Saturation. (This part works + // the same way as in the HSV/B and HSL systems???.) + if (R == G && R == B) + { + H = 0.0; + S = 0.0; + return; + } + + if (R >= G && R >= B) + { + // R is largest + if (B >= G) + { + H = 6.0 / 6.0 - 1.0 / 6.0 * (B - G) / (R - G); + S = 1.0 - G / R; + } + else + { + H = 0.0 / 6.0 + 1.0 / 6.0 * (G - B) / (R - B); + S = 1.0 - B / R; + } + } + else if (G >= R && G >= B) + { + // G is largest + if (R >= B) + { + H = 2.0 / 6.0 - 1.0 / 6.0 * (R - B) / (G - B); + S = 1.0 - B / G; + } + else + { + H = 2.0 / 6.0 + 1.0 / 6.0 * (B - R) / (G - R); + S = 1.0 - R / G; + } + } + else + { + // B is largest + if (G >= R) + { + H = 4.0 / 6.0 - 1.0 / 6.0 * (G - R) / (B - R); + S = 1.0 - R / B; + } + else + { + H = 4.0 / 6.0 + 1.0 / 6.0 * (R - G) / (B - G); + S = 1.0 - G / B; + } + } + } + + private static void HSPtoRGB(double H, double S, double P, out double R, out double G, out double B) + { + double part, minOverMax = 1.00-S; + + if (minOverMax > 0.0) + { + if (H < 1.0/6.0) { + // R>G>B + H = 6.0*(H - 0.0/6.0); + part = 1.0+H * (1.0/minOverMax - 1.0); + B = P / Math.Sqrt(Pr / minOverMax / minOverMax + Pg * part * part + Pb); + R = (B) / minOverMax; + G = (B) + H * ((R) - (B)); + } + else if (H < 2.0/6.0) { + // G>R>B + H = 6.0*(-H + 2.0/6.0); + part = 1.0+H * (1.0/minOverMax - 1.0); + B = P / Math.Sqrt(Pg / minOverMax / minOverMax + Pr * part * part + Pb); + G = (B) / minOverMax; + R = (B) + H * ((G) - (B)); + } + else if (H < 3.0/6.0) { + // G>B>R + H = 6.0*(H - 2.0/6.0); + part = 1.0+H * (1.0/minOverMax - 1.0); + R = P / Math.Sqrt(Pg / minOverMax / minOverMax + Pb * part * part + Pr); + G = (R) / minOverMax; + B = (R) + H * ((G) - (R)); + } + else if (H < 4.0/6.0) { + // B>G>R + H = 6.0*(-H + 4.0/6.0); + part = 1.0+H * (1.0/minOverMax - 1.0); + R = P / Math.Sqrt(Pb / minOverMax / minOverMax + Pg * part * part + Pr); + B = (R) / minOverMax; + G = (R) + H * ((B) - (R)); + } + else if (H < 5.0/6.0) { + // B>R>G + H = 6.0*(H - 4.0/6.0); + part = 1.0+H * (1.0/minOverMax - 1.0); + G = P / Math.Sqrt(Pb / minOverMax / minOverMax + Pr * part * part + Pg); + B = (G) / minOverMax; + R = (G) + H * ((B) - (G)); + } + else { + // R>B>G + H = 6.0*(-H + 6.0/6.0); + part = 1.0+H * (1.0/minOverMax - 1.0); + G = P / Math.Sqrt(Pr / minOverMax / minOverMax + Pb * part * part + Pg); + R = (G) / minOverMax; + B = (G) + H * ((R) - (G)); + } + } + else + { + if (H < 1.0/6.0) { + // R>G>B + H = 6.0*(H - 0.0/6.0); + R = Math.Sqrt(P * P / (Pr + Pg * H * H)); + G = (R) * H; + B = 0.0; + } + else if (H < 2.0/6.0) { + // G>R>B + H = 6.0*(-H + 2.0/6.0); + G = Math.Sqrt(P * P / (Pg + Pr * H * H)); + R = (G) * H; + B = 0.0; + } + else if (H < 3.0/6.0) { + // G>B>R + H = 6.0*(H - 2.0/6.0); + G = Math.Sqrt(P * P / (Pg + Pb * H * H)); + B = (G) * H; + R = 0.0; + } + else if (H < 4.0/6.0) { + // B>G>R + H = 6.0*(-H + 4.0/6.0); + B = Math.Sqrt(P * P / (Pb + Pg * H * H)); + G = (B) * H; + R = 0.0; + } + else if (H < 5.0/6.0) { + // B>R>G + H = 6.0*(H - 4.0/6.0); + B = Math.Sqrt(P * P / (Pb + Pr * H * H)); + R = (B) * H; + G = 0.0; + } + else { + // R>B>G + H = 6.0*(-H + 6.0/6.0); + R = Math.Sqrt(P * P / (Pr + Pb * H * H)); + B = (R) * H; + G = 0.0; + } + } + } +} \ No newline at end of file diff --git a/Atomorph.NET/Models/Frame.cs b/Atomorph.NET/Models/Frame.cs new file mode 100644 index 0000000..8052cb4 --- /dev/null +++ b/Atomorph.NET/Models/Frame.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; + +namespace Atomorph.Models; + +public class Frame +{ + public List Blobs { get; init; } = []; + + /// + /// Map of pixels by position + /// + public Dictionary Pixels { get; init; } = new(); + + /// + /// Map of blobs by position + /// + public Dictionary Owners { get; init; } = new(); + + public double X { get; set; } + public double Y { get; set; } + public double R { get; set; } + public double G { get; set; } + public double B { get; set; } + public double A { get; set; } + + + /// + /// Position in the nest container + /// + public ulong Index { get; set; } + + /// + /// Blobs before this index cannot expand + /// + public ulong FirstExpansion { get; set; } + + /// + /// First under-sized blob to be unified + /// + public ulong FirstDust { get; set; } +} \ No newline at end of file diff --git a/Atomorph.NET/Models/Pixel.cs b/Atomorph.NET/Models/Pixel.cs new file mode 100644 index 0000000..d861ffb --- /dev/null +++ b/Atomorph.NET/Models/Pixel.cs @@ -0,0 +1,10 @@ +namespace Atomorph.Models; + +public record struct Pixel +{ + public ushort X { get; set; } + public ushort Y { get; set; } + + public Color Color { get; set; } +} + diff --git a/Atomorph.NET/Models/Point.cs b/Atomorph.NET/Models/Point.cs new file mode 100644 index 0000000..7fc2322 --- /dev/null +++ b/Atomorph.NET/Models/Point.cs @@ -0,0 +1,54 @@ +namespace Atomorph.Models; + +public record struct Point +{ + // typedef union key_point { + // struct { + // uint16_t x; + // uint16_t y; + // uint8_t x_fract; + // uint8_t y_fract; + // uint8_t flags; + // } s; + // uint64_t word; + // } point; + // + + private ulong _word; + + public ulong Word + { + get => _word; + set => _word = value; + } + + public ushort X + { + get => (ushort)(_word & 0xFFFF); + set => _word = (_word & ~0xFFFFUL) | value; + } + + public ushort Y + { + get => (ushort)((_word >> 16) & 0xFFFF); + set => _word = (_word & ~(0xFFFFUL << 16)) | ((ulong)value << 16); + } + + public byte XFract + { + get => (byte)((_word >> 32) & 0xFF); + set => _word = (_word & ~(0xFFUL << 32)) | ((ulong)value << 32); + } + + public byte YFract + { + get => (byte)((_word >> 40) & 0xFF); + set => _word = (_word & ~(0xFFUL << 40)) | ((ulong)value << 40); + } + + public PointFlags Flags + { + get => (PointFlags)((_word >> 48) & 0xFF); + set => _word = (_word & ~(0xFFUL << 48)) | ((ulong)value << 48); + } +} \ No newline at end of file diff --git a/Atomorph.NET/Morph.cs b/Atomorph.NET/Morph.cs new file mode 100644 index 0000000..1dfc13d --- /dev/null +++ b/Atomorph.NET/Morph.cs @@ -0,0 +1,1779 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using Atomorph.FluidModel; +using Atomorph.GLNemo; +using Atomorph.Models; +using Atomorph.Perlin; +using Pcg; + +namespace Atomorph; + +public class Morph : IDisposable +{ + private Dictionary _frames = new(); + private Dictionary _chains = new(); + private uint _fluidSteps; + private uint _seed; + private ushort _bBoxX1 = ushort.MaxValue; + private ushort _bBoxY1 = ushort.MaxValue; + private ushort _bBoxX2 = 0; + private ushort _bBoxY2 = 0; + + private ushort _width = 0; + private ushort _height = 0; + + private ulong _identifier = 0; + private bool _skipState = false; + + private AtomorphThread _worker = new(); + private double _energy = 0.0; + + private PerlinNoise _lagMap = new(); + private PerlinNoise _slopeMap = new(); + + private FluidModel.FluidModel? _fluid; + private uint sparseness = 1; + + private PcgRandom _random = new(); + + public InterpolationMethod Fading { get; set; } = InterpolationMethod.Perlin; + public InterpolationMethod Motion { get; set; } = InterpolationMethod.Spline; + public ColorMethod BlobDelimiter { get; set; } = ColorMethod.HSP; + public double BlobThreshold { get; set; } = 1.0; + public ulong BlobNumber { get; set; } = 1; + public ulong BlobMaxSize { get; set; } = ulong.MaxValue; + public ulong BlobMinSize { get; set; } = 1; + public ulong BlobBoxSamples { get; set; } = 10; + public ushort BlobBoxGrip { get; set; } = ushort.MaxValue; + public byte BlobRgbaWeight { get; set; } = 1; + public byte BlobSizeWeight { get; set; } = 1; + public byte BlobXyWeight { get; set; } = 1; + public ulong Degeneration { get; set; } = 0; + public ushort Density { get; private set; } = 1; + public ulong Threads { get; set; } = 0; + public ulong CycleLength { get; set; } = 1000; + public ulong Feather { get; set; } = 0; + public bool KeepBackground { get; set; } = false; + public bool BlendBlobs { get; set; } = false; + public bool Finite { get; set; } = false; + private ShowBlobs ShowBlobs { get; set; } = ShowBlobs.Texture; + public MorphState State { get; private set; } = MorphState.BlobDetection; + + public void Clear() + { + _frames.Clear(); + _chains.Clear(); + _identifier = 0; + _energy = 0.0; + _bBoxX1 = ushort.MaxValue; + _bBoxY1 = ushort.MaxValue; + _bBoxX2 = 0; + _bBoxY2 = 0; + + if (_worker.IsRunning()) + { + _worker.Stop(); + _worker.Clear(); + } + if (_fluid is not null) + { + _fluid.Dispose(); + _fluid = null; + } + } + + public bool AddPixel(ulong frame_key, Pixel px) + { + if (BlobDelimiter == ColorMethod.HSP) + { + px.Color = ColorUtilities.RgbToHsp(px.Color); + } + + AddFrame(frame_key); + + var f = _frames[frame_key]; + + var pixelmap = f.Pixels; + ulong pos = (ulong)(px.Y * (ushort.MaxValue + 1) + px.X); + + pixelmap[pos] = px; + _identifier++; + + if (px.X < _bBoxX1) _bBoxX1 = px.X; + if (px.Y < _bBoxY1) _bBoxY1 = px.Y; + if (px.X > _bBoxX2) _bBoxX2 = px.X; + if (px.Y > _bBoxY2) _bBoxY2 = px.Y; + + if (pixelmap.Count == 1) + { + f.X = px.X; + f.Y = px.Y; + f.R = px.Color.B / 255.0; + f.G = px.Color.G / 255.0; + f.B = px.Color.B / 255.0; + f.A = px.Color.A / 255.0; + return true; + } + + double weight = 1.0 / pixelmap.Count; + f.X = (1.0 - weight) * f.X + weight * px.X; + f.Y = (1.0 - weight) * f.Y + weight * px.Y; + f.R = (1.0 - weight) * f.R + weight * (px.Color.R / 255.0); + f.G = (1.0 - weight) * f.G + weight * (px.Color.G / 255.0); + f.B = (1.0 - weight) * f.B + weight * (px.Color.B / 255.0); + f.A = (1.0 - weight) * f.A + weight * (px.Color.A / 255.0); + + return true; + } + + public bool AddFrame(ulong frame_key) + { + if (_frames.ContainsKey(frame_key)) return false; + var frame = new Frame + { + X = (_bBoxX1 <= _bBoxX2 ? (_bBoxX1 + _bBoxX2) / 2.0 : 0.0), + Y = (_bBoxY1 <= _bBoxY2 ? (_bBoxY1 + _bBoxY2) / 2.0 : 0.0) + }; + + _frames[frame_key] = frame; + + RefreshFrames(); + + return true; + } + + public ulong GetPixelCount(ulong f) + { + if (!HasFrame(f)) return 0; + return (ulong)_frames[f].Pixels.Count; + } + + public ulong GetFrameKey(double t) + { + t %= 1.0; + if (t < 0.0) t += 1.0; + + var f = (ulong)(t * (ulong)_frames.Count); + + ulong i = 0; + var frame = ulong.MaxValue; + foreach (var it in _frames) + { + if (i++ == f) + { + frame = it.Key; + break; + } + } + return frame; + } + + public ulong GetBlobCount(ulong f) + { + if (!HasFrame(f)) return 0; + return (ulong)_frames[f].Blobs.Count; + } + + public ulong GetBlobCount() + { + ulong count = 0; + foreach (var it in _frames) + { + count += GetBlobCount(it.Key); + } + return count; + } + + public Pixel GetAveragePixel(ulong f) + { + if (!HasFrame(f)) return new Pixel(); + var x = Math.Round(_frames[f].X); + var y = Math.Round(_frames[f].Y); + var r = Math.Round(255.0 * _frames[f].R); + var g = Math.Round(255.0 * _frames[f].G); + var b = Math.Round(255.0 * _frames[f].B); + var a = Math.Round(255.0 * _frames[f].A); + var color = new Color((byte)r, (byte)g, (byte)b, (byte)a); + + if (BlobDelimiter == ColorMethod.RGB) + { + color = ColorUtilities.RgbToHsp(color); + } + + return new Pixel { X = (ushort)x, Y = (ushort)y, Color = color, }; + } + + public Pixel GetAveragePixel(ulong f, ulong blobIndex) + { + if (!HasFrame(f) || (ulong)_frames[f].Blobs.Count <= blobIndex || _frames[f].Blobs[(int)blobIndex] is null) + { + return new Pixel(); + } + + var blob = _frames[f].Blobs[(int)blobIndex]!; + var x = Math.Round(blob.X); + var y = Math.Round(blob.Y); + var r = Math.Round(255.0 * blob.R); + var g = Math.Round(255.0 * blob.G); + var b = Math.Round(255.0 * blob.B); + var a = Math.Round(255.0 * blob.A); + + var color = new Color((byte)r, (byte)g, (byte)b, (byte)a); + if (BlobDelimiter == ColorMethod.HSP) + { + color = ColorUtilities.RgbToHsp(color); + } + + return new Pixel { X = (ushort)x, Y = (ushort)y, Color = color, }; + } + + public Pixel GetPixel(ulong f, ulong pos) + { + if (!HasPixel(f, pos)) return new Pixel(); + var px = _frames[f].Pixels[pos]; + if (BlobDelimiter == ColorMethod.HSP) + px.Color = ColorUtilities.HspToRgb(px.Color); + return px; + } + + public Color GetBackground(ushort x, ushort y, double time) + { + if (!_frames.Any()) return ColorUtilities.CreateColor(0.0, 0.0, 0.0, 0.0); + ulong position = AtomorphUtilities.XY2Pos(x, y); + + time = NormalizeTime(time); + double t = time; + + ulong frame_key = GetFrameKey(t); + + var next_frame_key = _frames.Keys.FirstOrDefault(k => k > frame_key); + if (next_frame_key == 0) next_frame_key = _frames.Keys.FirstOrDefault(); + + double dt = 1.0 / (double)(_frames.Count); + t = Math.Max(0.0, (t - (frame_key * dt)) / dt); + + var c1 = GetPixel(frame_key, position).Color; + var c2 = GetPixel(next_frame_key, position).Color; + + if (Fading == InterpolationMethod.Perlin) + { + double f = 8.0; // Frequency + int octaves = 8; // Octaves + double bbox_w = _bBoxX2 - _bBoxX1 + 1.0; + double bbox_h = _bBoxY2 - _bBoxY1 + 1.0; + double perlin_x = ((x - _bBoxX1) / bbox_w) * f; + double perlin_y = ((y - _bBoxY1) / bbox_h) * f; + double lag = _lagMap.OctaveNoise(perlin_x, perlin_y, octaves) * 0.5 + 0.5; + double slope = _slopeMap.OctaveNoise(perlin_x, perlin_y, 8) * 0.5 + 0.5; + + return Interpolate(c1, c2, lag, slope, 1.0 - t); + } + else if (Fading == InterpolationMethod.Cosine) return Interpolate(c1, c2, 0.5, 0.5, 1.0 - t); + + return Interpolate(c1, c2, 1.0 - t); + } + + public Point Interpolate(Point pt1, Point pt2, double pt1Weight) + { + Point pt = new(); + + double x1 = ((double)(byte.MaxValue+1)*pt1.X + pt1.XFract); + double y1 = ((double)(byte.MaxValue+1)*pt1.Y + pt1.YFract); + double x2 = ((double)(byte.MaxValue+1)*pt2.X + pt2.XFract); + double y2 = ((double)(byte.MaxValue+1)*pt2.Y + pt2.YFract); + double x = (pt1Weight * x1 + (1.0 - pt1Weight) * x2); + double y = (pt1Weight * y1 + (1.0 - pt1Weight) * y2); + + pt.X = (ushort)(x / (byte.MaxValue+1)); + pt.XFract = (byte)(x - (pt.X*(byte.MaxValue+1))); + pt.Y = (ushort)(y / (byte.MaxValue+1)); + pt.YFract = (byte)(y - (pt.Y*(byte.MaxValue+1))); + + return pt; + } + + public Pixel Interpolate(Pixel px1, Pixel px2, double px1Weight) + { + Pixel px = new() + { + X = (ushort)Math.Round(px1Weight * px1.X + (1.0 - px1Weight) * px2.X), + Y = (ushort)Math.Round(px1Weight * px1.Y + (1.0 - px1Weight) * px2.Y), + Color = new Color((byte)Math.Round(px1Weight * px1.Color.R + (1.0 - px1Weight) * px2.Color.R), + (byte)Math.Round(px1Weight * px1.Color.G + (1.0 - px1Weight) * px2.Color.G), + (byte)Math.Round(px1Weight * px1.Color.B + (1.0 - px1Weight) * px2.Color.B), + (byte)Math.Round(px1Weight * px1.Color.A + (1.0 - px1Weight) * px2.Color.A)), + }; + return px; + } + + public Color Interpolate(Color c1, Color c2, double c1Weight) + { + Color c = new((byte)Math.Round(c1Weight * c1.R + (1.0 - c1Weight) * c2.R), + (byte)Math.Round(c1Weight * c1.G + (1.0 - c1Weight) * c2.G), + (byte)Math.Round(c1Weight * c1.B + (1.0 - c1Weight) * c2.B), + (byte)Math.Round(c1Weight * c1.A + (1.0 - c1Weight) * c2.A)); + return c; + } + + public Color Interpolate(Color c1, Color c2, double lag, double slope, double str) + { + if (Fading is InterpolationMethod.Cosine or InterpolationMethod.Perlin) { + const double pi = 3.14159265358; + double s = (slope+0.1)/1.1; + double l = (1.0 - s) * lag; + + if (str <= l ) str = 0.0; + else if (str >= (l+s)) str = 1.0; + else str = ((-Math.Cos((str-l)*(pi/s))+1.0)/2.0); + } + + return Interpolate(c1, c2, str); + } + + public Blob? GetPixels(ulong blob_index, double time, out List? to) + { + time = NormalizeTime(time); + double t = time; + to = []; + + if (!_frames.Any()) return null; + + ulong frame_key = GetFrameKey(t); + ulong blob_count = GetBlobCount(frame_key); + + if (blob_index >= blob_count) return null; + + double dt = 1.0 / (double)(_frames.Count); + t = Math.Max(0.0, (t - (frame_key * dt)) / dt); + + var bl = GetBlob(frame_key, blob_index); + if (bl is null) return null; + + if (!_chains.Any()) + { + foreach (var v in bl.Surface) + { + var px = GetPixel(frame_key, v); + to.Add(px); + } + } + else + { + Dictionary> colors = new(); + Dictionary> weights = new(); + + if (!_chains.ContainsKey(bl.Group)) + return null; + + ulong chainWidth = _chains[bl.Group].Width; + ulong h = _chains[bl.Group].Height; + var p = _chains[bl.Group].Points; + + ulong yIndex = _frames[frame_key].Index; + ulong y_next = (yIndex + 1) % h; + + var next_frame_key = _frames.Keys.FirstOrDefault(k => k > frame_key); + if (next_frame_key == 0) next_frame_key = _frames.Keys.FirstOrDefault(); + + for (ulong x = 0; x < chainWidth; ++x) + { + Pixel px1, px2; + Point pt1 = p[x][yIndex]; + Point pt2 = p[x][y_next]; + + if (!pt1.PointHasPixel() && !pt2.PointHasPixel()) continue; + + if (pt1.PointHasPixel() && !pt2.PointHasPixel()) + { + px1 = GetPixel(frame_key, AtomorphUtilities.XY2Pos(pt1.X, pt1.Y)); + px2 = px1; + px2.X = pt2.X; + px2.Y = pt2.Y; + px2.Color = new Color(px2.Color.R, px2.Color.G, px2.Color.B, 0); + } + else if (pt2.PointHasPixel() && !pt1.PointHasPixel()) + { + px2 = GetPixel(next_frame_key, AtomorphUtilities.XY2Pos(pt2.X, pt2.Y)); + px1 = px2; + px1.X = pt1.X; + px1.Y = pt1.Y; + px1.Color = new Color(px1.Color.R, px1.Color.G, px1.Color.B, 0); + } + else + { + px1 = GetPixel(frame_key, AtomorphUtilities.XY2Pos(pt1.X, pt1.Y)); + px2 = GetPixel(next_frame_key, AtomorphUtilities.XY2Pos(pt2.X, pt2.Y)); + } + Point pt = pt1; + + if (Motion == InterpolationMethod.Linear) + pt = Interpolate(pt1, pt2, 1.0 - t); + else if (Motion == InterpolationMethod.Spline && _chains[bl.Group].Splines is not null) + { + var v = _chains[bl.Group].Splines![x].GetInterpolatedSplinePoint(time); + var fract = v.X % 1.0; + var integ = Math.Floor(v.X); + pt.X = (ushort)integ; + pt.XFract = (byte)Math.Round(fract * byte.MaxValue); + fract = v.Y % 1.0; + integ = Math.Floor(v.Y); + pt.Y = (ushort)integ; + pt.YFract = (byte)Math.Round(fract * byte.MaxValue); + } + + Pixel px = new() { X = pt.X, Y = pt.Y }; + + if (Fading == InterpolationMethod.Perlin) + { + double f = 8.0; // Frequency + int octaves = 8; // Octaves + double bbox_w = _bBoxX2 - _bBoxX1 + 1.0; + double bbox_h = _bBoxY2 - _bBoxY1 + 1.0; + double perlin_x = (((pt1.X - _bBoxX1) * (byte.MaxValue + 1) + pt1.XFract) / + (double)(bbox_w * (byte.MaxValue + 1))) * f; + double perlin_y = (((pt1.Y - _bBoxY1) * (byte.MaxValue + 1) + pt1.YFract) / + (double)(bbox_h * (byte.MaxValue + 1))) * f; + double lag = _lagMap.OctaveNoise(perlin_x, perlin_y, octaves) * 0.5 + 0.5; + double slope = _slopeMap.OctaveNoise(perlin_x, perlin_y, 8) * 0.5 + 0.5; + + px.Color = Interpolate(px1.Color, px2.Color, lag, slope, 1.0 - t); + } + else if (Fading == InterpolationMethod.Cosine) + px.Color = Interpolate(px1.Color, px2.Color, 0.5, 0.5, 1.0 - t); + else + px.Color = Interpolate(px1.Color, px2.Color, 1.0 - t); + + if (px.X >= _width || px.Y >= _height) + { + if (px.X > _bBoxX2 || px.X < _bBoxX1 || px.Y > _bBoxY2 || px.Y < _bBoxY1) continue; + } + + // Bilinear interpolation: + double total_weight = byte.MaxValue * byte.MaxValue; + double weight_x1y1 = ((byte.MaxValue - pt.XFract) * (byte.MaxValue - pt.YFract)) / total_weight; + double weight_x2y1 = (pt.XFract * (byte.MaxValue - pt.YFract)) / total_weight; + double weight_x1y2 = ((byte.MaxValue - pt.XFract) * pt.YFract) / total_weight; + double weight_x2y2 = (pt.XFract * pt.YFract) / total_weight; + + ulong pos = AtomorphUtilities.XY2Pos(px.X, px.Y); + if (weight_x1y1 > 0.0) + { + colors.AddToDictionaryList(pos, px.Color); + weights.AddToDictionaryList(pos, weight_x1y1); + } + if ((px.X < _bBoxX2 || px.X + 1 < _width) && weight_x2y1 > 0.0) + { + pos = AtomorphUtilities.XY2Pos((ushort)(px.X + 1), px.Y); + colors.AddToDictionaryList(pos, px.Color); + weights.AddToDictionaryList(pos, weight_x2y1); + } + + if ((px.Y < _bBoxY2 || px.Y + 1 < _height) && weight_x1y2 > 0.0) + { + pos = AtomorphUtilities.XY2Pos(px.X, (ushort)(px.Y + 1)); + colors.AddToDictionaryList(pos, px.Color); + weights.AddToDictionaryList(pos, weight_x1y2); + } + + if (weight_x2y2 > 0.0) + { + if ((px.Y < _bBoxY2 && px.X < _bBoxX2) || (px.Y + 1 < _height && px.X + 1 < _width)) + { + pos = AtomorphUtilities.XY2Pos((ushort)(px.X + 1), (ushort)(px.Y + 1)); + colors.AddToDictionaryList(pos, px.Color); + weights.AddToDictionaryList(pos, weight_x2y2); + } + } + } + + Dictionary blob = new(); + foreach (var cit in colors) + { + var cs = cit.Value; + var ws = weights[cit.Key]; + ulong vsz = (ulong)cs.Count; + + double r = 0.0, g = 0.0, b = 0.0, a = 0.0; + double weight_sum = 0.0; + for (ulong c = 0; c < vsz; ++c) + { + weight_sum += ws[(int)c]; + r += cs[(int)c].R * ws[(int)c]; + g += cs[(int)c].G * ws[(int)c]; + b += cs[(int)c].B * ws[(int)c]; + a += cs[(int)c].A * ws[(int)c]; + } + double w = Density > 0 ? vsz / (double)(Density) : 0.0; + if (w > 1.0) w = 1.0; + + r = Math.Round(r / weight_sum); + g = Math.Round(g / weight_sum); + b = Math.Round(b / weight_sum); + a = Math.Round(w * (a / weight_sum)); + + ulong pos = cit.Key; + var x = pos % (ushort.MaxValue + 1); + var y = pos / (ushort.MaxValue + 1); + + var px = new Pixel + { + X = (ushort)x, Y = (ushort)y, Color = new Color((byte)r, (byte)g, (byte)b, (byte)a) + }; + + if (Feather > 0) blob[pos] = px; + else to.Add(px); + } + + if (Feather > 0) + { + List> layers = new(); + var peeled_blob = blob; + while (peeled_blob.Any() && (ulong)layers.Count < Feather) + { + HashSet border = new(); + foreach (var pit in peeled_blob) + { + ulong pos = pit.Key; + var x = pos % (ushort.MaxValue + 1); + var y = pos / (ushort.MaxValue + 1); + + if (x == 0 || x == ushort.MaxValue || y == 0 || y == ushort.MaxValue) + { + border.Add(pos); + continue; + } + + if (peeled_blob.ContainsKey(AtomorphUtilities.XY2Pos((ushort)(x + 1), (ushort)y)) || + peeled_blob.ContainsKey(AtomorphUtilities.XY2Pos((ushort)(x - 1), (ushort)y)) || + peeled_blob.ContainsKey(AtomorphUtilities.XY2Pos((ushort)x, (ushort)(y + 1))) || + peeled_blob.ContainsKey(AtomorphUtilities.XY2Pos((ushort)x, (ushort)(y - 1)))) + { + border.Add(pos); + } + } + foreach (var bt in border) + { + ulong pos = bt; + peeled_blob.Remove(pos); + } + + layers.Add(border); + } + + ulong lsz = (ulong)layers.Count; + for (ulong l = 0; l < lsz; ++l) + { + var layer = layers[(int)l]; + foreach (var lt in layer) + { + var px = blob[lt]; + var a = Math.Round((double)(px.Color.A) * ((double)(l + 1) / (double)(Feather + 1))); + px.Color = new Color(px.Color.R, px.Color.G, px.Color.B, (byte)a); + to.Add(px); + } + } + + foreach (var pit in peeled_blob) + { + to.Add(pit.Value); + } + } + } + + return bl; + } + + public void GetPixels(double t, List image) + { + image.Clear(); + image.Capacity = _width * _height; + + for (ulong y = 0; y < _height; ++y) + { + for (ulong x = 0; x < _width; ++x) + { + var px = new Pixel() { X = (ushort)x, Y = (ushort)y, Color = new Color(0, 0, 0, 0), }; + if (KeepBackground) px.Color = GetBackground((ushort)x, (ushort)y, t); + image.Add(px); + } + } + + if (_fluid is not null && _fluidSteps > 0) DrawFluid(t, image); + else DrawAtoms(t, image); + + return; + } + + public void SetSeed(uint seed) + { + _seed = seed; + _random = new PcgRandom((int)Convert.ChangeType(seed, typeof(int))); + _lagMap = new PerlinNoise(seed); + _slopeMap = new PerlinNoise(seed + 1); + } + + public double GetTime(ulong frameIndex, ulong totalFrames) + { + if (totalFrames == 0) return 0.0; + + if (Finite) { + if (totalFrames == 1) { + if (GetFrameCount() == 0) return 0.0; + + return (1.0 - (1.0/GetFrameCount()))/2.0; + } + + var t = frameIndex / (double)(totalFrames-1); + t*= 1.0 - (1.0/GetFrameCount()); + return t; + } + + return frameIndex / (double)(totalFrames); + } + + public double NormalizeTime(double t) + { + var time = t % 1.0; + if (time < 0.0) time += 1.0; + return time; + } + + // Property accessors + public ushort GetWidth() => _width; + public ushort GetHeight() => _height; + public ulong GetFrameCount() => (ulong)_frames.Count; + public void NextState() => _skipState = true; + public Blob? GetBlob(ulong f, ulong b) => HasBlob(f, b) ? _frames[f].Blobs[(int)b] : null; + public double GetEnergy() => _energy; + + public Pixel Blob2Pixel(Blob bl) + { + var px = new Pixel() + { + X = (ushort)bl.X, Y = (ushort)bl.Y, Color = ColorUtilities.CreateColor(bl.R, bl.G, bl.B, bl.A) + }; + if (BlobDelimiter == ColorMethod.HSP) + { + px.Color = ColorUtilities.HspToRgb(px.Color); + } + return px; + } + + public void Compute() + { + if (IsBusy()) return; + if (_worker.IsRunning()) _worker.Resume(); + else _worker.Start(); + } + + public void Iterate(ulong iterations) + { + if (IsBusy()) return; + if (_worker.IsRunning()) _worker.Resume(iterations); + else _worker.Start(iterations); + } + + public void Compute(double seconds) + { + if (IsBusy()) return; + if (_worker.IsRunning()) _worker.Resume(seconds); + else _worker.Start(seconds); + } + + public void Suspend() + { + while (IsBusy()) + { + _worker.Pause(); + Thread.Sleep(0); + } + } + + public bool Suspend(double timeout) + { + if (!IsBusy()) return true; + + var tStart = DateTime.UtcNow; + + while (true) + { + // Attempt to suspend the worker. + _worker.Pause(); + if (_worker.IsPaused()) break; + + var tEnd = DateTime.UtcNow; + if ((tEnd - tStart).TotalSeconds > timeout) + { + return false; + } + + Thread.Sleep(0); + } + + return true; + } + + public bool IsBusy() => _worker.IsRunning() && !_worker.IsPaused(); + + public bool Synchronize() + { + if (!_worker.IsPaused()) return false; + + if (_worker.Seed != _seed) _worker.SetSeed(_seed); + + _worker.SetBlobDelimiter(BlobDelimiter); + _worker.SetBlobThreshold(BlobThreshold); + _worker.SetBlobMaxSize(BlobMaxSize); + _worker.SetBlobMinSize(BlobMinSize); + _worker.SetBlobBoxGrip(BlobBoxGrip); + _worker.SetBlobBoxSamples(BlobBoxSamples); + _worker.SetBlobNumber(BlobNumber); + _worker.SetDegeneration(Degeneration); + _worker.SetDensity(Density); + _worker.SetThreads(Threads); + _worker.SetCycleLength(CycleLength); + + _worker.SetBbox(_bBoxX1, _bBoxY1, _bBoxX2, _bBoxY2); + _worker.SetBlobWeights(BlobRgbaWeight, BlobSizeWeight, BlobXyWeight); + + if (_identifier != _worker.Identifier) + { + // Reset everything. + _worker.Clear(); + + RefreshFrames(); + foreach (var it in _frames) + { + _worker.SetFrame(it.Key, it.Value); + } + _worker.Identifier = _identifier; + + _fluid?.Dispose(); + _fluid = null; + } + + { + // Load results. + State = _worker.State; + _energy = _worker.GetEnergy(); + + foreach (var fit in _frames) + { + var to = fit.Value; + var from = _worker.GetFrame(fit.Key); + + to.Blobs.Clear(); + to.Owners.Clear(); + + for (ulong i = 0; i < (ulong)from.Blobs.Count; ++i) + { + var b = from.Blobs[(int)i]; + if (b is null) continue; + + var new_blob = new Blob() + { + Index = b.Index, + R = b.R, + G = b.G, + B = b.B, + A = b.A, + X = b.X, + Y = b.Y, + Surface = b.Surface, + Group = b.Group, + }; + + to.Blobs.Add(new_blob); + } + } + + var chains_from = _worker.Chains; + // Get chain updates from _worker's chains. + foreach (var cit in chains_from) + { + ulong chain_key = cit.Key; + + // If this chain already exists, it might have different attributes. + if (( + !_chains.TryGetValue(chain_key, out var cha) || (cha.Width != chains_from[chain_key].Width || + cha.Height != chains_from[chain_key].Height))) + { + cha ??= _chains[chain_key] = new Chain(); + // Chains are different, free the target to allocate memory again later. + if (!AtomorphUtilities.RenewChain(cha, cit.Value.Width, cit.Value.Height)) + { + _chains.Remove(chain_key); + return false; + } + } + + // Normally the above memory allocation is not needed because the morph should + // not change its parameters very often, although the implementation allows it + // by essentially restarting the whole procedure whenever critical parameters + // change. For normal synchronization, only the below code is called to refresh + // the key points and splines for example. + for (ulong y = 0; y < _chains[chain_key].Height; ++y) + { + for (ulong x = 0; x < _chains[chain_key].Width; ++x) + { + _chains[chain_key].Points[x][y] = chains_from[chain_key].Points[x][y]; + + double vx = _chains[chain_key].Points[x][y].X + + _chains[chain_key].Points[x][y].XFract / (double)(byte.MaxValue + 1); + double vy = _chains[chain_key].Points[x][y].Y + + _chains[chain_key].Points[x][y].YFract / (double)(byte.MaxValue + 1); + + if (y == 0) _chains[chain_key].GetSpline(x).ClearCPoints(); + _chains[chain_key].GetSpline(x).AddSplinePoint(new Vec3D(vx, vy, 0.0)); + } + } + if (_chains[chain_key].MaxSurface != chains_from[chain_key].MaxSurface) + { + // Number of particles in the fluid simulator has changed, reset the simulation. + _chains[chain_key].MaxSurface = chains_from[chain_key].MaxSurface; + if (_fluid is not null) + { + _fluid.Dispose(); + _fluid = null; + } + } + } + // Delete _chains that don't exist in _worker's _chains. + List delete_keys = []; + foreach (var cit in _chains) + { + if (chains_from.ContainsKey(cit.Key)) continue; + delete_keys.Add(cit.Key); + } + while (delete_keys.Any()) + { + AtomorphUtilities.ClearChain(_chains[delete_keys.Last()]); + _chains.Remove(delete_keys.Last()); + delete_keys.RemoveAt(delete_keys.Count - 1); + } + + _worker.Identifier = _identifier; + + if (_skipState) + { + _worker.NextState(); + _skipState = false; + } + + // Initialize the fluid simulator if needed. + if (_fluid is null && _width > 0 && _height > 0) + { + ulong particle_count = 0; + + foreach (var cit in _chains) + { + particle_count += cit.Value.MaxSurface; + } + + _fluid = new FluidModel.FluidModel(_width * sparseness + 20, _height * sparseness + 20, + (uint)particle_count); + if (_fluid is not null) + { + var particles = _fluid.Particles; + + for (ulong i = 0; i < particle_count; ++i) + { + var p = particles[(int)i]; + + p.Clear(); + p.X = _width * sparseness / 2.0 - 10; + p.Y = _height * sparseness / 2.0 - 10; + p.U = 0.0; + p.V = 0.0; + p.GravityX = p.X; + p.GravityY = p.Y; + p.FreedomR = 1.0; + p.R = 0.0; + p.r = p.R; + p.G = 1.0; + p.g = p.G; // Should never appear in morphs. + p.B = 0.0; + p.b = p.B; + p.A = 1.0; + p.a = p.A; + p.Active = false; + p.Mature = false; + } + } + } + } + + return true; + } + + // Configuration setters + public void SetBlobDelimiter(ColorMethod d) => BlobDelimiter = d; + public void SetBlobThreshold(double t) => BlobThreshold = t; + public void SetBlobMaxSize(ulong s) => BlobMaxSize = s; + public void SetBlobMinSize(ulong s) => BlobMinSize = s; + public void SetBlobBoxGrip(ushort g) => BlobBoxGrip = g; + public void SetBlobBoxSamples(ulong s) => BlobBoxSamples = s; + public void SetBlobNumber(ulong n) => BlobNumber = n; + public void SetBlobRgbaWeight(byte w) => BlobRgbaWeight = w; + public void SetBlobSizeWeight(byte w) => BlobSizeWeight = w; + public void SetBlobXyWeight(byte w) => BlobXyWeight = w; + public void SetDegeneration(ulong d) => Degeneration = d; + public void SetMotion(InterpolationMethod m) => Motion = m; + public void SetFading(InterpolationMethod f) => Fading = f; + public void SetThreads(ulong t) => Threads = t; + public void SetCycleLength(ulong c) => CycleLength = c; + public void SetFeather(ulong f) => Feather = f; + public void SetKeepBackground(bool k) => KeepBackground = k; + public void SetFinite(bool f) => Finite = f; + public void SetShowBlobs(ShowBlobs b) => ShowBlobs = b; + + // These change identifier, causing the morph to restart + public void SetFluid(uint f) + { + if (_fluidSteps != f) { + _fluidSteps = f; + if (_fluidSteps > 0 && Density > 1) { + SetDensity(1); + } + } + } + + public void SetDensity(ushort d) + { + if (Density != d) { + Density = d; + _identifier++; + if (_fluidSteps != 0 && Density > 1) { + SetFluid(0); + } + } + } + + public void SetResolution(ushort w, ushort h) + { + _width = w; + _height = h; + } + + // Private methods + private bool HasPixel(ulong f, ulong pos) => HasFrame(f) && _frames[f].Pixels.ContainsKey(pos); + private bool HasFrame(ulong f) => _frames.ContainsKey(f); + private bool HasBlob(ulong f, ulong b) => HasFrame(f) && (ulong)_frames[f].Blobs.Count > b; + + private void RefreshFrames() + { + ulong index = 0; + foreach (var it in _frames) + { + it.Value.Index = index++; + if (!it.Value.Pixels.Any()) + { + it.Value.X = (_bBoxX1 <= _bBoxX2 ? (_bBoxX1 + _bBoxX2) / 2.0 : 0.0); + it.Value.Y = (_bBoxY1 <= _bBoxY2 ? (_bBoxY1 + _bBoxY2) / 2.0 : 0.0); + it.Value.R = 0.0; + it.Value.G = 0.0; + it.Value.B = 0.0; + it.Value.A = 0.0; + } + } + } + + private Blob? FindBlobByGroup(ulong frameKey, ulong group) + { + if (!HasFrame(frameKey)) return null; + + var blobs = _frames[frameKey].Blobs; + ulong bsz = (ulong)blobs.Count; + + for (ulong i=0; i< bsz; ++i) { + if (blobs[(int)i]?.Group == group) + return blobs[(int)i]; + } + + return null; + } + + private void DrawAtoms(double t, List image) + { + Dictionary> colors = new(); + Blob? bl = null; + ulong blockIterator = 0; + + List? pixels = []; + + while ((bl = GetPixels(blockIterator++, t, out pixels)) != null) + { + ulong group = bl.Group; + var px_ave = Blob2Pixel(bl); + + while (pixels.Any()) + { + var px = pixels.Last(); + ulong pos = (ulong)(px.Y * _width + px.X); + pixels.RemoveAt(pixels.Count - 1); + + if (pos >= (ulong)image.Count) continue; + + byte rr, gg, bb, aa; + if (ShowBlobs == ShowBlobs.Distinct) + { + var rng = new Random((int)group); + rr = (byte)rng.Next(0, 256); + gg = (byte)rng.Next(0, 256); + bb = (byte)rng.Next(0, 256); + aa = 255; + } + else if (ShowBlobs == ShowBlobs.Average) + { + rr = px_ave.Color.R; + gg = px_ave.Color.G; + bb = px_ave.Color.B; + aa = px_ave.Color.A; + } + else + { + rr = px.Color.R; + gg = px.Color.G; + bb = px.Color.B; + aa = px.Color.A; + } + + if (aa == 0) continue; + + colors.AddToDictionaryList(pos, new Color(rr, gg, bb, aa)); + } + } + + foreach (var cit in colors) + { + ulong pos = cit.Key; + var cs = cit.Value; + ulong vsz = (ulong)cs.Count; + + double r = 0.0, g = 0.0, b = 0.0, a = 0.0; + double rsum = 0.0, gsum = 0.0, bsum = 0.0, asum = 0.0; + + for (ulong c = 0; c < vsz; ++c) + { + double sr = cs[(int)c].R / 255.0; + double sg = cs[(int)c].G / 255.0; + double sb = cs[(int)c].B / 255.0; + double sa = cs[(int)c].A / 255.0; + + asum += sa; + rsum += sr * sa; + gsum += sg * sa; + bsum += sb * sa; + + if (c == 0) + { + r = sr; + g = sg; + b = sb; + a = sa; + } + else + { + r = sa * sr + (1.0 - sa) * r; + g = sa * sg + (1.0 - sa) * g; + b = sa * sb + (1.0 - sa) * b; + a = a + (1.0 - a) * (cs[(int)c].A / 255.0); + } + } + + if (BlendBlobs) + { + r = rsum / asum; + g = gsum / asum; + b = bsum / asum; + } + + if (KeepBackground) + { + var bgc = image[(int)pos].Color; + double bgr = (double)(bgc.R) / 255.0; + double bgg = (double)(bgc.G) / 255.0; + double bgb = (double)(bgc.B) / 255.0; + double bga = (double)(bgc.A) / 255.0; + + r = a * r + (1.0 - a) * bgr; + g = a * g + (1.0 - a) * bgg; + b = a * b + (1.0 - a) * bgb; + a = bga + (1.0 - bga) * a; + } + var px = image[(int)pos]; + px.Color = ColorUtilities.CreateColor(r, g, b, a); + image[(int)pos] = px; + } + } + + private void DrawFluid(double time, List image) + { + if (_fluid is null || !_chains.Any()) return; + + time = NormalizeTime(time); + double t = time; + + if (!_frames.Any()) return; + + ulong frame_key = GetFrameKey(t); + double dt = 1.0 / (double)(_frames.Count); + t = Math.Max(0.0, (t - (frame_key * dt)) / dt); + // t is 0.0 at the beginning of frame + // t is 1.0 at the end of this frame + + StepFluid(frame_key, t, time); + + Dictionary image_buffer = new(); + + var particles = _fluid.Particles; + ulong particle_count = _fluid.ParticleCount; + + Dictionary> colors = new(); + Dictionary> weights = new(); + Dictionary> startups = new(); + + for (ulong i = 0; i < particle_count; ++i) + { + var p = particles[(int)i]; + if (p.Active == false) continue; + + { + // Correct the colours so they would not blur too much. + // Blobs that appear from nothingness should be blended + // with their surroundings a lot though to avoid sharp + // gradient spots in the very beginnning of the morph. + //double w = 1.0 / (100.0 * std::pow(t, 2.0)+1.0); + double w = (1.0 / (100.0 * Math.Pow((t - (1.0 * (1.0 - p.Strength))), 2.0) + 1.0)) * + Math.Pow(p.Strength, 2.0); + + p.r = (w * p.R) + (1.0 - w) * p.r; + p.g = (w * p.G) + (1.0 - w) * p.g; + p.b = (w * p.B) + (1.0 - w) * p.b; + p.a = (w * p.A) + (1.0 - w) * p.a; + } + + double px, py; + + if (p.X <= 10.0) px = 0.0; + else if (p.X >= _width * sparseness + 10.0) px = (_width - 1); + else px = (p.X - 10.0) / sparseness; + + if (p.Y <= 10.0) py = 0.0; + else if (p.Y >= _height * sparseness + 10.0) py = (_height - 1); + else py = (p.Y - 10.0) / sparseness; + + ushort x = (ushort)Math.Min((int)(px), _width - 1); + ushort y = (ushort)Math.Min((int)(py), _height - 1); + ulong pos = AtomorphUtilities.XY2Pos(x, y); + + if (!p.Mature) + { + p.Mature = true; + } + + double x_fract, y_fract; + + x_fract = PortUtilities.ModF(px, out px); + y_fract = PortUtilities.ModF(py, out py); + + if (px >= _width || py >= _height) + { + if (px > _bBoxX2 || px < _bBoxX1 || py > _bBoxY2 || py < _bBoxY1) continue; + } + + // Bilinear interpolation: + double weight_x1y1 = ((1.0 - x_fract) * (1.0 - y_fract)); + double weight_x2y1 = (x_fract * (1.0 - y_fract)); + double weight_x1y2 = ((1.0 - x_fract) * y_fract); + double weight_x2y2 = (x_fract * y_fract); + + var c = ColorUtilities.CreateColor(p.r, p.g, p.b, p.a); + + if (weight_x1y1 > 0.0) + { + colors[pos].Add(c); + weights[pos].Add(weight_x1y1); + } + if ((x < _bBoxX2 || x + 1 < _width) && weight_x2y1 > 0.0) + { + pos = AtomorphUtilities.XY2Pos((ushort)(x + 1), y); + colors[pos].Add(c); + weights[pos].Add(weight_x2y1); + } + + if ((y < _bBoxY2 || y + 1 < _height) && weight_x1y2 > 0.0) + { + pos = AtomorphUtilities.XY2Pos(x, (ushort)(y + 1)); + colors[pos].Add(c); + weights[pos].Add(weight_x1y2); + } + + if (weight_x2y2 > 0.0) + { + if ((y < _bBoxY2 && x < _bBoxX2) || (y + 1 < _height && x + 1 < _width)) + { + pos = AtomorphUtilities.XY2Pos((ushort)(x + 1), (ushort)(y + 1)); + colors[pos].Add(c); + weights[pos].Add(weight_x2y2); + } + } + } + + Dictionary blob = new(); + foreach (var cit in colors) + { + var cs = cit.Value; + var ws = (weights[cit.Key]); + + ulong vsz = (ulong)cs.Count; + + double r = 0.0, g = 0.0, b = 0.0, a = 0.0; + double weight_sum = 0.0; + for (ulong c = 0; c < vsz; ++c) + { + double weight = ws[(int)c]; + var color = cs[(int)c]; + + weight_sum += weight; + r += color.R * weight; + g += color.G * weight; + b += color.B * weight; + a += color.A * weight; + } + + r = Math.Round(r / weight_sum); + g = Math.Round(g / weight_sum); + b = Math.Round(b / weight_sum); + a = Math.Round(a / weight_sum); + + if (KeepBackground) + { + double alpha = 1.0 - Math.Pow(t, 24.0); + a *= alpha; + } + + ulong pos = cit.Key; + ushort x = (ushort)(pos % (ushort.MaxValue + 1)); + ushort y = (ushort)(pos / (ushort.MaxValue + 1)); + + var px = new Pixel() { X = x, Y = y, Color = ColorUtilities.CreateColor(r, g, b, a) }; + ulong imgpos = (ulong)(y * _width + x); + + if (Feather > 0) blob[pos] = px.Color; + else image_buffer[imgpos] = px.Color; + } + + if (Feather > 0) + { + for (ulong layer = 0; layer < Feather; ++layer) + { + double alpha = 1.0 - ((double)(layer + 1) / (double)(Feather + 1)); + HashSet border = new(); + foreach (var it in blob) + { + ulong pos = it.Key; + ushort x = (ushort)(pos % (ushort.MaxValue + 1)); + ushort y = (ushort)(pos / (ushort.MaxValue + 1)); + + ulong ps; + if (x + 1 < _width && !blob.ContainsKey((ps = AtomorphUtilities.XY2Pos((ushort)(x + 1), y)))) + border.Add(ps); + if (y + 1 < _height && !blob.ContainsKey((ps = AtomorphUtilities.XY2Pos(x, (ushort)(y + 1))))) + border.Add(ps); + if (x > 0 && !blob.ContainsKey((ps = AtomorphUtilities.XY2Pos((ushort)(x - 1), y)))) + border.Add(ps); + if (y > 0 && !blob.ContainsKey((ps = AtomorphUtilities.XY2Pos(x, (ushort)(y - 1))))) + border.Add(ps); + } + + if (!border.Any()) break; + + Dictionary blob_buf = new(); + + foreach (var pos in border) + { + ushort x = (ushort)(pos % (ushort.MaxValue + 1)); + ushort y = (ushort)(pos / (ushort.MaxValue + 1)); + + HashSet components = new(); + ulong ps; + // rewrite above + if (x + 1 < _width && blob.ContainsKey((ps = AtomorphUtilities.XY2Pos((ushort)(x + 1), y)))) + components.Add(ps); + if (y + 1 < _height && blob.ContainsKey((ps = AtomorphUtilities.XY2Pos(x, (ushort)(y + 1))))) + components.Add(ps); + if (x > 0 && blob.ContainsKey((ps = AtomorphUtilities.XY2Pos((ushort)(x - 1), y)))) + components.Add(ps); + if (y > 0 && blob.ContainsKey((ps = AtomorphUtilities.XY2Pos(x, (ushort)(y - 1))))) + components.Add(ps); + + double r = 0.0, g = 0.0, b = 0.0, a = 0.0; + double w = components.Count; + foreach (var comp in components) + { + var c = blob[comp]; + r += (c.R / 255.0) / w; + g += (c.G / 255.0) / w; + b += (c.B / 255.0) / w; + a += (c.A / 255.0) / w; + } + + a *= alpha; + + blob_buf[pos] = ColorUtilities.CreateColor(r, g, b, a); + } + + foreach (var color in blob_buf) + { + blob[color.Key] = color.Value; + } + } + + foreach (var it in blob) + { + ulong pos = it.Key; + ushort x = (ushort)(pos % (ushort.MaxValue + 1)); + ushort y = (ushort)(pos / (ushort.MaxValue + 1)); + + ulong imgpos = (ulong)(y * _width + x); + image_buffer[imgpos] = it.Value; + } + } + + { + foreach (var cit in image_buffer) + { + ulong pos = cit.Key; + var c = cit.Value; + + if (KeepBackground) + { + var bgc = image[(int)pos].Color; + double bgr = bgc.R / 255.0; + double bgg = bgc.G / 255.0; + double bgb = bgc.B / 255.0; + double bga = bgc.A / 255.0; + + double r = c.R / 255.0; + double g = c.G / 255.0; + double b = c.B / 255.0; + double a = c.A / 255.0; + + r = a * r + (1.0 - a) * bgr; + g = a * g + (1.0 - a) * bgg; + b = a * b + (1.0 - a) * bgb; + a = bga + (1.0 - bga) * a; + + c = new Color((byte)Math.Round(r * 255.0), (byte)Math.Round(g * 255.0), (byte)Math.Round(b * 255.0), + (byte)Math.Round(a * 255.0)); + } + + var px = image[(int)pos]; + px.Color = c; + image[(int)pos] = px; + } + } + } + + private void StepFluid(ulong frameKey, double t, double time) + { + // t is for current transition between 2 images, time is overall time across all key frames. + ulong iptc = 0; + ulong particle_count = _fluid.ParticleCount; + var particles = _fluid.Particles; + + foreach (var cit in _chains) + { + ulong chain_key = cit.Key; + ulong w = cit.Value.Width; + ulong h = cit.Value.Height; + var points = cit.Value.Points; + + ulong y = _frames[frameKey].Index; + ulong y_next = (y + 1) % h; + + var next_frame_key = _frames.Keys.FirstOrDefault(k => k > frameKey); + if (next_frame_key == 0) next_frame_key = _frames.Keys.FirstOrDefault(); + + var blob_before = FindBlobByGroup(frameKey, chain_key); + var blob_after = FindBlobByGroup(next_frame_key, chain_key); + + double previous_surface = blob_before.Surface.Count; + double next_surface = blob_after.Surface.Count; + double current_surface = Math.Round((1.0 - t) * previous_surface + t * next_surface); + + ulong active_count = 0; + ulong active_limit = (ulong)current_surface; + + { + Dictionary sources = new(); // pt1 has fluid, pt2 maybe not + Dictionary destinations = new(); // pt2 has fluid, pt1 maybe not + Dictionary> particles_by_destination = new(); + Dictionary> particles_by_source = new(); + + List free_particles = []; + List update_particles = []; + + for (ulong x = 0; x < w && iptc < particle_count; ++x) + { + var pt1 = points[x][y]; + var pt2 = points[x][y_next]; + + { + // Map this pixel as a possible destination. + // The vector it holds contains indexes for + // detailed lookups about this destination. + ulong destination_pos = AtomorphUtilities.XY2Pos(pt2.X, pt2.Y); + if (AtomorphUtilities.PointHasFluid(pt2)) + { + destinations[destination_pos] = x; + } + + // Map this pixel as a possible source. + ulong source_pos = AtomorphUtilities.XY2Pos(pt1.X, pt1.Y); + if (AtomorphUtilities.PointHasFluid(pt1)) + { + sources[source_pos] = x; + } + } + + { + var p = particles[(int)iptc++]; + if (p.Active && p.FrameKey == frameKey) + { + // Map this particle as an existing particle. + active_count++; + particles_by_destination[p.DestinationPos].Add(p); + particles_by_source[p.SourcePos].Add(p); + update_particles.Add(p); + } + else + { + p.Active = false; + free_particles.Add(p); + } + } + } + + if (active_count < active_limit) + { + ulong to_create = active_limit - active_count; + // Add new particles. + + while (to_create > 0) + { + if (!free_particles.Any()) + throw new Exception("No free particles available to create new ones."); + var p = free_particles.Last(); + free_particles.RemoveAt(free_particles.Count - 1); + update_particles.Add(p); + p.Clear(); + p.FrameKey = frameKey; + + { + bool source_found = false; + List source_candidates = []; + + // First see if any of the source positions is still unused, + // it is the highest priority to have these filled. + foreach (var it in sources) + { + ulong pos = it.Key; + + if (particles_by_source.TryGetValue(pos, out var prt) && prt.Any()) + { + // This source is already taken. + continue; + } + // Free source was found, take it. + source_candidates.Add(pos); + } + + if (source_candidates.Any()) + { + ulong pos = source_candidates[_random.Next(0, source_candidates.Count - 1)]; + if (!sources.TryGetValue(pos, out var x)) + { + throw new Exception("Source position not found in sources map."); + } + + p.SourcePos = pos; + particles_by_source[pos].Add(p); + source_found = true; + + { + // This source was unoccupied, take its default destination + // even if it leads to a place without HAS_FLUID flag and thus this + // particle must be destroyed sooner or later during this morph. + + var pt2 = points[x][y_next]; + ulong destination_pos = AtomorphUtilities.XY2Pos(pt2.X, pt2.Y); + p.DestinationPos = destination_pos; + particles_by_destination[destination_pos].Add(p); + } + } + + if (!source_found) + { + // All sources are already occupied, this new particle must now + // share the source with some other particle, but it will still + // must get an unused destination. Search for such destination. + var destination_found = false; + foreach (var it in destinations) + { + ulong pos = it.Key; + ulong x = it.Value; + + if (particles_by_destination.TryGetValue(pos, out var prt) && prt.Any()) + { + // This destination is already taken. + continue; + } + + // Free destination was found, take it. + p.DestinationPos = pos; + particles_by_destination[pos].Add(p); + destination_found = true; + + { + // Destination was found but all the sources were already + // occupied. Now see the pt1 of this destination even if + // it does not have HAS_FLUID flag. + + var pt1 = points[x][y]; + ulong source_pos = AtomorphUtilities.XY2Pos(pt1.X, pt1.Y); + p.SourcePos = source_pos; + particles_by_source[source_pos].Add(p); + source_found = true; + } + + break; + } + } + } + + { + ulong pos = p.SourcePos; + + // Find a suitable starting position for this particle. + if (particles_by_source.TryGetValue(pos, out var prt) && prt.Any()) + { + // Another particle exists with the same source, + // copy its location for seamless creation. + var parent = particles_by_source[pos][_random.Next(0, prt.Count - 2)]; + + p.CopyFrom(parent); + p.Mature = parent.Mature; + p.Strength = parent.Strength; + + p.X = Math.Min(p.X + _random.NextDouble(), _width * sparseness - 10.0); + p.Y = Math.Min(p.Y + _random.NextDouble(), _height * sparseness - 10.0); + + p.SourceOwner = false; + } + else + { + // No other particle currently exists with the + // same source location. Copy the attractor's + // current position for the initial setup of this + // new particle. + + p.Mature = false; + p.SourceOwner = true; + + UpdateParticle(p, blob_before, blob_after, points, sources, destinations, t, y, y_next, + frameKey, next_frame_key, chain_key, time); + } + } + p.Active = true; + to_create--; + } + } + else if (active_count > active_limit) + { + ulong to_delete = active_count - active_limit; + // Delete particles. + update_particles.RandomShuffle(_random); + while (to_delete > 0) + { + var p = update_particles.Last(); + + p.Active = false; + update_particles.RemoveAt(update_particles.Count - 1); + + to_delete--; + } + } + + { + // Particles either created or deleted by now, update their positions. + ulong usz = (ulong)update_particles.Count; + for (ulong i = 0; i < usz; ++i) + { + var p = update_particles[(int)i]; + if (!p.Active) continue; + + UpdateParticle(p, blob_before, blob_after, points, sources, destinations, t, y, y_next, + frameKey, next_frame_key, chain_key, time); + } + } + } + } + + double freedom = Math.Sqrt(_width * _width + _height * _height) * (double)(sparseness) / 4.0; + double freedom_radius = freedom * (1.0 - t); + for (ulong step = 0; step < _fluidSteps; ++step) + _fluid.Step(_fluidSteps - (step + 1), freedom_radius, t); + } + + private void UpdateParticle(Particle p, Blob? blobBefore, Blob? blobAfter, Point[][] points, + Dictionary sources, Dictionary destinations, double t, ulong y, ulong yNext, + ulong frameKey, ulong nextFrameKey, ulong chainKey, double time) + { + double previous_surface = blobBefore.Surface.Count; + double next_surface = blobAfter.Surface.Count; + + var src_pos = p.SourcePos; + var dst_pos = p.DestinationPos; + var src_x = sources[src_pos]; + var dst_x = destinations[dst_pos]; + + // If area is growing then gain the real source x from the destination. + if (next_surface > previous_surface) + { + src_x = destinations[dst_pos]; + } + + { + var pt1 = points[src_x][y]; + var pt2 = points[dst_x][yNext]; + + Pixel px1, px2; + + if (pt1.PointHasPixel() && !pt2.PointHasPixel()) + { + px1 = GetPixel(frameKey, AtomorphUtilities.XY2Pos(pt1.X, pt1.Y)); + px2 = px1; + px2.X = pt2.X; + px2.Y = pt2.Y; + if (next_surface > 0.0) + px2.Color = new Color(px2.Color.R, px2.Color.G, px2.Color.B, 0); + } + else if (AtomorphUtilities.PointHasPixel(pt2) && !AtomorphUtilities.PointHasPixel(pt1)) + { + px2 = GetPixel(nextFrameKey, AtomorphUtilities.XY2Pos(pt2.X, pt2.Y)); + px1 = px2; + px1.X = pt1.X; + px1.Y = pt1.Y; + if (previous_surface > 0.0) + px1.Color = new Color(px1.Color.R, px1.Color.G, px1.Color.B, 0); + } + else + { + px1 = GetPixel(frameKey, AtomorphUtilities.XY2Pos(pt1.X, pt1.Y)); + px2 = GetPixel(nextFrameKey, AtomorphUtilities.XY2Pos(pt2.X, pt2.Y)); + } + + Color c; + + if (Fading == InterpolationMethod.Perlin) + { + double f = 8.0; // Frequency + int octaves = 8; // Octaves + double bbox_w = _bBoxX2 - _bBoxX1 + 1.0; + double bbox_h = _bBoxY2 - _bBoxY1 + 1.0; + double perlin_x = (((pt1.X - _bBoxX1) * (byte.MaxValue + 1) + pt1.XFract) / + (double)(bbox_w * (byte.MaxValue + 1))) * f; + double perlin_y = (((pt1.Y - _bBoxY1) * (byte.MaxValue + 1) + pt1.YFract) / + (double)(bbox_h * (byte.MaxValue + 1))) * f; + double lag = _lagMap.OctaveNoise(perlin_x, perlin_y, octaves) * 0.5 + 0.5; + double slope = _slopeMap.OctaveNoise(perlin_x, perlin_y, 8) * 0.5 + 0.5; + + c = Interpolate(px1.Color, px2.Color, lag, slope, 1.0 - t); + } + else if (Fading == InterpolationMethod.Cosine) c = Interpolate(px1.Color, px2.Color, 0.5, 0.5, 1.0 - t); + else c = Interpolate(px1.Color, px2.Color, 1.0 - t); + + var pt = pt1; + + if (Motion == InterpolationMethod.Linear) pt = Interpolate(pt1, pt2, 1.0 - t); + else if (Motion == InterpolationMethod.Spline && _chains[chainKey].Splines is not null) + { + var v = _chains[chainKey].Splines![src_x].GetInterpolatedSplinePoint(time); + double fract, integ; + fract = PortUtilities.ModF(v.X, out integ); + pt.X = (ushort)integ; + pt.XFract = (byte)Math.Round(fract * byte.MaxValue); + fract = PortUtilities.ModF(v.Y, out integ); + pt.Y = (ushort)integ; + pt.YFract = (byte)Math.Round(fract * byte.MaxValue); + } + + AtomorphUtilities.Point2XY(pt, out var ptx, out var pty); + + p.GravityX = Math.Min(Math.Max((ptx * sparseness) + 10.0, 1.0), _width * sparseness + 10.0); + p.GravityY = Math.Min(Math.Max((pty * sparseness) + 10.0, 1.0), _height * sparseness + 10.0); + + p.R = c.R / 255.0; + p.G = c.G / 255.0; + p.B = c.B / 255.0; + p.A = c.A / 255.0; + + if (ShowBlobs == ShowBlobs.Distinct) + { + var rng = new Random((int)chainKey); + p.R = rng.NextDouble(); + p.G = rng.NextDouble(); + p.B = rng.NextDouble(); + p.A = 1.0; + } + else if (ShowBlobs == ShowBlobs.Average) + { + p.R = blobBefore.R; + p.G = blobBefore.G; + p.B = blobBefore.B; + p.A = blobBefore.A; + } + + p.r = t * p.R + (1.0 - t) * p.r; + p.g = t * p.G + (1.0 - t) * p.g; + p.b = t * p.B + (1.0 - t) * p.b; + p.a = t * p.A + (1.0 - t) * p.a; + + if (!p.Mature) + { + if (p.SourceOwner) + { + p.X = p.GravityX; + p.Y = p.GravityY; + + // These lines should only be called + // for a newly created particle that was + // first to occupy its source location: + p.r = p.R; + p.g = p.G; + p.b = p.B; + p.a = p.A; + // Otherwise wrongly coloured single particles + // start appearing during the morph when new + // particles are created. + } + + if (previous_surface == 0.0) p.Strength = 0.1; + else p.Strength = 1.0; + + p.FreedomR = 1.0; + } + } + } + + /// + public void Dispose() + { + Clear(); + _worker?.Dispose(); + } +} \ No newline at end of file diff --git a/Atomorph.NET/MorphState.cs b/Atomorph.NET/MorphState.cs new file mode 100644 index 0000000..b5e1aec --- /dev/null +++ b/Atomorph.NET/MorphState.cs @@ -0,0 +1,10 @@ +namespace Atomorph; + +public enum MorphState +{ + BlobDetection, + BlobUnification, + BlobMatching, + AtomMorphing, + Done, +} \ No newline at end of file diff --git a/Atomorph.NET/Perlin/PerlinNoise.cs b/Atomorph.NET/Perlin/PerlinNoise.cs new file mode 100644 index 0000000..d2bdf43 --- /dev/null +++ b/Atomorph.NET/Perlin/PerlinNoise.cs @@ -0,0 +1,120 @@ +using System; +using System.Runtime.CompilerServices; +using Pcg; + +namespace Atomorph.Perlin; + +public class PerlinNoise +{ + private int[] _p = new int[512]; + + public PerlinNoise(uint seed = 1) + { + var rng = seed == 0 ? new PcgRandom() : new PcgRandom((int)seed); + // p[0]..p[255] contains all numbers in [0..255] in random order + for (var i = 0; i < 256; i++) + { + _p[i] = i; + } + for (var i = 0; i < 256; i++) + { + var j = rng.Next(0, 256); + (_p[i], _p[j]) = (_p[j], _p[i]); + } + // p[256]...p[511] is a copy of p[0] + for (var i = 0; i < 256; i++) + { + _p[i + 256] = _p[i]; + } + } + + public double Noise(double x) => Noise(x, 0.0); + public double Noise(double x, double y) => Noise(x, y, 0.0); + + public double Noise(double x, double y, double z) + { + var xInt = (int)Math.Floor(x) & 255; + var yInt = (int)Math.Floor(y) & 255; + var zInt = (int)Math.Floor(z) & 255; + + x -= Math.Floor(x); + y -= Math.Floor(y); + z -= Math.Floor(z); + + var u = Fade(x); + var v = Fade(y); + var w = Fade(z); + + var a = _p[xInt] + yInt; + var aa = _p[a] + zInt; + var ab = _p[a + 1] + zInt; + + var b = _p[xInt + 1] + yInt; + var ba = _p[b] + zInt; + var bb = _p[b + 1] + zInt; + + return Lerp(w, + Lerp(v, Lerp(u, Grad(_p[aa], x, y, z), Grad(_p[ba], x - 1, y, z)), + Lerp(u, Grad(_p[ab], x, y - 1, z), Grad(_p[bb], x - 1, y - 1, z))), + Lerp(v, Lerp(u, Grad(_p[aa + 1], x, y, z - 1), Grad(_p[ba + 1], x - 1, y, z - 1)), + Lerp(u, Grad(_p[ab + 1], x, y - 1, z - 1), Grad(_p[bb + 1], x - 1, y - 1, z - 1)))); + } + + public double OctaveNoise(double x, int octaves) + { + var result = 0.0; + var amp = 1.0; + for (var i = 0; i < octaves; i++) + { + result += Noise(x) * amp; + x *= 2.0; + amp *= 0.5; + } + return result; + } + + public double OctaveNoise(double x, double y, int octaves) + { + var result = 0.0; + var amp = 1.0; + + for (var i = 0; i < octaves; ++i) + { + result += Noise(x, y) * amp; + x *= 2.0; + y *= 2.0; + amp *= 0.5; + } + + return result; + } + + public double OctaveNoise(double x, double y, double z, int octaves) + { + var result = 0.0; + var amp = 1.0; + + for (var i = 0; i < octaves; ++i) + { + result += Noise(x, y, z) * amp; + x *= 2.0; + y *= 2.0; + z *= 2.0; + amp *= 0.5; + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private double Fade(double t) => t * t * t * (t * (t * 6 - 15) + 10); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private double Lerp(double a, double b, double t) => a + t * (b - a); + + private double Grad(int hash, double x, double y, double z) + { + var h = hash & 15; + double u = h < 8 ? x : y, v = h < 4 ? y : h is 12 or 14 ? x : z; + return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v); + } +} \ No newline at end of file diff --git a/Atomorph.NET/PointFlags.cs b/Atomorph.NET/PointFlags.cs new file mode 100644 index 0000000..33182a1 --- /dev/null +++ b/Atomorph.NET/PointFlags.cs @@ -0,0 +1,11 @@ +using System; + +namespace Atomorph; + +[Flags] +public enum PointFlags : byte +{ + None = 0, + HasPixel = 1 << 0, // 1 + HasFluid = 1 << 1, // 2 +} \ No newline at end of file diff --git a/Atomorph.NET/ShowBlobs.cs b/Atomorph.NET/ShowBlobs.cs new file mode 100644 index 0000000..05fb775 --- /dev/null +++ b/Atomorph.NET/ShowBlobs.cs @@ -0,0 +1,8 @@ +namespace Atomorph; + +public enum ShowBlobs +{ + Texture, + Average, + Distinct, +} \ No newline at end of file diff --git a/Atomorph.NET/Utilities/IOrderedDictionary.cs b/Atomorph.NET/Utilities/IOrderedDictionary.cs new file mode 100644 index 0000000..319443f --- /dev/null +++ b/Atomorph.NET/Utilities/IOrderedDictionary.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; + +namespace Atomorph.Utilities; + +/// +/// Represents a generic collection of key/value pairs that are ordered independently of the key and value. +/// +/// The type of the keys in the dictionary +/// The type of the values in the dictionary +public interface IOrderedDictionary : IOrderedDictionary, IDictionary +{ + /// + /// Adds an entry with the specified key and value into the IOrderedDictionary<TKey,TValue> collection with the lowest available index. + /// + /// The key of the entry to add. + /// The value of the entry to add. + /// The index of the newly added entry + /// + /// You can also use the property to add new elements by setting the value of a key that does not exist in the IOrderedDictionary<TKey,TValue> collection; however, if the specified key already exists in the IOrderedDictionary<TKey,TValue>, setting the property overwrites the old value. In contrast, the method does not modify existing elements. + /// An element with the same key already exists in the IOrderedDictionary<TKey,TValue> + /// The IOrderedDictionary<TKey,TValue> is read-only.
+ /// -or-
+ /// The IOrderedDictionary<TKey,TValue> has a fized size.
+ new int Add(TKey key, TValue value); + + /// + /// Inserts a new entry into the IOrderedDictionary<TKey,TValue> collection with the specified key and value at the specified index. + /// + /// The zero-based index at which the element should be inserted. + /// The key of the entry to add. + /// The value of the entry to add. The value can be if the type of the values in the dictionary is a reference type. + /// is less than 0.
+ /// -or-
+ /// is greater than .
+ /// An element with the same key already exists in the IOrderedDictionary<TKey,TValue>. + /// The IOrderedDictionary<TKey,TValue> is read-only.
+ /// -or-
+ /// The IOrderedDictionary<TKey,TValue> has a fized size.
+ void Insert(int index, TKey key, TValue value); + + /// + /// Gets or sets the value at the specified index. + /// + /// The zero-based index of the value to get or set. + /// The value of the item at the specified index. + /// is less than 0.
+ /// -or-
+ /// is equal to or greater than .
+ new TValue this[int index] + { + get; + set; + } +} \ No newline at end of file diff --git a/Atomorph.NET/Utilities/OrderedDictionary.cs b/Atomorph.NET/Utilities/OrderedDictionary.cs new file mode 100644 index 0000000..90f6cc1 --- /dev/null +++ b/Atomorph.NET/Utilities/OrderedDictionary.cs @@ -0,0 +1,641 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; + +namespace Atomorph.Utilities; + +/// +/// Represents a generic collection of key/value pairs that are ordered independently of the key and value. +/// +/// The type of the keys in the dictionary +/// The type of the values in the dictionary +internal class OrderedDictionary : IOrderedDictionary +{ + private const int DefaultInitialCapacity = 0; + + private static readonly string _keyTypeName = typeof(TKey).FullName; + private static readonly string _valueTypeName = typeof(TValue).FullName; + private static readonly bool _valueTypeIsReferenceType = !typeof(ValueType).IsAssignableFrom(typeof(TValue)); + + private Dictionary _dictionary; + private List> _list; + private IEqualityComparer _comparer; + private object _syncRoot; + private int _initialCapacity; + + /// + /// Initializes a new instance of the OrderedDictionary<TKey,TValue> class. + /// + public OrderedDictionary() + : this(DefaultInitialCapacity, null) + { + } + + /// + /// Initializes a new instance of the OrderedDictionary<TKey,TValue> class using the specified initial capacity. + /// + /// The initial number of elements that the OrderedDictionary<TKey,TValue> can contain. + /// is less than 0 + public OrderedDictionary(int capacity) + : this(capacity, null) + { + } + + /// + /// Initializes a new instance of the OrderedDictionary<TKey,TValue> class using the specified comparer. + /// + /// The IEqualityComparer<TKey> to use when comparing keys, or to use the default EqualityComparer<TKey> for the type of the key. + public OrderedDictionary(IEqualityComparer comparer) + : this(DefaultInitialCapacity, comparer) + { + } + + /// + /// Initializes a new instance of the OrderedDictionary<TKey,TValue> class using the specified initial capacity and comparer. + /// + /// The initial number of elements that the OrderedDictionary<TKey,TValue> collection can contain. + /// The IEqualityComparer<TKey> to use when comparing keys, or to use the default EqualityComparer<TKey> for the type of the key. + /// is less than 0 + public OrderedDictionary(int capacity, IEqualityComparer comparer) + { + if(0 > capacity) + throw new ArgumentOutOfRangeException("capacity", "'capacity' must be non-negative"); + + _initialCapacity = capacity; + _comparer = comparer; + } + + /// + /// Converts the object passed as a key to the key type of the dictionary + /// + /// The key object to check + /// The key object, cast as the key type of the dictionary + /// is . + /// The key type of the OrderedDictionary<TKey,TValue> is not in the inheritance hierarchy of . + private static TKey ConvertToKeyType(object keyObject) + { + if(null == keyObject) + { + throw new ArgumentNullException("key"); + } + else + { + if(keyObject is TKey) + return (TKey)keyObject; + } + throw new ArgumentException("'key' must be of type " + _keyTypeName, "key"); + } + + /// + /// Converts the object passed as a value to the value type of the dictionary + /// + /// The object to convert to the value type of the dictionary + /// The value object, converted to the value type of the dictionary + /// is , and the value type of the OrderedDictionary<TKey,TValue> is a value type. + /// The value type of the OrderedDictionary<TKey,TValue> is not in the inheritance hierarchy of . + private static TValue ConvertToValueType(object value) + { + if(null == value) + { + if(_valueTypeIsReferenceType) + return default(TValue); + else + throw new ArgumentNullException("value"); + } + else + { + if(value is TValue) + return (TValue)value; + } + throw new ArgumentException("'value' must be of type " + _valueTypeName, "value"); + } + + /// + /// Gets the dictionary object that stores the keys and values + /// + /// The dictionary object that stores the keys and values for the OrderedDictionary<TKey,TValue> + /// Accessing this property will create the dictionary object if necessary + private Dictionary Dictionary + { + get + { + if(null == _dictionary) + { + _dictionary = new Dictionary(_initialCapacity, _comparer); + } + return _dictionary; + } + } + + /// + /// Gets the list object that stores the key/value pairs. + /// + /// The list object that stores the key/value pairs for the OrderedDictionary<TKey,TValue> + /// Accessing this property will create the list object if necessary. + private List> List + { + get + { + if(null == List) + { + _list = new List>(_initialCapacity); + } + return _list; + } + } + + IDictionaryEnumerator IOrderedDictionary.GetEnumerator() + { + return Dictionary.GetEnumerator(); + } + + IDictionaryEnumerator IDictionary.GetEnumerator() + { + return Dictionary.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return List.GetEnumerator(); + } + + IEnumerator> IEnumerable>.GetEnumerator() + { + return List.GetEnumerator(); + } + + /// + /// Inserts a new entry into the OrderedDictionary<TKey,TValue> collection with the specified key and value at the specified index. + /// + /// The zero-based index at which the element should be inserted. + /// The key of the entry to add. + /// The value of the entry to add. The value can be if the type of the values in the dictionary is a reference type. + /// is less than 0.
+ /// -or-
+ /// is greater than .
+ /// is . + /// An element with the same key already exists in the OrderedDictionary<TKey,TValue>. + public void Insert(int index, TKey key, TValue value) + { + if(index > Count || index < 0) + throw new ArgumentOutOfRangeException("index"); + + Dictionary.Add(key, value); + List.Insert(index, new KeyValuePair(key, value)); + } + + /// + /// Inserts a new entry into the OrderedDictionary<TKey,TValue> collection with the specified key and value at the specified index. + /// + /// The zero-based index at which the element should be inserted. + /// The key of the entry to add. + /// The value of the entry to add. The value can be if the type of the values in the dictionary is a reference type. + /// is less than 0.
+ /// -or-
+ /// is greater than .
+ /// is .
+ /// -or-
+ /// is , and the value type of the OrderedDictionary<TKey,TValue> is a value type.
+ /// The key type of the OrderedDictionary<TKey,TValue> is not in the inheritance hierarchy of .
+ /// -or-
+ /// The value type of the OrderedDictionary<TKey,TValue> is not in the inheritance hierarchy of .
+ /// -or-
+ /// An element with the same key already exists in the OrderedDictionary<TKey,TValue>.
+ void IOrderedDictionary.Insert(int index, object key, object value) + { + Insert(index, ConvertToKeyType(key), ConvertToValueType(value)); + } + + /// + /// Removes the entry at the specified index from the OrderedDictionary<TKey,TValue> collection. + /// + /// The zero-based index of the entry to remove. + /// is less than 0.
+ /// -or-
+ /// index is equal to or greater than .
+ public void RemoveAt(int index) + { + if(index >= Count || index < 0) + throw new ArgumentOutOfRangeException("index", "'index' must be non-negative and less than the size of the collection"); + + TKey key = List[index].Key; + + List.RemoveAt(index); + Dictionary.Remove(key); + } + + /// + /// Gets or sets the value at the specified index. + /// + /// The zero-based index of the value to get or set. + /// The value of the item at the specified index. + /// is less than 0.
+ /// -or-
+ /// index is equal to or greater than .
+ public TValue this[int index] + { + get + { + return List[index].Value; + } + + set + { + if(index >= Count || index < 0) + throw new ArgumentOutOfRangeException("index", "'index' must be non-negative and less than the size of the collection"); + + TKey key = List[index].Key; + + List[index] = new KeyValuePair(key, value); + Dictionary[key] = value; + } + } + + /// + /// Gets or sets the value at the specified index. + /// + /// The zero-based index of the value to get or set. + /// The value of the item at the specified index. + /// is less than 0.
+ /// -or-
+ /// index is equal to or greater than .
+ /// is a null reference, and the value type of the OrderedDictionary<TKey,TValue> is a value type. + /// The value type of the OrderedDictionary<TKey,TValue> is not in the inheritance hierarchy of . + object IOrderedDictionary.this[int index] + { + get + { + return this[index]; + } + + set + { + this[index] = ConvertToValueType(value); + } + } + + /// + /// Adds an entry with the specified key and value into the OrderedDictionary<TKey,TValue> collection with the lowest available index. + /// + /// The key of the entry to add. + /// The value of the entry to add. This value can be . + /// A key cannot be , but a value can be. + /// You can also use the property to add new elements by setting the value of a key that does not exist in the OrderedDictionary<TKey,TValue> collection; however, if the specified key already exists in the OrderedDictionary<TKey,TValue>, setting the property overwrites the old value. In contrast, the method does not modify existing elements. + /// is + /// An element with the same key already exists in the OrderedDictionary<TKey,TValue> + void IDictionary.Add(TKey key, TValue value) + { + Add(key, value); + } + + /// + /// Adds an entry with the specified key and value into the OrderedDictionary<TKey,TValue> collection with the lowest available index. + /// + /// The key of the entry to add. + /// The value of the entry to add. This value can be . + /// The index of the newly added entry + /// A key cannot be , but a value can be. + /// You can also use the property to add new elements by setting the value of a key that does not exist in the OrderedDictionary<TKey,TValue> collection; however, if the specified key already exists in the OrderedDictionary<TKey,TValue>, setting the property overwrites the old value. In contrast, the method does not modify existing elements. + /// is + /// An element with the same key already exists in the OrderedDictionary<TKey,TValue> + public int Add(TKey key, TValue value) + { + Dictionary.Add(key, value); + List.Add(new KeyValuePair(key, value)); + return Count - 1; + } + + /// + /// Adds an entry with the specified key and value into the OrderedDictionary<TKey,TValue> collection with the lowest available index. + /// + /// The key of the entry to add. + /// The value of the entry to add. This value can be . + /// is .
+ /// -or-
+ /// is , and the value type of the OrderedDictionary<TKey,TValue> is a value type.
+ /// The key type of the OrderedDictionary<TKey,TValue> is not in the inheritance hierarchy of .
+ /// -or-
+ /// The value type of the OrderedDictionary<TKey,TValue> is not in the inheritance hierarchy of .
+ void IDictionary.Add(object key, object value) + { + Add(ConvertToKeyType(key), ConvertToValueType(value)); + } + + /// + /// Removes all elements from the OrderedDictionary<TKey,TValue> collection. + /// + /// The capacity is not changed as a result of calling this method. + public void Clear() + { + Dictionary.Clear(); + List.Clear(); + } + + /// + /// Determines whether the OrderedDictionary<TKey,TValue> collection contains a specific key. + /// + /// The key to locate in the OrderedDictionary<TKey,TValue> collection. + /// if the OrderedDictionary<TKey,TValue> collection contains an element with the specified key; otherwise, . + /// is + public bool ContainsKey(TKey key) + { + return Dictionary.ContainsKey(key); + } + /// + /// Determines whether the OrderedDictionary<TKey,TValue> collection contains a specific key. + /// + /// The key to locate in the OrderedDictionary<TKey,TValue> collection. + /// if the OrderedDictionary<TKey,TValue> collection contains an element with the specified key; otherwise, . + /// is + /// The key type of the OrderedDictionary<TKey,TValue> is not in the inheritance hierarchy of . + bool IDictionary.Contains(object key) + { + return ContainsKey(ConvertToKeyType(key)); + } + + /// + /// Gets a value indicating whether the OrderedDictionary<TKey,TValue> has a fixed size. + /// + /// if the OrderedDictionary<TKey,TValue> has a fixed size; otherwise, . The default is . + bool IDictionary.IsFixedSize + { + get + { + return false; + } + } + + /// + /// Gets a value indicating whether the OrderedDictionary<TKey,TValue> collection is read-only. + /// + /// if the OrderedDictionary<TKey,TValue> is read-only; otherwise, . The default is . + /// + /// A collection that is read-only does not allow the addition, removal, or modification of elements after the collection is created. + /// A collection that is read-only is simply a collection with a wrapper that prevents modification of the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes. + /// + public bool IsReadOnly + { + get + { + return false; + } + } + + /// + /// Gets an object containing the keys in the OrderedDictionary<TKey,TValue>. + /// + /// An object containing the keys in the OrderedDictionary<TKey,TValue>. + /// The returned object is not a static copy; instead, the collection refers back to the keys in the original OrderedDictionary<TKey,TValue>. Therefore, changes to the OrderedDictionary<TKey,TValue> continue to be reflected in the key collection. + ICollection IDictionary.Keys + { + get + { + return (ICollection)Keys; + } + } + + /// + /// Returns the zero-based index of the specified key in the OrderedDictionary<TKey,TValue> + /// + /// The key to locate in the OrderedDictionary<TKey,TValue> + /// The zero-based index of , if is found in the OrderedDictionary<TKey,TValue>; otherwise, -1 + /// This method performs a linear search; therefore it has a cost of O(n) at worst. + public int IndexOfKey(TKey key) + { + if(null == key) + throw new ArgumentNullException("key"); + + for(int index = 0; index < List.Count; index++) + { + KeyValuePair entry = List[index]; + TKey next = entry.Key; + if(null != _comparer) + { + if(_comparer.Equals(next, key)) + { + return index; + } + } + else if(next.Equals(key)) + { + return index; + } + } + + return -1; + } + + /// + /// Removes the entry with the specified key from the OrderedDictionary<TKey,TValue> collection. + /// + /// The key of the entry to remove + /// if the key was found and the corresponding element was removed; otherwise, + public bool Remove(TKey key) + { + if(null == key) + throw new ArgumentNullException("key"); + + int index = IndexOfKey(key); + if(index >= 0) + { + if(Dictionary.Remove(key)) + { + List.RemoveAt(index); + return true; + } + } + return false; + } + + /// + /// Removes the entry with the specified key from the OrderedDictionary<TKey,TValue> collection. + /// + /// The key of the entry to remove + void IDictionary.Remove(object key) + { + Remove(ConvertToKeyType(key)); + } + + /// + /// Gets an object containing the values in the OrderedDictionary<TKey,TValue> collection. + /// + /// An object containing the values in the OrderedDictionary<TKey,TValue> collection. + /// The returned object is not a static copy; instead, the refers back to the values in the original OrderedDictionary<TKey,TValue> collection. Therefore, changes to the OrderedDictionary<TKey,TValue> continue to be reflected in the . + ICollection IDictionary.Values + { + get + { + return (ICollection)Values; + } + } + + /// + /// Gets or sets the value with the specified key. + /// + /// The key of the value to get or set. + /// The value associated with the specified key. If the specified key is not found, attempting to get it returns , and attempting to set it creates a new element using the specified key. + public TValue this[TKey key] + { + get + { + return Dictionary[key]; + } + set + { + if(Dictionary.ContainsKey(key)) + { + Dictionary[key] = value; + List[IndexOfKey(key)] = new KeyValuePair(key, value); + } + else + { + Add(key, value); + } + } + } + + /// + /// Gets or sets the value with the specified key. + /// + /// The key of the value to get or set. + /// The value associated with the specified key. If the specified key is not found, attempting to get it returns , and attempting to set it creates a new element using the specified key. + object IDictionary.this[object key] + { + get + { + return this[ConvertToKeyType(key)]; + } + set + { + this[ConvertToKeyType(key)] = ConvertToValueType(value); + } + } + + /// + /// Copies the elements of the OrderedDictionary<TKey,TValue> elements to a one-dimensional Array object at the specified index. + /// + /// The one-dimensional object that is the destination of the objects copied from the OrderedDictionary<TKey,TValue>. The must have zero-based indexing. + /// The zero-based index in at which copying begins. + /// The method preserves the order of the elements in the OrderedDictionary<TKey,TValue> + void ICollection.CopyTo(Array array, int index) + { + ((ICollection)List).CopyTo(array, index); + } + + /// + /// Gets the number of key/values pairs contained in the OrderedDictionary<TKey,TValue> collection. + /// + /// The number of key/value pairs contained in the OrderedDictionary<TKey,TValue> collection. + public int Count + { + get + { + return List.Count; + } + } + + /// + /// Gets a value indicating whether access to the OrderedDictionary<TKey,TValue> object is synchronized (thread-safe). + /// + /// This method always returns false. + bool ICollection.IsSynchronized + { + get + { + return false; + } + } + + /// + /// Gets an object that can be used to synchronize access to the OrderedDictionary<TKey,TValue> object. + /// + /// An object that can be used to synchronize access to the OrderedDictionary<TKey,TValue> object. + object ICollection.SyncRoot + { + get + { + if(this._syncRoot == null) + { + System.Threading.Interlocked.CompareExchange(ref this._syncRoot, new object(), null); + } + return this._syncRoot; + } + } + + /// + /// Gets an ICollection<TKey> object containing the keys in the OrderedDictionary<TKey,TValue>. + /// + /// An ICollection<TKey> object containing the keys in the OrderedDictionary<TKey,TValue>. + /// The returned ICollection<TKey> object is not a static copy; instead, the collection refers back to the keys in the original OrderedDictionary<TKey,TValue>. Therefore, changes to the OrderedDictionary<TKey,TValue> continue to be reflected in the key collection. + public ICollection Keys + { + get + { + return Dictionary.Keys; + } + } + + /// + /// Gets the value associated with the specified key. + /// + /// The key of the value to get. + /// When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of . This parameter can be passed uninitialized. + /// if the OrderedDictionary<TKey,TValue> contains an element with the specified key; otherwise, . + public bool TryGetValue(TKey key, out TValue value) + { + return Dictionary.TryGetValue(key, out value); + } + + /// + /// Gets an ICollection<TValue> object containing the values in the OrderedDictionary<TKey,TValue>. + /// + /// An ICollection<TValue> object containing the values in the OrderedDictionary<TKey,TValue>. + /// The returned ICollection<TKey> object is not a static copy; instead, the collection refers back to the values in the original OrderedDictionary<TKey,TValue>. Therefore, changes to the OrderedDictionary<TKey,TValue> continue to be reflected in the value collection. + public ICollection Values + { + get + { + return Dictionary.Values; + } + } + + /// + /// Adds the specified value to the OrderedDictionary<TKey,TValue> with the specified key. + /// + /// The KeyValuePair<TKey,TValue> structure representing the key and value to add to the OrderedDictionary<TKey,TValue>. + void ICollection>.Add(KeyValuePair item) + { + Add(item.Key, item.Value); + } + + /// + /// Determines whether the OrderedDictionary<TKey,TValue> contains a specific key and value. + /// + /// The KeyValuePair<TKey,TValue> structure to locate in the OrderedDictionary<TKey,TValue>. + /// if is found in the OrderedDictionary<TKey,TValue>; otherwise, . + bool ICollection>.Contains(KeyValuePair item) + { + return ((ICollection>)Dictionary).Contains(item); + } + + /// + /// Copies the elements of the OrderedDictionary<TKey,TValue> to an array of type , starting at the specified index. + /// + /// The one-dimensional array of type KeyValuePair<TKey,TValue> that is the destination of the KeyValuePair<TKey,TValue> elements copied from the OrderedDictionary<TKey,TValue>. The array must have zero-based indexing. + /// The zero-based index in at which copying begins. + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) + { + ((ICollection>)Dictionary).CopyTo(array, arrayIndex); + } + + /// + /// Removes a key and value from the dictionary. + /// + /// The KeyValuePair<TKey,TValue> structure representing the key and value to remove from the OrderedDictionary<TKey,TValue>. + /// if the key and value represented by is successfully found and removed; otherwise, . This method returns if is not found in the OrderedDictionary<TKey,TValue>. + bool ICollection>.Remove(KeyValuePair item) + { + return Remove(item.Key); + } +} \ No newline at end of file diff --git a/Atomorph.NET/Utilities/PortUtilities.cs b/Atomorph.NET/Utilities/PortUtilities.cs new file mode 100644 index 0000000..263729d --- /dev/null +++ b/Atomorph.NET/Utilities/PortUtilities.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using Pcg; + +namespace Atomorph; + +internal static class PortUtilities +{ + private static readonly PcgRandom Rng = new PcgRandom(); + + public static void RandomShuffle(this IList list, PcgRandom? rng = null) + { + rng ??= Rng; + for (var i = list.Count - 1; i > 0; i--) + { + var j = rng.Next(0, i + 1); + if (i != j) + { + (list[i], list[j]) = (list[j], list[i]); + } + } + } + + public static double ModF(this double value, out double integerPart) + { + integerPart = Math.Floor(value); + return value - integerPart; + } + + public static void AddToDictionaryList(this Dictionary> dictionary, TKey key, TValue value) + { + if (!dictionary.TryGetValue(key, out var list)) + { + list = new List(); + dictionary[key] = list; + } + list.Add(value); + } +} \ No newline at end of file diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..d713a3b --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,20 @@ + + + $([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)'))=./ + + + + enable + 12 + true + enable + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + \ No newline at end of file diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..c25d8d2 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,12 @@ + + + true + + + + + + + + + \ No newline at end of file