Path: blob/21.2-virgl/src/imgui/imstb_rectpack.h
4558 views
// [DEAR IMGUI]1// This is a slightly modified version of stb_rect_pack.h 0.99.2// Those changes would need to be pushed into nothings/stb:3// - Added STBRP__CDECL4// Grep for [DEAR IMGUI] to find the changes.56// stb_rect_pack.h - v0.99 - public domain - rectangle packing7// Sean Barrett 20148//9// Useful for e.g. packing rectangular textures into an atlas.10// Does not do rotation.11//12// Not necessarily the awesomest packing method, but better than13// the totally naive one in stb_truetype (which is primarily what14// this is meant to replace).15//16// Has only had a few tests run, may have issues.17//18// More docs to come.19//20// No memory allocations; uses qsort() and assert() from stdlib.21// Can override those by defining STBRP_SORT and STBRP_ASSERT.22//23// This library currently uses the Skyline Bottom-Left algorithm.24//25// Please note: better rectangle packers are welcome! Please26// implement them to the same API, but with a different init27// function.28//29// Credits30//31// Library32// Sean Barrett33// Minor features34// Martins Mozeiko35// github:IntellectualKitty36//37// Bugfixes / warning fixes38// Jeremy Jaussaud39//40// Version history:41//42// 0.99 (2019-02-07) warning fixes43// 0.11 (2017-03-03) return packing success/fail result44// 0.10 (2016-10-25) remove cast-away-const to avoid warnings45// 0.09 (2016-08-27) fix compiler warnings46// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)47// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)48// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort49// 0.05: added STBRP_ASSERT to allow replacing assert50// 0.04: fixed minor bug in STBRP_LARGE_RECTS support51// 0.01: initial release52//53// LICENSE54//55// See end of file for license information.5657//////////////////////////////////////////////////////////////////////////////58//59// INCLUDE SECTION60//6162#ifndef STB_INCLUDE_STB_RECT_PACK_H63#define STB_INCLUDE_STB_RECT_PACK_H6465#define STB_RECT_PACK_VERSION 16667#ifdef STBRP_STATIC68#define STBRP_DEF static69#else70#define STBRP_DEF extern71#endif7273#ifdef __cplusplus74extern "C" {75#endif7677typedef struct stbrp_context stbrp_context;78typedef struct stbrp_node stbrp_node;79typedef struct stbrp_rect stbrp_rect;8081#ifdef STBRP_LARGE_RECTS82typedef int stbrp_coord;83#else84typedef unsigned short stbrp_coord;85#endif8687STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);88// Assign packed locations to rectangles. The rectangles are of type89// 'stbrp_rect' defined below, stored in the array 'rects', and there90// are 'num_rects' many of them.91//92// Rectangles which are successfully packed have the 'was_packed' flag93// set to a non-zero value and 'x' and 'y' store the minimum location94// on each axis (i.e. bottom-left in cartesian coordinates, top-left95// if you imagine y increasing downwards). Rectangles which do not fit96// have the 'was_packed' flag set to 0.97//98// You should not try to access the 'rects' array from another thread99// while this function is running, as the function temporarily reorders100// the array while it executes.101//102// To pack into another rectangle, you need to call stbrp_init_target103// again. To continue packing into the same rectangle, you can call104// this function again. Calling this multiple times with multiple rect105// arrays will probably produce worse packing results than calling it106// a single time with the full rectangle array, but the option is107// available.108//109// The function returns 1 if all of the rectangles were successfully110// packed and 0 otherwise.111112struct stbrp_rect113{114// reserved for your use:115int id;116117// input:118stbrp_coord w, h;119120// output:121stbrp_coord x, y;122int was_packed; // non-zero if valid packing123124}; // 16 bytes, nominally125126127STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);128// Initialize a rectangle packer to:129// pack a rectangle that is 'width' by 'height' in dimensions130// using temporary storage provided by the array 'nodes', which is 'num_nodes' long131//132// You must call this function every time you start packing into a new target.133//134// There is no "shutdown" function. The 'nodes' memory must stay valid for135// the following stbrp_pack_rects() call (or calls), but can be freed after136// the call (or calls) finish.137//138// Note: to guarantee best results, either:139// 1. make sure 'num_nodes' >= 'width'140// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'141//142// If you don't do either of the above things, widths will be quantized to multiples143// of small integers to guarantee the algorithm doesn't run out of temporary storage.144//145// If you do #2, then the non-quantized algorithm will be used, but the algorithm146// may run out of temporary storage and be unable to pack some rectangles.147148STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);149// Optionally call this function after init but before doing any packing to150// change the handling of the out-of-temp-memory scenario, described above.151// If you call init again, this will be reset to the default (false).152153154STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);155// Optionally select which packing heuristic the library should use. Different156// heuristics will produce better/worse results for different data sets.157// If you call init again, this will be reset to the default.158159enum160{161STBRP_HEURISTIC_Skyline_default=0,162STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,163STBRP_HEURISTIC_Skyline_BF_sortHeight164};165166167//////////////////////////////////////////////////////////////////////////////168//169// the details of the following structures don't matter to you, but they must170// be visible so you can handle the memory allocations for them171172struct stbrp_node173{174stbrp_coord x,y;175stbrp_node *next;176};177178struct stbrp_context179{180int width;181int height;182int align;183int init_mode;184int heuristic;185int num_nodes;186stbrp_node *active_head;187stbrp_node *free_head;188stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'189};190191#ifdef __cplusplus192}193#endif194195#endif196197//////////////////////////////////////////////////////////////////////////////198//199// IMPLEMENTATION SECTION200//201202#ifdef STB_RECT_PACK_IMPLEMENTATION203#ifndef STBRP_SORT204#include <stdlib.h>205#define STBRP_SORT qsort206#endif207208#ifndef STBRP_ASSERT209#include <assert.h>210#define STBRP_ASSERT assert211#endif212213// [DEAR IMGUI] Added STBRP__CDECL214#ifdef _MSC_VER215#define STBRP__NOTUSED(v) (void)(v)216#define STBRP__CDECL __cdecl217#else218#define STBRP__NOTUSED(v) (void)sizeof(v)219#define STBRP__CDECL220#endif221222enum223{224STBRP__INIT_skyline = 1225};226227STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)228{229switch (context->init_mode) {230case STBRP__INIT_skyline:231STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);232context->heuristic = heuristic;233break;234default:235STBRP_ASSERT(0);236}237}238239STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)240{241if (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 though244// the rectangles easily fit). @TODO a smarter approach would be to only245// quantize once we've hit OOM, then we could get rid of this parameter.246context->align = 1;247else {248// if it's not ok to run out of memory, then quantize the widths249// so that num_nodes is always enough nodes.250//251// I.e. num_nodes * align >= width252// align >= width / num_nodes253// align = ceil(width/num_nodes)254255context->align = (context->width + context->num_nodes-1) / context->num_nodes;256}257}258259STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)260{261int i;262#ifndef STBRP_LARGE_RECTS263STBRP_ASSERT(width <= 0xffff && height <= 0xffff);264#endif265266for (i=0; i < num_nodes-1; ++i)267nodes[i].next = &nodes[i+1];268nodes[i].next = NULL;269context->init_mode = STBRP__INIT_skyline;270context->heuristic = STBRP_HEURISTIC_Skyline_default;271context->free_head = &nodes[0];272context->active_head = &context->extra[0];273context->width = width;274context->height = height;275context->num_nodes = num_nodes;276stbrp_setup_allow_out_of_mem(context, 0);277278// node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)279context->extra[0].x = 0;280context->extra[0].y = 0;281context->extra[0].next = &context->extra[1];282context->extra[1].x = (stbrp_coord) width;283#ifdef STBRP_LARGE_RECTS284context->extra[1].y = (1<<30);285#else286context->extra[1].y = 65535;287#endif288context->extra[1].next = NULL;289}290291// find minimum y position if it starts at x1292static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)293{294stbrp_node *node = first;295int x1 = x0 + width;296int min_y, visited_width, waste_area;297298STBRP__NOTUSED(c);299300STBRP_ASSERT(first->x <= x0);301302#if 0303// skip in case we're past the node304while (node->next->x <= x0)305++node;306#else307STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency308#endif309310STBRP_ASSERT(node->x <= x0);311312min_y = 0;313waste_area = 0;314visited_width = 0;315while (node->x < x1) {316if (node->y > min_y) {317// raise min_y higher.318// we've accounted for all waste up to min_y,319// but we'll now add more waste for everything we've visted320waste_area += visited_width * (node->y - min_y);321min_y = node->y;322// the first time through, visited_width might be reduced323if (node->x < x0)324visited_width += node->next->x - x0;325else326visited_width += node->next->x - node->x;327} else {328// add waste area329int under_width = node->next->x - node->x;330if (under_width + visited_width > width)331under_width = width - visited_width;332waste_area += under_width * (min_y - node->y);333visited_width += under_width;334}335node = node->next;336}337338*pwaste = waste_area;339return min_y;340}341342typedef struct343{344int x,y;345stbrp_node **prev_link;346} stbrp__findresult;347348static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)349{350int best_waste = (1<<30), best_x, best_y = (1 << 30);351stbrp__findresult fr;352stbrp_node **prev, *node, *tail, **best = NULL;353354// align to multiple of c->align355width = (width + c->align - 1);356width -= width % c->align;357STBRP_ASSERT(width % c->align == 0);358359node = c->active_head;360prev = &c->active_head;361while (node->x + width <= c->width) {362int y,waste;363y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);364if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL365// bottom left366if (y < best_y) {367best_y = y;368best = prev;369}370} else {371// best-fit372if (y + height <= c->height) {373// can only use it if it first vertically374if (y < best_y || (y == best_y && waste < best_waste)) {375best_y = y;376best_waste = waste;377best = prev;378}379}380}381prev = &node->next;382node = node->next;383}384385best_x = (best == NULL) ? 0 : (*best)->x;386387// if doing best-fit (BF), we also have to try aligning right edge to each node position388//389// e.g, if fitting390//391// ____________________392// |____________________|393//394// into395//396// | |397// | ____________|398// |____________|399//400// then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned401//402// This makes BF take about 2x the time403404if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {405tail = c->active_head;406node = c->active_head;407prev = &c->active_head;408// find first node that's admissible409while (tail->x < width)410tail = tail->next;411while (tail) {412int xpos = tail->x - width;413int y,waste;414STBRP_ASSERT(xpos >= 0);415// find the left position that matches this416while (node->next->x <= xpos) {417prev = &node->next;418node = node->next;419}420STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);421y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);422if (y + height < c->height) {423if (y <= best_y) {424if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {425best_x = xpos;426STBRP_ASSERT(y <= best_y);427best_y = y;428best_waste = waste;429best = prev;430}431}432}433tail = tail->next;434}435}436437fr.prev_link = best;438fr.x = best_x;439fr.y = best_y;440return fr;441}442443static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)444{445// find best position according to heuristic446stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);447stbrp_node *node, *cur;448449// bail if:450// 1. it failed451// 2. the best node doesn't fit (we don't always check this)452// 3. we're out of memory453if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {454res.prev_link = NULL;455return res;456}457458// on success, create new node459node = context->free_head;460node->x = (stbrp_coord) res.x;461node->y = (stbrp_coord) (res.y + height);462463context->free_head = node->next;464465// insert the new node into the right starting point, and466// let 'cur' point to the remaining nodes needing to be467// stiched back in468469cur = *res.prev_link;470if (cur->x < res.x) {471// preserve the existing one, so start testing with the next one472stbrp_node *next = cur->next;473cur->next = node;474cur = next;475} else {476*res.prev_link = node;477}478479// from here, traverse cur and free the nodes, until we get to one480// that shouldn't be freed481while (cur->next && cur->next->x <= res.x + width) {482stbrp_node *next = cur->next;483// move the current node to the free list484cur->next = context->free_head;485context->free_head = cur;486cur = next;487}488489// stitch the list back in490node->next = cur;491492if (cur->x < res.x + width)493cur->x = (stbrp_coord) (res.x + width);494495#ifdef _DEBUG496cur = context->active_head;497while (cur->x < context->width) {498STBRP_ASSERT(cur->x < cur->next->x);499cur = cur->next;500}501STBRP_ASSERT(cur->next == NULL);502503{504int count=0;505cur = context->active_head;506while (cur) {507cur = cur->next;508++count;509}510cur = context->free_head;511while (cur) {512cur = cur->next;513++count;514}515STBRP_ASSERT(count == context->num_nodes+2);516}517#endif518519return res;520}521522// [DEAR IMGUI] Added STBRP__CDECL523static int STBRP__CDECL rect_height_compare(const void *a, const void *b)524{525const stbrp_rect *p = (const stbrp_rect *) a;526const stbrp_rect *q = (const stbrp_rect *) b;527if (p->h > q->h)528return -1;529if (p->h < q->h)530return 1;531return (p->w > q->w) ? -1 : (p->w < q->w);532}533534// [DEAR IMGUI] Added STBRP__CDECL535static int STBRP__CDECL rect_original_order(const void *a, const void *b)536{537const stbrp_rect *p = (const stbrp_rect *) a;538const stbrp_rect *q = (const stbrp_rect *) b;539return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);540}541542#ifdef STBRP_LARGE_RECTS543#define STBRP__MAXVAL 0xffffffff544#else545#define STBRP__MAXVAL 0xffff546#endif547548STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)549{550int i, all_rects_packed = 1;551552// we use the 'was_packed' field internally to allow sorting/unsorting553for (i=0; i < num_rects; ++i) {554rects[i].was_packed = i;555}556557// sort according to heuristic558STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);559560for (i=0; i < num_rects; ++i) {561if (rects[i].w == 0 || rects[i].h == 0) {562rects[i].x = rects[i].y = 0; // empty rect needs no space563} else {564stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);565if (fr.prev_link) {566rects[i].x = (stbrp_coord) fr.x;567rects[i].y = (stbrp_coord) fr.y;568} else {569rects[i].x = rects[i].y = STBRP__MAXVAL;570}571}572}573574// unsort575STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);576577// set was_packed flags and all_rects_packed status578for (i=0; i < num_rects; ++i) {579rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);580if (!rects[i].was_packed)581all_rects_packed = 0;582}583584// return the all_rects_packed status585return all_rects_packed;586}587#endif588589/*590------------------------------------------------------------------------------591This software is available under 2 licenses -- choose whichever you prefer.592------------------------------------------------------------------------------593ALTERNATIVE A - MIT License594Copyright (c) 2017 Sean Barrett595Permission is hereby granted, free of charge, to any person obtaining a copy of596this software and associated documentation files (the "Software"), to deal in597the Software without restriction, including without limitation the rights to598use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies599of the Software, and to permit persons to whom the Software is furnished to do600so, subject to the following conditions:601The above copyright notice and this permission notice shall be included in all602copies or substantial portions of the Software.603THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR604IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,605FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE606AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER607LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,608OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE609SOFTWARE.610------------------------------------------------------------------------------611ALTERNATIVE B - Public Domain (www.unlicense.org)612This is free and unencumbered software released into the public domain.613Anyone is free to copy, modify, publish, use, compile, sell, or distribute this614software, either in source code form or as a compiled binary, for any purpose,615commercial or non-commercial, and by any means.616In jurisdictions that recognize copyright laws, the author or authors of this617software dedicate any and all copyright interest in the software to the public618domain. We make this dedication for the benefit of the public at large and to619the detriment of our heirs and successors. We intend this dedication to be an620overt act of relinquishment in perpetuity of all present and future rights to621this software under copyright law.622THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR623IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,624FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE625AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN626ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION627WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.628------------------------------------------------------------------------------629*/630631632