// [DEAR IMGUI]1// This is a slightly modified version of stb_rect_pack.h 1.01.2// Grep for [DEAR IMGUI] to find the changes.3//4// stb_rect_pack.h - v1.01 - public domain - rectangle packing5// Sean Barrett 20146//7// Useful for e.g. packing rectangular textures into an atlas.8// Does not do rotation.9//10// Before #including,11//12// #define STB_RECT_PACK_IMPLEMENTATION13//14// in the file that you want to have the implementation.15//16// Not necessarily the awesomest packing method, but better than17// the totally naive one in stb_truetype (which is primarily what18// this is meant to replace).19//20// Has only had a few tests run, may have issues.21//22// More docs to come.23//24// No memory allocations; uses qsort() and assert() from stdlib.25// Can override those by defining STBRP_SORT and STBRP_ASSERT.26//27// This library currently uses the Skyline Bottom-Left algorithm.28//29// Please note: better rectangle packers are welcome! Please30// implement them to the same API, but with a different init31// function.32//33// Credits34//35// Library36// Sean Barrett37// Minor features38// Martins Mozeiko39// github:IntellectualKitty40//41// Bugfixes / warning fixes42// Jeremy Jaussaud43// Fabian Giesen44//45// Version history:46//47// 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section48// 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles49// 0.99 (2019-02-07) warning fixes50// 0.11 (2017-03-03) return packing success/fail result51// 0.10 (2016-10-25) remove cast-away-const to avoid warnings52// 0.09 (2016-08-27) fix compiler warnings53// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)54// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)55// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort56// 0.05: added STBRP_ASSERT to allow replacing assert57// 0.04: fixed minor bug in STBRP_LARGE_RECTS support58// 0.01: initial release59//60// LICENSE61//62// See end of file for license information.6364//////////////////////////////////////////////////////////////////////////////65//66// INCLUDE SECTION67//6869#ifndef STB_INCLUDE_STB_RECT_PACK_H70#define STB_INCLUDE_STB_RECT_PACK_H7172#define STB_RECT_PACK_VERSION 17374#ifdef STBRP_STATIC75#define STBRP_DEF static76#else77#define STBRP_DEF extern78#endif7980#ifdef __cplusplus81extern "C" {82#endif8384typedef struct stbrp_context stbrp_context;85typedef struct stbrp_node stbrp_node;86typedef struct stbrp_rect stbrp_rect;8788typedef int stbrp_coord;8990#define STBRP__MAXVAL 0x7fffffff91// Mostly for internal use, but this is the maximum supported coordinate value.9293STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);94// Assign packed locations to rectangles. The rectangles are of type95// 'stbrp_rect' defined below, stored in the array 'rects', and there96// are 'num_rects' many of them.97//98// Rectangles which are successfully packed have the 'was_packed' flag99// set to a non-zero value and 'x' and 'y' store the minimum location100// on each axis (i.e. bottom-left in cartesian coordinates, top-left101// if you imagine y increasing downwards). Rectangles which do not fit102// have the 'was_packed' flag set to 0.103//104// You should not try to access the 'rects' array from another thread105// while this function is running, as the function temporarily reorders106// the array while it executes.107//108// To pack into another rectangle, you need to call stbrp_init_target109// again. To continue packing into the same rectangle, you can call110// this function again. Calling this multiple times with multiple rect111// arrays will probably produce worse packing results than calling it112// a single time with the full rectangle array, but the option is113// available.114//115// The function returns 1 if all of the rectangles were successfully116// packed and 0 otherwise.117118struct stbrp_rect119{120// reserved for your use:121int id;122123// input:124stbrp_coord w, h;125126// output:127stbrp_coord x, y;128int was_packed; // non-zero if valid packing129130}; // 16 bytes, nominally131132133STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);134// Initialize a rectangle packer to:135// pack a rectangle that is 'width' by 'height' in dimensions136// using temporary storage provided by the array 'nodes', which is 'num_nodes' long137//138// You must call this function every time you start packing into a new target.139//140// There is no "shutdown" function. The 'nodes' memory must stay valid for141// the following stbrp_pack_rects() call (or calls), but can be freed after142// the call (or calls) finish.143//144// Note: to guarantee best results, either:145// 1. make sure 'num_nodes' >= 'width'146// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'147//148// If you don't do either of the above things, widths will be quantized to multiples149// of small integers to guarantee the algorithm doesn't run out of temporary storage.150//151// If you do #2, then the non-quantized algorithm will be used, but the algorithm152// may run out of temporary storage and be unable to pack some rectangles.153154STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);155// Optionally call this function after init but before doing any packing to156// change the handling of the out-of-temp-memory scenario, described above.157// If you call init again, this will be reset to the default (false).158159160STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);161// Optionally select which packing heuristic the library should use. Different162// heuristics will produce better/worse results for different data sets.163// If you call init again, this will be reset to the default.164165enum166{167STBRP_HEURISTIC_Skyline_default=0,168STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,169STBRP_HEURISTIC_Skyline_BF_sortHeight170};171172173//////////////////////////////////////////////////////////////////////////////174//175// the details of the following structures don't matter to you, but they must176// be visible so you can handle the memory allocations for them177178struct stbrp_node179{180stbrp_coord x,y;181stbrp_node *next;182};183184struct stbrp_context185{186int width;187int height;188int align;189int init_mode;190int heuristic;191int num_nodes;192stbrp_node *active_head;193stbrp_node *free_head;194stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'195};196197#ifdef __cplusplus198}199#endif200201#endif202203//////////////////////////////////////////////////////////////////////////////204//205// IMPLEMENTATION SECTION206//207208#ifdef STB_RECT_PACK_IMPLEMENTATION209#ifndef STBRP_SORT210#include <stdlib.h>211#define STBRP_SORT qsort212#endif213214#ifndef STBRP_ASSERT215#include <assert.h>216#define STBRP_ASSERT assert217#endif218219#ifdef _MSC_VER220#define STBRP__NOTUSED(v) (void)(v)221#define STBRP__CDECL __cdecl222#else223#define STBRP__NOTUSED(v) (void)sizeof(v)224#define STBRP__CDECL225#endif226227enum228{229STBRP__INIT_skyline = 1230};231232STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)233{234switch (context->init_mode) {235case STBRP__INIT_skyline:236STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);237context->heuristic = heuristic;238break;239default:240STBRP_ASSERT(0);241}242}243244STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)245{246if (allow_out_of_mem)247// if it's ok to run out of memory, then don't bother aligning them;248// this gives better packing, but may fail due to OOM (even though249// the rectangles easily fit). @TODO a smarter approach would be to only250// quantize once we've hit OOM, then we could get rid of this parameter.251context->align = 1;252else {253// if it's not ok to run out of memory, then quantize the widths254// so that num_nodes is always enough nodes.255//256// I.e. num_nodes * align >= width257// align >= width / num_nodes258// align = ceil(width/num_nodes)259260context->align = (context->width + context->num_nodes-1) / context->num_nodes;261}262}263264STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)265{266int i;267268for (i=0; i < num_nodes-1; ++i)269nodes[i].next = &nodes[i+1];270nodes[i].next = NULL;271context->init_mode = STBRP__INIT_skyline;272context->heuristic = STBRP_HEURISTIC_Skyline_default;273context->free_head = &nodes[0];274context->active_head = &context->extra[0];275context->width = width;276context->height = height;277context->num_nodes = num_nodes;278stbrp_setup_allow_out_of_mem(context, 0);279280// node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)281context->extra[0].x = 0;282context->extra[0].y = 0;283context->extra[0].next = &context->extra[1];284context->extra[1].x = (stbrp_coord) width;285context->extra[1].y = (1<<30);286context->extra[1].next = NULL;287}288289// find minimum y position if it starts at x1290static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)291{292stbrp_node *node = first;293int x1 = x0 + width;294int min_y, visited_width, waste_area;295296STBRP__NOTUSED(c);297298STBRP_ASSERT(first->x <= x0);299300#if 0301// skip in case we're past the node302while (node->next->x <= x0)303++node;304#else305STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency306#endif307308STBRP_ASSERT(node->x <= x0);309310min_y = 0;311waste_area = 0;312visited_width = 0;313while (node->x < x1) {314if (node->y > min_y) {315// raise min_y higher.316// we've accounted for all waste up to min_y,317// but we'll now add more waste for everything we've visted318waste_area += visited_width * (node->y - min_y);319min_y = node->y;320// the first time through, visited_width might be reduced321if (node->x < x0)322visited_width += node->next->x - x0;323else324visited_width += node->next->x - node->x;325} else {326// add waste area327int under_width = node->next->x - node->x;328if (under_width + visited_width > width)329under_width = width - visited_width;330waste_area += under_width * (min_y - node->y);331visited_width += under_width;332}333node = node->next;334}335336*pwaste = waste_area;337return min_y;338}339340typedef struct341{342int x,y;343stbrp_node **prev_link;344} stbrp__findresult;345346static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)347{348int best_waste = (1<<30), best_x, best_y = (1 << 30);349stbrp__findresult fr;350stbrp_node **prev, *node, *tail, **best = NULL;351352// align to multiple of c->align353width = (width + c->align - 1);354width -= width % c->align;355STBRP_ASSERT(width % c->align == 0);356357// if it can't possibly fit, bail immediately358if (width > c->width || height > c->height) {359fr.prev_link = NULL;360fr.x = fr.y = 0;361return fr;362}363364node = c->active_head;365prev = &c->active_head;366while (node->x + width <= c->width) {367int y,waste;368y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);369if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL370// bottom left371if (y < best_y) {372best_y = y;373best = prev;374}375} else {376// best-fit377if (y + height <= c->height) {378// can only use it if it first vertically379if (y < best_y || (y == best_y && waste < best_waste)) {380best_y = y;381best_waste = waste;382best = prev;383}384}385}386prev = &node->next;387node = node->next;388}389390best_x = (best == NULL) ? 0 : (*best)->x;391392// if doing best-fit (BF), we also have to try aligning right edge to each node position393//394// e.g, if fitting395//396// ____________________397// |____________________|398//399// into400//401// | |402// | ____________|403// |____________|404//405// then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned406//407// This makes BF take about 2x the time408409if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {410tail = c->active_head;411node = c->active_head;412prev = &c->active_head;413// find first node that's admissible414while (tail->x < width)415tail = tail->next;416while (tail) {417int xpos = tail->x - width;418int y,waste;419STBRP_ASSERT(xpos >= 0);420// find the left position that matches this421while (node->next->x <= xpos) {422prev = &node->next;423node = node->next;424}425STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);426y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);427if (y + height <= c->height) {428if (y <= best_y) {429if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {430best_x = xpos;431//STBRP_ASSERT(y <= best_y); [DEAR IMGUI]432best_y = y;433best_waste = waste;434best = prev;435}436}437}438tail = tail->next;439}440}441442fr.prev_link = best;443fr.x = best_x;444fr.y = best_y;445return fr;446}447448static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)449{450// find best position according to heuristic451stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);452stbrp_node *node, *cur;453454// bail if:455// 1. it failed456// 2. the best node doesn't fit (we don't always check this)457// 3. we're out of memory458if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {459res.prev_link = NULL;460return res;461}462463// on success, create new node464node = context->free_head;465node->x = (stbrp_coord) res.x;466node->y = (stbrp_coord) (res.y + height);467468context->free_head = node->next;469470// insert the new node into the right starting point, and471// let 'cur' point to the remaining nodes needing to be472// stiched back in473474cur = *res.prev_link;475if (cur->x < res.x) {476// preserve the existing one, so start testing with the next one477stbrp_node *next = cur->next;478cur->next = node;479cur = next;480} else {481*res.prev_link = node;482}483484// from here, traverse cur and free the nodes, until we get to one485// that shouldn't be freed486while (cur->next && cur->next->x <= res.x + width) {487stbrp_node *next = cur->next;488// move the current node to the free list489cur->next = context->free_head;490context->free_head = cur;491cur = next;492}493494// stitch the list back in495node->next = cur;496497if (cur->x < res.x + width)498cur->x = (stbrp_coord) (res.x + width);499500#ifdef _DEBUG501cur = context->active_head;502while (cur->x < context->width) {503STBRP_ASSERT(cur->x < cur->next->x);504cur = cur->next;505}506STBRP_ASSERT(cur->next == NULL);507508{509int count=0;510cur = context->active_head;511while (cur) {512cur = cur->next;513++count;514}515cur = context->free_head;516while (cur) {517cur = cur->next;518++count;519}520STBRP_ASSERT(count == context->num_nodes+2);521}522#endif523524return res;525}526527static int STBRP__CDECL rect_height_compare(const void *a, const void *b)528{529const stbrp_rect *p = (const stbrp_rect *) a;530const stbrp_rect *q = (const stbrp_rect *) b;531if (p->h > q->h)532return -1;533if (p->h < q->h)534return 1;535return (p->w > q->w) ? -1 : (p->w < q->w);536}537538static int STBRP__CDECL rect_original_order(const void *a, const void *b)539{540const stbrp_rect *p = (const stbrp_rect *) a;541const stbrp_rect *q = (const stbrp_rect *) b;542return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);543}544545STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)546{547int i, all_rects_packed = 1;548549// we use the 'was_packed' field internally to allow sorting/unsorting550for (i=0; i < num_rects; ++i) {551rects[i].was_packed = i;552}553554// sort according to heuristic555STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);556557for (i=0; i < num_rects; ++i) {558if (rects[i].w == 0 || rects[i].h == 0) {559rects[i].x = rects[i].y = 0; // empty rect needs no space560} else {561stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);562if (fr.prev_link) {563rects[i].x = (stbrp_coord) fr.x;564rects[i].y = (stbrp_coord) fr.y;565} else {566rects[i].x = rects[i].y = STBRP__MAXVAL;567}568}569}570571// unsort572STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);573574// set was_packed flags and all_rects_packed status575for (i=0; i < num_rects; ++i) {576rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);577if (!rects[i].was_packed)578all_rects_packed = 0;579}580581// return the all_rects_packed status582return all_rects_packed;583}584#endif585586/*587------------------------------------------------------------------------------588This software is available under 2 licenses -- choose whichever you prefer.589------------------------------------------------------------------------------590ALTERNATIVE A - MIT License591Copyright (c) 2017 Sean Barrett592Permission is hereby granted, free of charge, to any person obtaining a copy of593this software and associated documentation files (the "Software"), to deal in594the Software without restriction, including without limitation the rights to595use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies596of the Software, and to permit persons to whom the Software is furnished to do597so, subject to the following conditions:598The above copyright notice and this permission notice shall be included in all599copies or substantial portions of the Software.600THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR601IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,602FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE603AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER604LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,605OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE606SOFTWARE.607------------------------------------------------------------------------------608ALTERNATIVE B - Public Domain (www.unlicense.org)609This is free and unencumbered software released into the public domain.610Anyone is free to copy, modify, publish, use, compile, sell, or distribute this611software, either in source code form or as a compiled binary, for any purpose,612commercial or non-commercial, and by any means.613In jurisdictions that recognize copyright laws, the author or authors of this614software dedicate any and all copyright interest in the software to the public615domain. We make this dedication for the benefit of the public at large and to616the detriment of our heirs and successors. We intend this dedication to be an617overt act of relinquishment in perpetuity of all present and future rights to618this software under copyright law.619THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR620IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,621FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE622AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN623ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION624WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.625------------------------------------------------------------------------------626*/627628629