1 // stb_rect_pack.h - v0.10 - public domain - rectangle packing
4 // Useful for e.g. packing rectangular textures into an atlas.
5 // Does not do rotation.
7 // Not necessarily the awesomest packing method, but better than
8 // the totally naive one in stb_truetype (which is primarily what
9 // this is meant to replace).
11 // Has only had a few tests run, may have issues.
15 // No memory allocations; uses qsort() and assert() from stdlib.
16 // Can override those by defining STBRP_SORT and STBRP_ASSERT.
18 // This library currently uses the Skyline Bottom-Left algorithm.
20 // Please note: better rectangle packers are welcome! Please
21 // implement them to the same API, but with a different init
30 // Bugfixes / warning fixes
35 // 0.10 (2016-10-25) remove cast-away-const to avoid warnings
36 // 0.09 (2016-08-27) fix compiler warnings
37 // 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
38 // 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
39 // 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
40 // 0.05: added STBRP_ASSERT to allow replacing assert
41 // 0.04: fixed minor bug in STBRP_LARGE_RECTS support
42 // 0.01: initial release
46 // This software is dual-licensed to the public domain and under the following
47 // license: you are granted a perpetual, irrevocable license to copy, modify,
48 // publish, and distribute this file as you see fit.
50 //////////////////////////////////////////////////////////////////////////////
55 #ifndef STB_INCLUDE_STB_RECT_PACK_H
56 #define STB_INCLUDE_STB_RECT_PACK_H
58 #define STB_RECT_PACK_VERSION 1
61 #define STBRP_DEF static
63 #define STBRP_DEF extern
70 typedef struct stbrp_context stbrp_context;
71 typedef struct stbrp_node stbrp_node;
72 typedef struct stbrp_rect stbrp_rect;
74 #ifdef STBRP_LARGE_RECTS
75 typedef int stbrp_coord;
77 typedef unsigned short stbrp_coord;
80 STBRP_DEF void stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
81 // Assign packed locations to rectangles. The rectangles are of type
82 // 'stbrp_rect' defined below, stored in the array 'rects', and there
83 // are 'num_rects' many of them.
85 // Rectangles which are successfully packed have the 'was_packed' flag
86 // set to a non-zero value and 'x' and 'y' store the minimum location
87 // on each axis (i.e. bottom-left in cartesian coordinates, top-left
88 // if you imagine y increasing downwards). Rectangles which do not fit
89 // have the 'was_packed' flag set to 0.
91 // You should not try to access the 'rects' array from another thread
92 // while this function is running, as the function temporarily reorders
93 // the array while it executes.
95 // To pack into another rectangle, you need to call stbrp_init_target
96 // again. To continue packing into the same rectangle, you can call
97 // this function again. Calling this multiple times with multiple rect
98 // arrays will probably produce worse packing results than calling it
99 // a single time with the full rectangle array, but the option is
104 // reserved for your use:
112 int was_packed; // non-zero if valid packing
114 }; // 16 bytes, nominally
117 STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
118 // Initialize a rectangle packer to:
119 // pack a rectangle that is 'width' by 'height' in dimensions
120 // using temporary storage provided by the array 'nodes', which is 'num_nodes' long
122 // You must call this function every time you start packing into a new target.
124 // There is no "shutdown" function. The 'nodes' memory must stay valid for
125 // the following stbrp_pack_rects() call (or calls), but can be freed after
126 // the call (or calls) finish.
128 // Note: to guarantee best results, either:
129 // 1. make sure 'num_nodes' >= 'width'
130 // or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
132 // If you don't do either of the above things, widths will be quantized to multiples
133 // of small integers to guarantee the algorithm doesn't run out of temporary storage.
135 // If you do #2, then the non-quantized algorithm will be used, but the algorithm
136 // may run out of temporary storage and be unable to pack some rectangles.
138 STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
139 // Optionally call this function after init but before doing any packing to
140 // change the handling of the out-of-temp-memory scenario, described above.
141 // If you call init again, this will be reset to the default (false).
144 STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
145 // Optionally select which packing heuristic the library should use. Different
146 // heuristics will produce better/worse results for different data sets.
147 // If you call init again, this will be reset to the default.
151 STBRP_HEURISTIC_Skyline_default=0,
152 STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
153 STBRP_HEURISTIC_Skyline_BF_sortHeight
157 //////////////////////////////////////////////////////////////////////////////
159 // the details of the following structures don't matter to you, but they must
160 // be visible so you can handle the memory allocations for them
176 stbrp_node *active_head;
177 stbrp_node *free_head;
178 stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
187 //////////////////////////////////////////////////////////////////////////////
189 // IMPLEMENTATION SECTION
192 #ifdef STB_RECT_PACK_IMPLEMENTATION
195 #define STBRP_SORT qsort
200 #define STBRP_ASSERT assert
204 #define STBRP__NOTUSED(v) (void)(v)
206 #define STBRP__NOTUSED(v) (void)sizeof(v)
211 STBRP__INIT_skyline = 1
214 STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
216 switch (context->init_mode) {
217 case STBRP__INIT_skyline:
218 STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
219 context->heuristic = heuristic;
226 STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
228 if (allow_out_of_mem)
229 // if it's ok to run out of memory, then don't bother aligning them;
230 // this gives better packing, but may fail due to OOM (even though
231 // the rectangles easily fit). @TODO a smarter approach would be to only
232 // quantize once we've hit OOM, then we could get rid of this parameter.
235 // if it's not ok to run out of memory, then quantize the widths
236 // so that num_nodes is always enough nodes.
238 // I.e. num_nodes * align >= width
239 // align >= width / num_nodes
240 // align = ceil(width/num_nodes)
242 context->align = (context->width + context->num_nodes-1) / context->num_nodes;
246 STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
249 #ifndef STBRP_LARGE_RECTS
250 STBRP_ASSERT(width <= 0xffff && height <= 0xffff);
253 for (i=0; i < num_nodes-1; ++i)
254 nodes[i].next = &nodes[i+1];
255 nodes[i].next = NULL;
256 context->init_mode = STBRP__INIT_skyline;
257 context->heuristic = STBRP_HEURISTIC_Skyline_default;
258 context->free_head = &nodes[0];
259 context->active_head = &context->extra[0];
260 context->width = width;
261 context->height = height;
262 context->num_nodes = num_nodes;
263 stbrp_setup_allow_out_of_mem(context, 0);
265 // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
266 context->extra[0].x = 0;
267 context->extra[0].y = 0;
268 context->extra[0].next = &context->extra[1];
269 context->extra[1].x = (stbrp_coord) width;
270 #ifdef STBRP_LARGE_RECTS
271 context->extra[1].y = (1<<30);
273 context->extra[1].y = 65535;
275 context->extra[1].next = NULL;
278 // find minimum y position if it starts at x1
279 static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
281 stbrp_node *node = first;
283 int min_y, visited_width, waste_area;
287 STBRP_ASSERT(first->x <= x0);
290 // skip in case we're past the node
291 while (node->next->x <= x0)
294 STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
297 STBRP_ASSERT(node->x <= x0);
302 while (node->x < x1) {
303 if (node->y > min_y) {
304 // raise min_y higher.
305 // we've accounted for all waste up to min_y,
306 // but we'll now add more waste for everything we've visted
307 waste_area += visited_width * (node->y - min_y);
309 // the first time through, visited_width might be reduced
311 visited_width += node->next->x - x0;
313 visited_width += node->next->x - node->x;
316 int under_width = node->next->x - node->x;
317 if (under_width + visited_width > width)
318 under_width = width - visited_width;
319 waste_area += under_width * (min_y - node->y);
320 visited_width += under_width;
325 *pwaste = waste_area;
332 stbrp_node **prev_link;
335 static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
337 int best_waste = (1<<30), best_x, best_y = (1 << 30);
338 stbrp__findresult fr;
339 stbrp_node **prev, *node, *tail, **best = NULL;
341 // align to multiple of c->align
342 width = (width + c->align - 1);
343 width -= width % c->align;
344 STBRP_ASSERT(width % c->align == 0);
346 node = c->active_head;
347 prev = &c->active_head;
348 while (node->x + width <= c->width) {
350 y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
351 if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
359 if (y + height <= c->height) {
360 // can only use it if it first vertically
361 if (y < best_y || (y == best_y && waste < best_waste)) {
372 best_x = (best == NULL) ? 0 : (*best)->x;
374 // if doing best-fit (BF), we also have to try aligning right edge to each node position
378 // ____________________
379 // |____________________|
387 // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
389 // This makes BF take about 2x the time
391 if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
392 tail = c->active_head;
393 node = c->active_head;
394 prev = &c->active_head;
395 // find first node that's admissible
396 while (tail->x < width)
399 int xpos = tail->x - width;
401 STBRP_ASSERT(xpos >= 0);
402 // find the left position that matches this
403 while (node->next->x <= xpos) {
407 STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
408 y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
409 if (y + height < c->height) {
411 if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
413 STBRP_ASSERT(y <= best_y);
430 static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
432 // find best position according to heuristic
433 stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
434 stbrp_node *node, *cur;
438 // 2. the best node doesn't fit (we don't always check this)
439 // 3. we're out of memory
440 if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
441 res.prev_link = NULL;
445 // on success, create new node
446 node = context->free_head;
447 node->x = (stbrp_coord) res.x;
448 node->y = (stbrp_coord) (res.y + height);
450 context->free_head = node->next;
452 // insert the new node into the right starting point, and
453 // let 'cur' point to the remaining nodes needing to be
456 cur = *res.prev_link;
457 if (cur->x < res.x) {
458 // preserve the existing one, so start testing with the next one
459 stbrp_node *next = cur->next;
463 *res.prev_link = node;
466 // from here, traverse cur and free the nodes, until we get to one
467 // that shouldn't be freed
468 while (cur->next && cur->next->x <= res.x + width) {
469 stbrp_node *next = cur->next;
470 // move the current node to the free list
471 cur->next = context->free_head;
472 context->free_head = cur;
476 // stitch the list back in
479 if (cur->x < res.x + width)
480 cur->x = (stbrp_coord) (res.x + width);
483 cur = context->active_head;
484 while (cur->x < context->width) {
485 STBRP_ASSERT(cur->x < cur->next->x);
488 STBRP_ASSERT(cur->next == NULL);
491 stbrp_node *L1 = NULL, *L2 = NULL;
493 cur = context->active_head;
499 cur = context->free_head;
505 STBRP_ASSERT(count == context->num_nodes+2);
512 static int rect_height_compare(const void *a, const void *b)
514 const stbrp_rect *p = (const stbrp_rect *) a;
515 const stbrp_rect *q = (const stbrp_rect *) b;
520 return (p->w > q->w) ? -1 : (p->w < q->w);
523 static int rect_width_compare(const void *a, const void *b)
525 const stbrp_rect *p = (const stbrp_rect *) a;
526 const stbrp_rect *q = (const stbrp_rect *) b;
531 return (p->h > q->h) ? -1 : (p->h < q->h);
534 static int rect_original_order(const void *a, const void *b)
536 const stbrp_rect *p = (const stbrp_rect *) a;
537 const stbrp_rect *q = (const stbrp_rect *) b;
538 return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
541 #ifdef STBRP_LARGE_RECTS
542 #define STBRP__MAXVAL 0xffffffff
544 #define STBRP__MAXVAL 0xffff
547 STBRP_DEF void stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
551 // we use the 'was_packed' field internally to allow sorting/unsorting
552 for (i=0; i < num_rects; ++i) {
553 rects[i].was_packed = i;
554 #ifndef STBRP_LARGE_RECTS
555 STBRP_ASSERT(rects[i].w <= 0xffff && rects[i].h <= 0xffff);
559 // sort according to heuristic
560 STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
562 for (i=0; i < num_rects; ++i) {
563 if (rects[i].w == 0 || rects[i].h == 0) {
564 rects[i].x = rects[i].y = 0; // empty rect needs no space
566 stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
568 rects[i].x = (stbrp_coord) fr.x;
569 rects[i].y = (stbrp_coord) fr.y;
571 rects[i].x = rects[i].y = STBRP__MAXVAL;
577 STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
579 // set was_packed flags
580 for (i=0; i < num_rects; ++i)
581 rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);