SpritePacker/SpritePacker/SpritePacker.cs

296 lines
9.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Security.Cryptography;
using System.IO;
using System.Configuration;
using System.Drawing.Text;
using System.Drawing.Imaging;
using System.Text;
using System.Linq;
namespace SpritePacker
{
public class SpritePacker
{
/// <summary>
/// A list of all the sprites added to the sprite packer.
/// </summary>
private List<Sprite> sprites = new List<Sprite>();
/// <summary>
/// Whether debug information should be outputted to the console.
/// </summary>
/// <value><c>true</c> if verbose; <c>false</c> otherwise.</value>
public bool Verbose { get; private set; }
/// <summary>
/// Gets a list of the current sprites.
/// </summary>
public Sprite[] CurrentSprites
{
get {
return sprites.ToArray();
}
}
/// <summary>
/// Initializes a new SpritePacker.
/// </summary>
/// <param name="inVerbose">Whether to output debug information to the console.</param>
public SpritePacker(bool inVerbose = false)
{
Verbose = inVerbose;
}
/// <summary>
/// Adds a sprite to the sprite packer.
/// </summary>
/// <param name="sprite">Sprite.</param>
public void Add(Sprite sprite)
{
if(Verbose) Console.WriteLine("Adding {0}.", sprite);
sprites.Add(sprite);
}
public void Add(IEnumerable<Sprite> sprites)
{
foreach (Sprite sprite in sprites)
Add(sprite);
}
/// <summary>
/// Adds a sprite to the sprite packer.
/// </summary>
/// <param name="sprite">Whether a sprite was actually removed or not.</param>
public bool Remove(Sprite sprite)
{
return sprites.Remove(sprite);
}
/// <summary>
/// Clears the list of sprites added to the current sprite packer.
/// </summary>
public void Clear()
{
sprites.Clear();
}
/// <summary>
/// Packs all the added sprites in as small a area as possible.
/// Note that this operation may potentially be very computationally expensive.
/// </summary>
public void Arrange()
{
sortBySize();
List<Sprite> arrangedSprites = sprites.Where((Sprite spr) => spr.Placed).ToList();
List<Sprite> spritesToPack = sprites.Where((Sprite spr) => !spr.Placed).ToList();
foreach(Sprite cspr in spritesToPack)
{
if(Verbose) Console.WriteLine("Attempting to place {0}.", cspr);
Point scanLines = Point.Empty;
Point nextScanLines = new Point(int.MaxValue, int.MaxValue);
while(true)
{
if (!cspr.IntersectsWith(arrangedSprites))
break;
if(Verbose) Console.WriteLine("Scan lines: {0}", scanLines);
if(Verbose) Console.WriteLine("Scanning X...");
// Scan along the X axis
cspr.X = 0;
cspr.Y = scanLines.Y;
bool foundPosition = false;
while(cspr.X <= scanLines.X)
{
if(Verbose) Console.Write("Position: {0} ", cspr.X);
if (!cspr.IntersectsWith(arrangedSprites))
{
if(Verbose) Console.WriteLine("Found position on the X axis.");
foundPosition = true;
break;
}
// Get the edge furthest to the right
List<Sprite> problems = cspr.GetIntersectors(arrangedSprites);
Sprite rightProblem = problems[0];
foreach (Sprite probSpr in problems)
{
if (probSpr.Right > rightProblem.Right)
rightProblem = probSpr;
// If the current problem's bottom edge is less than the bottom of the next scan line,
// move the next scan line up a bit.
// Also make sure that the next scan line and the current scan line don't touch or cross.
if (probSpr.Bottom < nextScanLines.Y && probSpr.Bottom > scanLines.Y)
nextScanLines.Y = probSpr.Bottom; // NOTE: Add one here?
}
if(Verbose) Console.WriteLine("Found rightmost problem: {0}", rightProblem);
// Move up to the position furthest to the right
cspr.X = rightProblem.Right; // NOTE: Add one here?
}
if (!foundPosition)
{
if(Verbose) Console.WriteLine("Failed to find anything on the X axis. Scanning Y...");
// We didn't find anything along the x axis - let's scan the y axis next
cspr.X = scanLines.X;
cspr.Y = 0;
while (cspr.Y <= scanLines.Y)
{
if(Verbose) Console.Write("Position: {0} ", cspr.Y);
if (!cspr.IntersectsWith(arrangedSprites))
{
if(Verbose) Console.WriteLine("Found position on the Y axis.");
foundPosition = true;
break;
}
// Get the edge furthest downwards
List<Sprite> problems = cspr.GetIntersectors(arrangedSprites);
Sprite downProblem = problems[0];
foreach (Sprite probSpr in problems)
{
if (probSpr.Bottom > downProblem.Bottom)
downProblem = probSpr;
// If the current problem's right edge is further in than the current next scan line,
// move the next scan line up to meet it.
// Also make sure that the next scan line and the current scan line don't touch or cross.
if (probSpr.Right < nextScanLines.X && probSpr.Right > scanLines.X)
nextScanLines.X = probSpr.Right; // NOTE: Add one here?
}
if(Verbose) Console.WriteLine("Found downProblem {0}", downProblem);
// Move up to the position furthest downwards
cspr.Y = downProblem.Bottom; // NOTE: Add one here?
}
}
// If we found a new position, then we don't need to move the scan lines up and try again
if (foundPosition) {
cspr.Placed = true;
break;
}
if(Verbose) Console.WriteLine("Failed to find a position along the current scan lines.");
if(Verbose) Console.WriteLine("Next candidate scan lines: {0}", nextScanLines);
// Make sure that the next scan lines are sane
if (nextScanLines.X == int.MaxValue)
nextScanLines.X = scanLines.X;
if (nextScanLines.Y == int.MaxValue)
nextScanLines.Y = scanLines.Y;
if(Verbose) Console.WriteLine("Actual next scan lines: {0}", nextScanLines);
// If the next scan lines and the current scan lines are identical,
// then something is very wrong
if(nextScanLines.Equals(scanLines))
throw new Exception("Failed to find the next set of lines to scan!");
// Move the scan lines up to the next nearest ones we've found
scanLines = nextScanLines;
nextScanLines = new Point(int.MaxValue, int.MaxValue);
}
arrangedSprites.Add(cspr);
if(Verbose) Console.WriteLine("Finished positioning {0}.", cspr);
}
// We don't need to copy the list of arranged sprites across to the main list here
// because Sprite is a class and classes are passed by _reference_.
}
/// <summary>
/// Generates an image that contains all the currently added sprites.
/// You probably want to call Arrage() before calling this method.
/// Returns <c>null</c> if you haven't added any sprites to the SpritePacker yet.
/// </summary>
/// <returns>The generated image.</returns>
public Bitmap GenerateImage()
{
// Calculate the size of the image we are about to output
Point imageSize = new Point(0, 0);
foreach(Sprite spr in sprites)
{
if (spr.Bottom > imageSize.Y)
imageSize.Y = spr.Bottom;
if (spr.Right > imageSize.X)
imageSize.X = spr.Right;
}
if (imageSize.IsEmpty)
return null;
Bitmap finalImage = new Bitmap(imageSize.X, imageSize.Y, PixelFormat.Format32bppArgb);
finalImage.MakeTransparent();
using (Graphics context = Graphics.FromImage(finalImage))
{
foreach(Sprite spr in sprites)
{
context.DrawImage(spr.Image, spr.Location);
}
}
return finalImage;
}
/// <summary>
/// Output the packed sprite as an image to the specified filename.
/// You probably want to call Arrage() before calling this method.
/// </summary>
/// <param name="outputFilename">The filename to save the generated image to.</param>
public void Output(string outputFilename)
{
using (Bitmap finalImage = GenerateImage())
{
finalImage.Save(outputFilename);
}
}
/// <summary>
/// Gets a the details of the currently added sprites as a string of CSV.
/// </summary>
/// <returns>Details of the current sprites as a string of CSV.</returns>
/// <param name="header">Whether to include a header in the generated CSV.</param>
public string GetSpritePositionsCSV(bool header = true)
{
StringWriter result = new StringWriter();
if (header)
result.WriteLine("index,filename,x,y,width,height");
int i = 0;
foreach(Sprite spr in sprites)
{
result.WriteLine("{0},{1},{2},{3},{4},{5}", new object[] { i, spr.Filename, spr.X, spr.Y, spr.Width, spr.Height });
i++;
}
return result.ToString();
}
/// <summary>
/// Sorts the sprites by size.
/// </summary>
private void sortBySize()
{
sprites.Sort((a, b) => -a.AreaSize.CompareTo(b.AreaSize));
}
/// <summary>
/// Returns a string that represents the current sprite packer.
/// </summary>
/// <returns>A string that represents the current sprite packer.</returns>
public override string ToString()
{
string result = string.Format("SpritePacker:") + Environment.NewLine;
foreach (Sprite spr in sprites)
result += string.Format("\t{0}\n", spr);
return result;
}
}
}