1 // stb_rect_pack.h - v1.01 - public domain - rectangle packing
2 // Sean Barrett 2014
3 //
4 // Useful for e.g. packing rectangular textures into an atlas.
5 // Does not do rotation.
6 //
7 // Before #including,
8 //
9 //    #define STB_RECT_PACK_IMPLEMENTATION
10 //
11 // in the file that you want to have the implementation.
12 //
13 // Not necessarily the awesomest packing method, but better than
14 // the totally naive one in stb_truetype (which is primarily what
15 // this is meant to replace).
16 //
17 // Has only had a few tests run, may have issues.
18 //
19 // More docs to come.
20 //
21 // No memory allocations; uses qsort() and assert() from stdlib.
22 // Can override those by defining STBRP_SORT and STBRP_ASSERT.
23 //
24 // This library currently uses the Skyline Bottom-Left algorithm.
25 //
26 // Please note: better rectangle packers are welcome! Please
27 // implement them to the same API, but with a different init
28 // function.
29 //
30 // Credits
31 //
32 //  Library
33 //    Sean Barrett
34 //  Minor features
35 //    Martins Mozeiko
36 //    github:IntellectualKitty
37 //
38 //  Bugfixes / warning fixes
39 //    Jeremy Jaussaud
40 //    Fabian Giesen
41 //
42 // Version history:
43 //
44 //     1.01  (2021-07-11)  always use large rect mode, expose STBRP__MAXVAL in public section
45 //     1.00  (2019-02-25)  avoid small space waste; gracefully fail too-wide rectangles
46 //     0.99  (2019-02-07)  warning fixes
47 //     0.11  (2017-03-03)  return packing success/fail result
48 //     0.10  (2016-10-25)  remove cast-away-const to avoid warnings
49 //     0.09  (2016-08-27)  fix compiler warnings
50 //     0.08  (2015-09-13)  really fix bug with empty rects (w=0 or h=0)
51 //     0.07  (2015-09-13)  fix bug with empty rects (w=0 or h=0)
52 //     0.06  (2015-04-15)  added STBRP_SORT to allow replacing qsort
53 //     0.05:  added STBRP_ASSERT to allow replacing assert
54 //     0.04:  fixed minor bug in STBRP_LARGE_RECTS support
55 //     0.01:  initial release
56 //
57 // LICENSE
58 //
59 //   See end of file for license information.
60 
61 //////////////////////////////////////////////////////////////////////////////
62 //
63 //       INCLUDE SECTION
64 //
65 
66 #ifndef STB_INCLUDE_STB_RECT_PACK_H
67 #define STB_INCLUDE_STB_RECT_PACK_H
68 
69 #define STB_RECT_PACK_VERSION  1
70 
71 #ifdef STBRP_STATIC
72     #define STBRP_DEF static
73 #else
74     #define STBRP_DEF extern
75 #endif
76 
77 #ifdef __cplusplus
78 extern "C" {
79 #endif
80 
81 /// @cond
82 /**
83  *  Tells Doxygen to ignore a duplicate declaration
84  */
85 typedef struct stbrp_context stbrp_context;
86 typedef struct stbrp_node    stbrp_node;
87 typedef struct stbrp_rect    stbrp_rect;
88 /// @endcond
89 
90 typedef int            stbrp_coord;
91 
92 #define STBRP__MAXVAL  0x7fffffff
93 // Mostly for internal use, but this is the maximum supported coordinate value.
94 
95 #if defined(__GNUC__) || defined(__clang__)
96 #pragma GCC diagnostic push
97 #pragma GCC diagnostic ignored "-Wunused-function"
98 #endif
99 
100 STBRP_DEF int stbrp_pack_rects(stbrp_context * context, stbrp_rect * rects, int num_rects);
101 // Assign packed locations to rectangles. The rectangles are of type
102 // 'stbrp_rect' defined below, stored in the array 'rects', and there
103 // are 'num_rects' many of them.
104 //
105 // Rectangles which are successfully packed have the 'was_packed' flag
106 // set to a non-zero value and 'x' and 'y' store the minimum location
107 // on each axis (i.e. bottom-left in cartesian coordinates, top-left
108 // if you imagine y increasing downwards). Rectangles which do not fit
109 // have the 'was_packed' flag set to 0.
110 //
111 // You should not try to access the 'rects' array from another thread
112 // while this function is running, as the function temporarily reorders
113 // the array while it executes.
114 //
115 // To pack into another rectangle, you need to call stbrp_init_target
116 // again. To continue packing into the same rectangle, you can call
117 // this function again. Calling this multiple times with multiple rect
118 // arrays will probably produce worse packing results than calling it
119 // a single time with the full rectangle array, but the option is
120 // available.
121 //
122 // The function returns 1 if all of the rectangles were successfully
123 // packed and 0 otherwise.
124 
125 struct stbrp_rect {
126     // reserved for your use:
127     int            id;
128 
129     // input:
130     stbrp_coord    w, h;
131 
132     // output:
133     stbrp_coord    x, y;
134     int            was_packed;  // non-zero if valid packing
135 
136 }; // 16 bytes, nominally
137 
138 STBRP_DEF void stbrp_init_target(stbrp_context * context, int width, int height, stbrp_node * nodes, int num_nodes);
139 // Initialize a rectangle packer to:
140 //    pack a rectangle that is 'width' by 'height' in dimensions
141 //    using temporary storage provided by the array 'nodes', which is 'num_nodes' long
142 //
143 // You must call this function every time you start packing into a new target.
144 //
145 // There is no "shutdown" function. The 'nodes' memory must stay valid for
146 // the following stbrp_pack_rects() call (or calls), but can be freed after
147 // the call (or calls) finish.
148 //
149 // Note: to guarantee best results, either:
150 //       1. make sure 'num_nodes' >= 'width'
151 //   or  2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
152 //
153 // If you don't do either of the above things, widths will be quantized to multiples
154 // of small integers to guarantee the algorithm doesn't run out of temporary storage.
155 //
156 // If you do #2, then the non-quantized algorithm will be used, but the algorithm
157 // may run out of temporary storage and be unable to pack some rectangles.
158 
159 STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context * context, int allow_out_of_mem);
160 // Optionally call this function after init but before doing any packing to
161 // change the handling of the out-of-temp-memory scenario, described above.
162 // If you call init again, this will be reset to the default (false).
163 
164 STBRP_DEF void stbrp_setup_heuristic(stbrp_context * context, int heuristic);
165 // Optionally select which packing heuristic the library should use. Different
166 // heuristics will produce better/worse results for different data sets.
167 // If you call init again, this will be reset to the default.
168 
169 enum {
170     STBRP_HEURISTIC_Skyline_default = 0,
171     STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
172     STBRP_HEURISTIC_Skyline_BF_sortHeight
173 };
174 
175 //////////////////////////////////////////////////////////////////////////////
176 //
177 // the details of the following structures don't matter to you, but they must
178 // be visible so you can handle the memory allocations for them
179 
180 struct stbrp_node {
181     stbrp_coord  x, y;
182     stbrp_node * next;
183 };
184 
185 struct stbrp_context {
186     int width;
187     int height;
188     int align;
189     int init_mode;
190     int heuristic;
191     int num_nodes;
192     stbrp_node * active_head;
193     stbrp_node * free_head;
194     stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
195 };
196 
197 #ifdef __cplusplus
198 }
199 #endif
200 
201 #endif
202 
203 //////////////////////////////////////////////////////////////////////////////
204 //
205 //     IMPLEMENTATION SECTION
206 //
207 
208 #ifdef STB_RECT_PACK_IMPLEMENTATION
209 #ifndef STBRP_SORT
210     #include <stdlib.h>
211     #define STBRP_SORT qsort
212 #endif
213 
214 #ifndef STBRP_ASSERT
215     #include <assert.h>
216     #define STBRP_ASSERT assert
217 #endif
218 
219 #ifdef _MSC_VER
220     #define STBRP__NOTUSED(v)  (void)(v)
221     #define STBRP__CDECL       __cdecl
222 #else
223     #define STBRP__NOTUSED(v)  (void)sizeof(v)
224     #define STBRP__CDECL
225 #endif
226 
227 enum {
228     STBRP__INIT_skyline = 1
229 };
230 
stbrp_setup_heuristic(stbrp_context * context,int heuristic)231 STBRP_DEF void stbrp_setup_heuristic(stbrp_context * context, int heuristic)
232 {
233     switch(context->init_mode) {
234         case STBRP__INIT_skyline:
235             STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
236             context->heuristic = heuristic;
237             break;
238         default:
239             STBRP_ASSERT(0);
240     }
241 }
242 
stbrp_setup_allow_out_of_mem(stbrp_context * context,int allow_out_of_mem)243 STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context * context, int allow_out_of_mem)
244 {
245     if(allow_out_of_mem)
246         // if it's ok to run out of memory, then don't bother aligning them;
247         // this gives better packing, but may fail due to OOM (even though
248         // the rectangles easily fit). @TODO a smarter approach would be to only
249         // quantize once we've hit OOM, then we could get rid of this parameter.
250         context->align = 1;
251     else {
252         // if it's not ok to run out of memory, then quantize the widths
253         // so that num_nodes is always enough nodes.
254         //
255         // I.e. num_nodes * align >= width
256         //                  align >= width / num_nodes
257         //                  align = ceil(width/num_nodes)
258 
259         context->align = (context->width + context->num_nodes - 1) / context->num_nodes;
260     }
261 }
262 
stbrp_init_target(stbrp_context * context,int width,int height,stbrp_node * nodes,int num_nodes)263 STBRP_DEF void stbrp_init_target(stbrp_context * context, int width, int height, stbrp_node * nodes, int num_nodes)
264 {
265     int i;
266 
267     for(i = 0; i < num_nodes - 1; ++i)
268         nodes[i].next = &nodes[i + 1];
269     nodes[i].next = NULL;
270     context->init_mode = STBRP__INIT_skyline;
271     context->heuristic = STBRP_HEURISTIC_Skyline_default;
272     context->free_head = &nodes[0];
273     context->active_head = &context->extra[0];
274     context->width = width;
275     context->height = height;
276     context->num_nodes = num_nodes;
277     stbrp_setup_allow_out_of_mem(context, 0);
278 
279     // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
280     context->extra[0].x = 0;
281     context->extra[0].y = 0;
282     context->extra[0].next = &context->extra[1];
283     context->extra[1].x = (stbrp_coord) width;
284     context->extra[1].y = (1 << 30);
285     context->extra[1].next = NULL;
286 }
287 
288 // find minimum y position if it starts at x1
stbrp__skyline_find_min_y(stbrp_context * c,stbrp_node * first,int x0,int width,int * pwaste)289 static int stbrp__skyline_find_min_y(stbrp_context * c, stbrp_node * first, int x0, int width, int * pwaste)
290 {
291     stbrp_node * node = first;
292     int x1 = x0 + width;
293     int min_y, visited_width, waste_area;
294 
295     STBRP__NOTUSED(c);
296 
297     STBRP_ASSERT(first->x <= x0);
298 
299 #if 0
300     // skip in case we're past the node
301     while(node->next->x <= x0)
302         ++node;
303 #else
304     STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
305 #endif
306 
307     STBRP_ASSERT(node->x <= x0);
308 
309     min_y = 0;
310     waste_area = 0;
311     visited_width = 0;
312     while(node->x < x1) {
313         if(node->y > min_y) {
314             // raise min_y higher.
315             // we've accounted for all waste up to min_y,
316             // but we'll now add more waste for everything we've visited
317             waste_area += visited_width * (node->y - min_y);
318             min_y = node->y;
319             // the first time through, visited_width might be reduced
320             if(node->x < x0)
321                 visited_width += node->next->x - x0;
322             else
323                 visited_width += node->next->x - node->x;
324         }
325         else {
326             // add waste area
327             int under_width = node->next->x - node->x;
328             if(under_width + visited_width > width)
329                 under_width = width - visited_width;
330             waste_area += under_width * (min_y - node->y);
331             visited_width += under_width;
332         }
333         node = node->next;
334     }
335 
336     *pwaste = waste_area;
337     return min_y;
338 }
339 
340 typedef struct {
341     int x, y;
342     stbrp_node ** prev_link;
343 } stbrp__findresult;
344 
stbrp__skyline_find_best_pos(stbrp_context * c,int width,int height)345 static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context * c, int width, int height)
346 {
347     int best_waste = (1 << 30), best_x, best_y = (1 << 30);
348     stbrp__findresult fr;
349     stbrp_node ** prev, * node, * tail, ** best = NULL;
350 
351     // align to multiple of c->align
352     width = (width + c->align - 1);
353     width -= width % c->align;
354     STBRP_ASSERT(width % c->align == 0);
355 
356     // if it can't possibly fit, bail immediately
357     if(width > c->width || height > c->height) {
358         fr.prev_link = NULL;
359         fr.x = fr.y = 0;
360         return fr;
361     }
362 
363     node = c->active_head;
364     prev = &c->active_head;
365     while(node->x + width <= c->width) {
366         int y, waste;
367         y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
368         if(c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) {  // actually just want to test BL
369             // bottom left
370             if(y < best_y) {
371                 best_y = y;
372                 best = prev;
373             }
374         }
375         else {
376             // best-fit
377             if(y + height <= c->height) {
378                 // can only use it if it first vertically
379                 if(y < best_y || (y == best_y && waste < best_waste)) {
380                     best_y = y;
381                     best_waste = waste;
382                     best = prev;
383                 }
384             }
385         }
386         prev = &node->next;
387         node = node->next;
388     }
389 
390     best_x = (best == NULL) ? 0 : (*best)->x;
391 
392     // if doing best-fit (BF), we also have to try aligning right edge to each node position
393     //
394     // e.g, if fitting
395     //
396     //     ____________________
397     //    |____________________|
398     //
399     //            into
400     //
401     //   |                         |
402     //   |             ____________|
403     //   |____________|
404     //
405     // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
406     //
407     // This makes BF take about 2x the time
408 
409     if(c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
410         tail = c->active_head;
411         node = c->active_head;
412         prev = &c->active_head;
413         // find first node that's admissible
414         while(tail->x < width)
415             tail = tail->next;
416         while(tail) {
417             int xpos = tail->x - width;
418             int y, waste;
419             STBRP_ASSERT(xpos >= 0);
420             // find the left position that matches this
421             while(node->next->x <= xpos) {
422                 prev = &node->next;
423                 node = node->next;
424             }
425             STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
426             y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
427             if(y + height <= c->height) {
428                 if(y <= best_y) {
429                     if(y < best_y || waste < best_waste || (waste == best_waste && xpos < best_x)) {
430                         best_x = xpos;
431                         STBRP_ASSERT(y <= best_y);
432                         best_y = y;
433                         best_waste = waste;
434                         best = prev;
435                     }
436                 }
437             }
438             tail = tail->next;
439         }
440     }
441 
442     fr.prev_link = best;
443     fr.x = best_x;
444     fr.y = best_y;
445     return fr;
446 }
447 
stbrp__skyline_pack_rectangle(stbrp_context * context,int width,int height)448 static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context * context, int width, int height)
449 {
450     // find best position according to heuristic
451     stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
452     stbrp_node * node, * cur;
453 
454     // bail if:
455     //    1. it failed
456     //    2. the best node doesn't fit (we don't always check this)
457     //    3. we're out of memory
458     if(res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
459         res.prev_link = NULL;
460         return res;
461     }
462 
463     // on success, create new node
464     node = context->free_head;
465     node->x = (stbrp_coord) res.x;
466     node->y = (stbrp_coord)(res.y + height);
467 
468     context->free_head = node->next;
469 
470     // insert the new node into the right starting point, and
471     // let 'cur' point to the remaining nodes needing to be
472     // stiched back in
473 
474     cur = *res.prev_link;
475     if(cur->x < res.x) {
476         // preserve the existing one, so start testing with the next one
477         stbrp_node * next = cur->next;
478         cur->next = node;
479         cur = next;
480     }
481     else {
482         *res.prev_link = node;
483     }
484 
485     // from here, traverse cur and free the nodes, until we get to one
486     // that shouldn't be freed
487     while(cur->next && cur->next->x <= res.x + width) {
488         stbrp_node * next = cur->next;
489         // move the current node to the free list
490         cur->next = context->free_head;
491         context->free_head = cur;
492         cur = next;
493     }
494 
495     // stitch the list back in
496     node->next = cur;
497 
498     if(cur->x < res.x + width)
499         cur->x = (stbrp_coord)(res.x + width);
500 
501 #ifdef _DEBUG
502     cur = context->active_head;
503     while(cur->x < context->width) {
504         STBRP_ASSERT(cur->x < cur->next->x);
505         cur = cur->next;
506     }
507     STBRP_ASSERT(cur->next == NULL);
508 
509     {
510         int count = 0;
511         cur = context->active_head;
512         while(cur) {
513             cur = cur->next;
514             ++count;
515         }
516         cur = context->free_head;
517         while(cur) {
518             cur = cur->next;
519             ++count;
520         }
521         STBRP_ASSERT(count == context->num_nodes + 2);
522     }
523 #endif
524 
525     return res;
526 }
527 
rect_height_compare(const void * a,const void * b)528 static int STBRP__CDECL rect_height_compare(const void * a, const void * b)
529 {
530     const stbrp_rect * p = (const stbrp_rect *) a;
531     const stbrp_rect * q = (const stbrp_rect *) b;
532     if(p->h > q->h)
533         return -1;
534     if(p->h < q->h)
535         return  1;
536     return (p->w > q->w) ? -1 : (p->w < q->w);
537 }
538 
rect_original_order(const void * a,const void * b)539 static int STBRP__CDECL rect_original_order(const void * a, const void * b)
540 {
541     const stbrp_rect * p = (const stbrp_rect *) a;
542     const stbrp_rect * q = (const stbrp_rect *) b;
543     return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
544 }
545 
stbrp_pack_rects(stbrp_context * context,stbrp_rect * rects,int num_rects)546 STBRP_DEF int stbrp_pack_rects(stbrp_context * context, stbrp_rect * rects, int num_rects)
547 {
548     int i, all_rects_packed = 1;
549 
550     // we use the 'was_packed' field internally to allow sorting/unsorting
551     for(i = 0; i < num_rects; ++i) {
552         rects[i].was_packed = i;
553     }
554 
555     // sort according to heuristic
556     STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
557 
558     for(i = 0; i < num_rects; ++i) {
559         if(rects[i].w == 0 || rects[i].h == 0) {
560             rects[i].x = rects[i].y = 0;  // empty rect needs no space
561         }
562         else {
563             stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
564             if(fr.prev_link) {
565                 rects[i].x = (stbrp_coord) fr.x;
566                 rects[i].y = (stbrp_coord) fr.y;
567             }
568             else {
569                 rects[i].x = rects[i].y = STBRP__MAXVAL;
570             }
571         }
572     }
573 
574     // unsort
575     STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
576 
577     // set was_packed flags and all_rects_packed status
578     for(i = 0; i < num_rects; ++i) {
579         rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
580         if(!rects[i].was_packed)
581             all_rects_packed = 0;
582     }
583 
584     // return the all_rects_packed status
585     return all_rects_packed;
586 }
587 #endif
588 
589 #if defined(__GNUC__) || defined(__clang__)
590     #pragma GCC diagnostic pop
591 #endif
592 
593 /*
594 ------------------------------------------------------------------------------
595 This software is available under 2 licenses -- choose whichever you prefer.
596 ------------------------------------------------------------------------------
597 ALTERNATIVE A - MIT License
598 Copyright (c) 2017 Sean Barrett
599 Permission is hereby granted, free of charge, to any person obtaining a copy of
600 this software and associated documentation files (the "Software"), to deal in
601 the Software without restriction, including without limitation the rights to
602 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
603 of the Software, and to permit persons to whom the Software is furnished to do
604 so, subject to the following conditions:
605 The above copyright notice and this permission notice shall be included in all
606 copies or substantial portions of the Software.
607 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
608 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
609 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
610 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
611 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
612 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
613 SOFTWARE.
614 ------------------------------------------------------------------------------
615 ALTERNATIVE B - Public Domain (www.unlicense.org)
616 This is free and unencumbered software released into the public domain.
617 Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
618 software, either in source code form or as a compiled binary, for any purpose,
619 commercial or non-commercial, and by any means.
620 In jurisdictions that recognize copyright laws, the author or authors of this
621 software dedicate any and all copyright interest in the software to the public
622 domain. We make this dedication for the benefit of the public at large and to
623 the detriment of our heirs and successors. We intend this dedication to be an
624 overt act of relinquishment in perpetuity of all present and future rights to
625 this software under copyright law.
626 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
627 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
628 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
629 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
630 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
631 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
632 ------------------------------------------------------------------------------
633 */
634