This repository was archived by the owner on Sep 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathPacker.cs
More file actions
432 lines (367 loc) · 13.9 KB
/
Copy pathPacker.cs
File metadata and controls
432 lines (367 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
using System;
using System.Collections.Generic;
using System.IO;
namespace Foster.Framework;
/// <summary>
/// The Packer takes source image data and packs them into large texture pages that can then be used for Atlases
/// This is useful for sprite fonts, sprite sheets, etc.
/// </summary>
public class Packer
{
/// <summary>
/// A single packed Entry
/// </summary>
public class Entry
{
/// <summary>
/// The Name of the Entry
/// </summary>
public readonly string Name;
/// <summary>
/// The corresponding image page of the Entry
/// </summary>
public readonly int Page;
/// <summary>
/// The Source Rectangle
/// </summary>
public readonly RectInt Source;
/// <summary>
/// The Frame Rectangle. This is the size of the image before it was packed
/// </summary>
public readonly RectInt Frame;
public Entry(string name, int page, RectInt source, RectInt frame)
{
Name = name;
Page = page;
Source = source;
Frame = frame;
}
}
/// <summary>
/// Stores the Packed result of the Packer
/// </summary>
public class Output
{
public readonly List<Bitmap> Pages = new List<Bitmap>();
public readonly Dictionary<string, Entry> Entries = new Dictionary<string, Entry>();
}
/// <summary>
/// The Packed Output
/// This is null if the Packer has not yet been packed
/// </summary>
public Output Packed { get; private set; } = new Output();
/// <summary>
/// Whether the Packer has unpacked source data
/// </summary>
public bool HasUnpackedData { get; private set; }
/// <summary>
/// Whether to trim transparency from the source images
/// </summary>
public bool Trim = true;
/// <summary>
/// Maximum Texture Size. If the packed data is too large it will be split into multiple pages
/// </summary>
public int MaxSize = 8192;
/// <summary>
/// Image Padding
/// </summary>
public int Padding = 1;
/// <summary>
/// Power of Two
/// </summary>
public bool PowerOfTwo = false;
/// <summary>
/// This will check each image to see if it's a duplicate of an already packed image.
/// It will still add the entry, but not the duplicate image data.
/// </summary>
public bool CombineDuplicates = false;
/// <summary>
/// The total number of source images
/// </summary>
public int SourceImageCount => sources.Count;
private class Source
{
public string Name;
public RectInt Packed;
public RectInt Frame;
public Color[]? Buffer;
public Source? DuplicateOf;
public bool Empty => Packed.Width <= 0 || Packed.Height <= 0;
public Source(string name)
{
Name = name;
}
}
private readonly List<Source> sources = new List<Source>();
private readonly Dictionary<int, Source> duplicateLookup = new Dictionary<int, Source>();
public void AddBitmap(string name, Bitmap bitmap)
{
if (bitmap != null)
AddPixels(name, bitmap.Width, bitmap.Height, new ReadOnlySpan<Color>(bitmap.Pixels));
}
public void AddFile(string name, string path)
{
using var stream = File.OpenRead(path);
AddBitmap(name, new Bitmap(stream));
}
public void AddPixels(string name, int width, int height, ReadOnlySpan<Color> pixels)
{
HasUnpackedData = true;
var source = new Source(name);
int top = 0, left = 0, right = width, bottom = height;
// trim
if (Trim)
{
// TOP:
for (int y = 0; y < height; y++)
for (int x = 0, s = y * width; x < width; x++, s++)
if (pixels[s].A > 0)
{
top = y;
goto LEFT;
}
LEFT:
for (int x = 0; x < width; x++)
for (int y = top, s = x + y * width; y < height; y++, s += width)
if (pixels[s].A > 0)
{
left = x;
goto RIGHT;
}
RIGHT:
for (int x = width - 1; x >= left; x--)
for (int y = top, s = x + y * width; y < height; y++, s += width)
if (pixels[s].A > 0)
{
right = x + 1;
goto BOTTOM;
}
BOTTOM:
for (int y = height - 1; y >= top; y--)
for (int x = left, s = x + y * width; x < right; x++, s++)
if (pixels[s].A > 0)
{
bottom = y + 1;
goto END;
}
END:;
}
// determine sizes
// there's a chance this image was empty in which case we have no width / height
if (left <= right && top <= bottom)
{
var isDuplicate = false;
if (CombineDuplicates)
{
var hash = 0;
for (int x = left; x < right; x++)
for (int y = top; y < bottom; y++)
hash = ((hash << 5) + hash) + (int)pixels[x + y * width].ABGR;
if (duplicateLookup.TryGetValue(hash, out var duplicate))
{
source.DuplicateOf = duplicate;
isDuplicate = true;
}
else
{
duplicateLookup.Add(hash, source);
}
}
source.Packed = new RectInt(0, 0, right - left, bottom - top);
source.Frame = new RectInt(-left, -top, width, height);
if (!isDuplicate)
{
source.Buffer = new Color[source.Packed.Width * source.Packed.Height];
// copy our trimmed pixel data to the main buffer
for (int i = 0; i < source.Packed.Height; i++)
{
var run = source.Packed.Width;
var from = pixels.Slice(left + (top + i) * width, run);
var to = new Span<Color>(source.Buffer, i * run, run);
from.CopyTo(to);
}
}
}
else
{
source.Packed = new RectInt();
source.Frame = new RectInt(0, 0, width, height);
}
sources.Add(source);
}
private struct PackingNode
{
public bool Used;
public RectInt Rect;
public unsafe PackingNode* Right;
public unsafe PackingNode* Down;
};
public unsafe Output Pack()
{
// Already been packed
if (!HasUnpackedData)
return Packed;
// Reset
Packed = new Output();
HasUnpackedData = false;
// Nothing to pack
if (sources.Count <= 0)
return Packed;
// sort the sources by size
sources.Sort((a, b) => b.Packed.Width * b.Packed.Height - a.Packed.Width * a.Packed.Height);
// make sure the largest isn't too large
if (sources[0].Packed.Width > MaxSize || sources[0].Packed.Height > MaxSize)
throw new Exception("Source image is larger than max atlas size");
// TODO: why do we sometimes need more than source images * 3?
// for safety I've just made it 4 ... but it should really only be 3?
int nodeCount = sources.Count * 4;
Span<PackingNode> buffer = (nodeCount <= 2000 ?
stackalloc PackingNode[nodeCount] :
new PackingNode[nodeCount]);
var padding = Math.Max(0, Padding);
// using pointer operations here was faster
fixed (PackingNode* nodes = buffer)
{
int packed = 0, page = 0;
while (packed < sources.Count)
{
if (sources[packed].Empty)
{
packed++;
continue;
}
var from = packed;
var nodePtr = nodes;
var rootPtr = ResetNode(nodePtr++, 0, 0, sources[from].Packed.Width + padding, sources[from].Packed.Height + padding);
while (packed < sources.Count)
{
if (sources[packed].Empty || sources[packed].DuplicateOf != null)
{
packed++;
continue;
}
int w = sources[packed].Packed.Width + padding;
int h = sources[packed].Packed.Height + padding;
var node = FindNode(rootPtr, w, h);
// try to expand
if (node == null)
{
bool canGrowDown = (w <= rootPtr->Rect.Width) && (rootPtr->Rect.Height + h < MaxSize);
bool canGrowRight = (h <= rootPtr->Rect.Height) && (rootPtr->Rect.Width + w < MaxSize);
bool shouldGrowRight = canGrowRight && (rootPtr->Rect.Height >= (rootPtr->Rect.Width + w));
bool shouldGrowDown = canGrowDown && (rootPtr->Rect.Width >= (rootPtr->Rect.Height + h));
if (canGrowDown || canGrowRight)
{
// grow right
if (shouldGrowRight || (!shouldGrowDown && canGrowRight))
{
var next = ResetNode(nodePtr++, 0, 0, rootPtr->Rect.Width + w, rootPtr->Rect.Height);
next->Used = true;
next->Down = rootPtr;
next->Right = node = ResetNode(nodePtr++, rootPtr->Rect.Width, 0, w, rootPtr->Rect.Height);
rootPtr = next;
}
// grow down
else
{
var next = ResetNode(nodePtr++, 0, 0, rootPtr->Rect.Width, rootPtr->Rect.Height + h);
next->Used = true;
next->Down = node = ResetNode(nodePtr++, 0, rootPtr->Rect.Height, rootPtr->Rect.Width, h);
next->Right = rootPtr;
rootPtr = next;
}
}
}
// doesn't fit in this page
if (node == null)
break;
// add
node->Used = true;
node->Down = ResetNode(nodePtr++, node->Rect.X, node->Rect.Y + h, node->Rect.Width, node->Rect.Height - h);
node->Right = ResetNode(nodePtr++, node->Rect.X + w, node->Rect.Y, node->Rect.Width - w, h);
sources[packed].Packed.X = node->Rect.X;
sources[packed].Packed.Y = node->Rect.Y;
packed++;
}
// get page size
int pageWidth, pageHeight;
if (PowerOfTwo)
{
pageWidth = 2;
pageHeight = 2;
while (pageWidth < rootPtr->Rect.Width)
pageWidth *= 2;
while (pageHeight < rootPtr->Rect.Height)
pageHeight *= 2;
}
else
{
pageWidth = rootPtr->Rect.Width;
pageHeight = rootPtr->Rect.Height;
}
// create each page
{
var bmp = new Bitmap(pageWidth, pageHeight);
Packed.Pages.Add(bmp);
// create each entry for this page and copy its image data
for (int i = from; i < packed; i++)
{
var source = sources[i];
// do not pack duplicate entries yet
if (source.DuplicateOf == null)
{
Packed.Entries[source.Name] = new Entry(source.Name, page, source.Packed, source.Frame);
if (!source.Empty)
bmp.SetPixels(source.Packed, source.Buffer);
}
}
}
page++;
}
}
// make sure duplicates have entries
if (CombineDuplicates)
{
foreach (var source in sources)
{
if (source.DuplicateOf != null)
{
var entry = Packed.Entries[source.DuplicateOf.Name];
Packed.Entries[source.Name] = new Entry(source.Name, entry.Page, entry.Source, entry.Frame);
}
}
}
return Packed;
static unsafe PackingNode* FindNode(PackingNode* root, int w, int h)
{
if (root->Used)
{
var r = FindNode(root->Right, w, h);
return (r != null ? r : FindNode(root->Down, w, h));
}
else if (w <= root->Rect.Width && h <= root->Rect.Height)
{
return root;
}
return null;
}
static unsafe PackingNode* ResetNode(PackingNode* node, int x, int y, int w, int h)
{
node->Used = false;
node->Rect = new RectInt(x, y, w, h);
node->Right = null;
node->Down = null;
return node;
}
}
/// <summary>
/// Removes all source data and removes the Packed Output
/// </summary>
public void Clear()
{
sources.Clear();
duplicateLookup.Clear();
Packed = new Output();
HasUnpackedData = false;
}
}