Skip to content

Instantly share code, notes, and snippets.

@JohnnyonFlame
Last active October 8, 2021 05:55
Show Gist options
  • Save JohnnyonFlame/926801fc26ebb4dad0d24b41634cfe7d to your computer and use it in GitHub Desktop.
Save JohnnyonFlame/926801fc26ebb4dad0d24b41634cfe7d to your computer and use it in GitHub Desktop.
A C# binpacker.
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
public class Program
{
public class Rect
{
public int X;
public int Y;
public int Width;
public int Height;
public int Right { get { return X + Width; } }
public int Down { get { return Y + Height; } }
public int Area { get { return Width * Height; } }
}
public class Split : Rect
{
public bool Invalidated;
public Split(int X, int Y, int Width, int Height)
{
this.X = X;
this.Y = Y;
this.Width = Width;
this.Height = Height;
this.Invalidated = false;
}
public bool containsRect(Rect rect)
{
return (rect.X >= this.X) && (rect.Y >= this.Y) && (this.Right >= rect.Right) && (this.Down >= rect.Down);
}
public bool overlapsRect(Rect rect)
{
return (((rect.X >= this.X) && (rect.X <= this.Right))
|| ((this.X >= rect.X) && (this.X <= rect.Right)))
&& (((rect.Y >= this.Y) && (rect.Y <= this.Down))
|| ((this.Y >= rect.Y) && (this.Y <= rect.Down)));
}
public bool fits(int Width, int Height)
{
return (this.Width >= Width) && (this.Height >= Height);
}
public IEnumerable<Split> splitNode(Rect rect)
{
// If the rect isn't contained or has been invalidated, create no new Splits and don't invalidate
if (!overlapsRect(rect) || Invalidated)
return new List<Split>();
this.Invalidated = true;
// Now split it in four
return new List<Split> {
new Split(this.X, this.Y, this.Width, rect.Y - this.Y), /* up */
new Split(this.X, this.Y, rect.X - this.X, this.Height), /* left */
new Split(this.X, rect.Down, this.Width, this.Down - rect.Down), /* down */
new Split(rect.Right, this.Y, this.Right - rect.Right, this.Height), /* right */
}.Where(item => item.Area > 0);
}
};
public class TextureAtlas
{
public int Size;
public int Padding;
public List<Split> Splits;
public List<Rect> Textures;
public TextureAtlas(int Size, int Padding)
{
this.Splits = new List<Split> { new Split(0, 0, Size, Size) };
this.Textures = new List<Rect>();
this.Size = Size;
this.Padding = Padding;
}
// Finds the best split to fit a rectangle based on a provided heuristic function
public Split findBestFit(int Width, int Height, Func<Split, float> heuristics)
{
var possibleNodes =
from item in Splits
where item.fits(Width, Height)
orderby heuristics(item) ascending
select item;
return possibleNodes.DefaultIfEmpty(null).First();
}
// Allocate space on this atlas
// returns the Rect containing said rectangle or null on failure
public Rect Allocate(int Width, int Height)
{
var pWidth = Width + 2 * this.Padding;
var pHeight = Height + 2 * this.Padding;
// Best Long Side fit.
var bestFit = findBestFit(pWidth, pHeight,
split => Math.Min(pWidth - split.Width, pHeight - split.Height)
);
if (bestFit == null)
return null;
Rect rect = new Rect()
{
X = bestFit.X,
Y = bestFit.Y,
Width = pWidth,
Height = pHeight
};
var newSplits = Splits
.AsParallel()
.Select(item => item.splitNode(rect))
.SelectMany(list => list.Distinct())
.ToList();
Splits = Enumerable.Concat(Splits.Where(item => item.Invalidated == false), newSplits).ToList();
foreach (var split1 in Splits)
{
foreach (var split2 in Splits)
{
if (split1 == split2)
continue;
if (split1.containsRect((Rect)split2))
split2.Invalidated = true;
}
}
// Remove all the redundant or free'd splits
Splits.RemoveAll(item => item.Invalidated);
var tex = new Rect()
{
X = bestFit.X + Padding,
Y = bestFit.Y + Padding,
Width = Width,
Height = Height
};
Textures.Add(tex);
return tex;
}
};
public static void Main()
{
var atlas = new TextureAtlas(512, 2);
var rects = new List<Rect>{
atlas.Allocate(32, 32),
atlas.Allocate(256, 32),
atlas.Allocate(32, 256),
atlas.Allocate(32, 32),
atlas.Allocate(32, 32),
atlas.Allocate(32, 100),
atlas.Allocate(32, 100)
};
int s = 0;
foreach (var split in atlas.Splits) {
System.Console.WriteLine($"split: {s++}: {split.X}, {split.Y}, {split.Width}, {split.Height}");
}
foreach (var rect in rects) {
System.Console.WriteLine($"tex: {rects.IndexOf(rect)}: {rect.X}, {rect.Y}, {rect.Width}, {rect.Height}");
}
}
}
import re
from PIL import Image, ImageDraw, ImageColor
img = Image.new("RGB", (512, 512), color="white")
# create rectangle image
img1 = ImageDraw.Draw(img)
parse = """
split: 0: 332, 0, 180, 512
split: 1: 0, 436, 512, 76
split: 2: 36, 140, 476, 372
split: 3: 72, 36, 440, 476
tex: 0: 2, 2, 32, 32
tex: 1: 38, 2, 256, 32
tex: 2: 2, 38, 32, 256
tex: 3: 298, 2, 32, 32
tex: 4: 2, 298, 32, 32
tex: 5: 2, 334, 32, 100
tex: 6: 38, 38, 32, 100
"""
def coord(r):
return [r[0], r[1], r[0] + r[2] - 1, r[1] + r[3] - 1]
col = [c for (c, _) in ImageColor.colormap.items()]
regex = re.compile(r"(\w+): (\d+): (\d+), (\d+), (\d+), (\d+)")
for l in parse.split('\n'):
m = regex.fullmatch(l)
if not m:
continue
rect = [int(i) for i in m.groups()[2:]]
rect = coord(rect)
col_id = int(m.group(2)) % len(col)
if m[1] == 'tex':
img1.rectangle(rect, fill=col[col_id])
else:
img1.rectangle(rect, outline="red")
img
@JohnnyonFlame
Copy link
Author

image

@JohnnyonFlame
Copy link
Author

This is licensed under MIT.

The MIT License (MIT)

Copyright © 2021 João Henrique

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment