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