Open Source Tomb Raider Engine
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

stb_rect_pack.h 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. // stb_rect_pack.h - v0.05 - 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. // 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).
  10. //
  11. // Has only had a few tests run, may have issues.
  12. //
  13. // More docs to come.
  14. //
  15. // No memory allocations; uses qsort() and assert() from stdlib.
  16. //
  17. // This library currently uses the Skyline Bottom-Left algorithm.
  18. //
  19. // Please note: better rectangle packers are welcome! Please
  20. // implement them to the same API, but with a different init
  21. // function.
  22. //
  23. // Version history:
  24. //
  25. // 0.05: added STBRP_ASSERT to allow replacing assert
  26. // 0.04: fixed minor bug in STBRP_LARGE_RECTS support
  27. // 0.01: initial release
  28. //////////////////////////////////////////////////////////////////////////////
  29. //
  30. // INCLUDE SECTION
  31. //
  32. #ifndef STB_INCLUDE_STB_RECT_PACK_H
  33. #define STB_INCLUDE_STB_RECT_PACK_H
  34. #define STB_RECT_PACK_VERSION 1
  35. #ifdef STBRP_STATIC
  36. #define STBRP_DEF static
  37. #else
  38. #define STBRP_DEF extern
  39. #endif
  40. #ifdef __cplusplus
  41. extern "C" {
  42. #endif
  43. typedef struct stbrp_context stbrp_context;
  44. typedef struct stbrp_node stbrp_node;
  45. typedef struct stbrp_rect stbrp_rect;
  46. #ifdef STBRP_LARGE_RECTS
  47. typedef int stbrp_coord;
  48. #else
  49. typedef unsigned short stbrp_coord;
  50. #endif
  51. STBRP_DEF void stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
  52. // Assign packed locations to rectangles. The rectangles are of type
  53. // 'stbrp_rect' defined below, stored in the array 'rects', and there
  54. // are 'num_rects' many of them.
  55. //
  56. // Rectangles which are successfully packed have the 'was_packed' flag
  57. // set to a non-zero value and 'x' and 'y' store the minimum location
  58. // on each axis (i.e. bottom-left in cartesian coordinates, top-left
  59. // if you imagine y increasing downwards). Rectangles which do not fit
  60. // have the 'was_packed' flag set to 0.
  61. //
  62. // You should not try to access the 'rects' array from another thread
  63. // while this function is running, as the function temporarily reorders
  64. // the array while it executes.
  65. //
  66. // To pack into another rectangle, you need to call stbrp_init_target
  67. // again. To continue packing into the same rectangle, you can call
  68. // this function again. Calling this multiple times with multiple rect
  69. // arrays will probably produce worse packing results than calling it
  70. // a single time with the full rectangle array, but the option is
  71. // available.
  72. struct stbrp_rect
  73. {
  74. // reserved for your use:
  75. int id;
  76. // input:
  77. stbrp_coord w, h;
  78. // output:
  79. stbrp_coord x, y;
  80. int was_packed; // non-zero if valid packing
  81. }; // 16 bytes, nominally
  82. STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
  83. // Initialize a rectangle packer to:
  84. // pack a rectangle that is 'width' by 'height' in dimensions
  85. // using temporary storage provided by the array 'nodes', which is 'num_nodes' long
  86. //
  87. // You must call this function every time you start packing into a new target.
  88. //
  89. // There is no "shutdown" function. The 'nodes' memory must stay valid for
  90. // the following stbrp_pack_rects() call (or calls), but can be freed after
  91. // the call (or calls) finish.
  92. //
  93. // Note: to guarantee best results, either:
  94. // 1. make sure 'num_nodes' >= 'width'
  95. // or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
  96. //
  97. // If you don't do either of the above things, widths will be quantized to multiples
  98. // of small integers to guarantee the algorithm doesn't run out of temporary storage.
  99. //
  100. // If you do #2, then the non-quantized algorithm will be used, but the algorithm
  101. // may run out of temporary storage and be unable to pack some rectangles.
  102. STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
  103. // Optionally call this function after init but before doing any packing to
  104. // change the handling of the out-of-temp-memory scenario, described above.
  105. // If you call init again, this will be reset to the default (false).
  106. STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
  107. // Optionally select which packing heuristic the library should use. Different
  108. // heuristics will produce better/worse results for different data sets.
  109. // If you call init again, this will be reset to the default.
  110. enum
  111. {
  112. STBRP_HEURISTIC_Skyline_default=0,
  113. STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
  114. STBRP_HEURISTIC_Skyline_BF_sortHeight,
  115. };
  116. //////////////////////////////////////////////////////////////////////////////
  117. //
  118. // the details of the following structures don't matter to you, but they must
  119. // be visible so you can handle the memory allocations for them
  120. struct stbrp_node
  121. {
  122. stbrp_coord x,y;
  123. stbrp_node *next;
  124. };
  125. struct stbrp_context
  126. {
  127. int width;
  128. int height;
  129. int align;
  130. int init_mode;
  131. int heuristic;
  132. int num_nodes;
  133. stbrp_node *active_head;
  134. stbrp_node *free_head;
  135. stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
  136. };
  137. #ifdef __cplusplus
  138. }
  139. #endif
  140. #endif
  141. //////////////////////////////////////////////////////////////////////////////
  142. //
  143. // IMPLEMENTATION SECTION
  144. //
  145. #ifdef STB_RECT_PACK_IMPLEMENTATION
  146. #include <stdlib.h>
  147. #ifndef STBRP_ASSERT
  148. #include <assert.h>
  149. #define STBRP_ASSERT assert
  150. #endif
  151. enum
  152. {
  153. STBRP__INIT_skyline = 1,
  154. };
  155. STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
  156. {
  157. switch (context->init_mode) {
  158. case STBRP__INIT_skyline:
  159. STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
  160. context->heuristic = heuristic;
  161. break;
  162. default:
  163. STBRP_ASSERT(0);
  164. }
  165. }
  166. STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
  167. {
  168. if (allow_out_of_mem)
  169. // if it's ok to run out of memory, then don't bother aligning them;
  170. // this gives better packing, but may fail due to OOM (even though
  171. // the rectangles easily fit). @TODO a smarter approach would be to only
  172. // quantize once we've hit OOM, then we could get rid of this parameter.
  173. context->align = 1;
  174. else {
  175. // if it's not ok to run out of memory, then quantize the widths
  176. // so that num_nodes is always enough nodes.
  177. //
  178. // I.e. num_nodes * align >= width
  179. // align >= width / num_nodes
  180. // align = ceil(width/num_nodes)
  181. context->align = (context->width + context->num_nodes-1) / context->num_nodes;
  182. }
  183. }
  184. STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
  185. {
  186. int i;
  187. #ifndef STBRP_LARGE_RECTS
  188. STBRP_ASSERT(width <= 0xffff && height <= 0xffff);
  189. #endif
  190. for (i=0; i < num_nodes-1; ++i)
  191. nodes[i].next = &nodes[i+1];
  192. nodes[i].next = NULL;
  193. context->init_mode = STBRP__INIT_skyline;
  194. context->heuristic = STBRP_HEURISTIC_Skyline_default;
  195. context->free_head = &nodes[0];
  196. context->active_head = &context->extra[0];
  197. context->width = width;
  198. context->height = height;
  199. context->num_nodes = num_nodes;
  200. stbrp_setup_allow_out_of_mem(context, 0);
  201. // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
  202. context->extra[0].x = 0;
  203. context->extra[0].y = 0;
  204. context->extra[0].next = &context->extra[1];
  205. context->extra[1].x = (stbrp_coord) width;
  206. #ifdef STBRP_LARGE_RECTS
  207. context->extra[1].y = (1<<30);
  208. #else
  209. context->extra[1].y = 65535;
  210. #endif
  211. context->extra[1].next = NULL;
  212. }
  213. // find minimum y position if it starts at x1
  214. static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
  215. {
  216. stbrp_node *node = first;
  217. int x1 = x0 + width;
  218. int min_y, visited_width, waste_area;
  219. STBRP_ASSERT(first->x <= x0);
  220. #if 0
  221. // skip in case we're past the node
  222. while (node->next->x <= x0)
  223. ++node;
  224. #else
  225. STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
  226. #endif
  227. STBRP_ASSERT(node->x <= x0);
  228. min_y = 0;
  229. waste_area = 0;
  230. visited_width = 0;
  231. while (node->x < x1) {
  232. if (node->y > min_y) {
  233. // raise min_y higher.
  234. // we've accounted for all waste up to min_y,
  235. // but we'll now add more waste for everything we've visted
  236. waste_area += visited_width * (node->y - min_y);
  237. min_y = node->y;
  238. // the first time through, visited_width might be reduced
  239. if (node->x < x0)
  240. visited_width += node->next->x - x0;
  241. else
  242. visited_width += node->next->x - node->x;
  243. } else {
  244. // add waste area
  245. int under_width = node->next->x - node->x;
  246. if (under_width + visited_width > width)
  247. under_width = width - visited_width;
  248. waste_area += under_width * (min_y - node->y);
  249. visited_width += under_width;
  250. }
  251. node = node->next;
  252. }
  253. *pwaste = waste_area;
  254. return min_y;
  255. }
  256. typedef struct
  257. {
  258. int x,y;
  259. stbrp_node **prev_link;
  260. } stbrp__findresult;
  261. static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
  262. {
  263. int best_waste = (1<<30), best_x, best_y = (1 << 30);
  264. stbrp__findresult fr;
  265. stbrp_node **prev, *node, *tail, **best = NULL;
  266. // align to multiple of c->align
  267. width = (width + c->align - 1);
  268. width -= width % c->align;
  269. STBRP_ASSERT(width % c->align == 0);
  270. node = c->active_head;
  271. prev = &c->active_head;
  272. while (node->x + width <= c->width) {
  273. int y,waste;
  274. y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
  275. if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
  276. // bottom left
  277. if (y < best_y) {
  278. best_y = y;
  279. best = prev;
  280. }
  281. } else {
  282. // best-fit
  283. if (y + height <= c->height) {
  284. // can only use it if it first vertically
  285. if (y < best_y || (y == best_y && waste < best_waste)) {
  286. best_y = y;
  287. best_waste = waste;
  288. best = prev;
  289. }
  290. }
  291. }
  292. prev = &node->next;
  293. node = node->next;
  294. }
  295. best_x = (best == NULL) ? 0 : (*best)->x;
  296. // if doing best-fit (BF), we also have to try aligning right edge to each node position
  297. //
  298. // e.g, if fitting
  299. //
  300. // ____________________
  301. // |____________________|
  302. //
  303. // into
  304. //
  305. // | |
  306. // | ____________|
  307. // |____________|
  308. //
  309. // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
  310. //
  311. // This makes BF take about 2x the time
  312. if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
  313. tail = c->active_head;
  314. node = c->active_head;
  315. prev = &c->active_head;
  316. // find first node that's admissible
  317. while (tail->x < width)
  318. tail = tail->next;
  319. while (tail) {
  320. int xpos = tail->x - width;
  321. int y,waste;
  322. STBRP_ASSERT(xpos >= 0);
  323. // find the left position that matches this
  324. while (node->next->x <= xpos) {
  325. prev = &node->next;
  326. node = node->next;
  327. }
  328. STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
  329. y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
  330. if (y + height < c->height) {
  331. if (y <= best_y) {
  332. if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
  333. best_x = xpos;
  334. STBRP_ASSERT(y <= best_y);
  335. best_y = y;
  336. best_waste = waste;
  337. best = prev;
  338. }
  339. }
  340. }
  341. tail = tail->next;
  342. }
  343. }
  344. fr.prev_link = best;
  345. fr.x = best_x;
  346. fr.y = best_y;
  347. return fr;
  348. }
  349. static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
  350. {
  351. // find best position according to heuristic
  352. stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
  353. stbrp_node *node, *cur;
  354. // bail if:
  355. // 1. it failed
  356. // 2. the best node doesn't fit (we don't always check this)
  357. // 3. we're out of memory
  358. if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
  359. res.prev_link = NULL;
  360. return res;
  361. }
  362. // on success, create new node
  363. node = context->free_head;
  364. node->x = (stbrp_coord) res.x;
  365. node->y = (stbrp_coord) (res.y + height);
  366. context->free_head = node->next;
  367. // insert the new node into the right starting point, and
  368. // let 'cur' point to the remaining nodes needing to be
  369. // stiched back in
  370. cur = *res.prev_link;
  371. if (cur->x < res.x) {
  372. // preserve the existing one, so start testing with the next one
  373. stbrp_node *next = cur->next;
  374. cur->next = node;
  375. cur = next;
  376. } else {
  377. *res.prev_link = node;
  378. }
  379. // from here, traverse cur and free the nodes, until we get to one
  380. // that shouldn't be freed
  381. while (cur->next && cur->next->x <= res.x + width) {
  382. stbrp_node *next = cur->next;
  383. // move the current node to the free list
  384. cur->next = context->free_head;
  385. context->free_head = cur;
  386. cur = next;
  387. }
  388. // stitch the list back in
  389. node->next = cur;
  390. if (cur->x < res.x + width)
  391. cur->x = (stbrp_coord) (res.x + width);
  392. #ifdef _DEBUG
  393. cur = context->active_head;
  394. while (cur->x < context->width) {
  395. STBRP_ASSERT(cur->x < cur->next->x);
  396. cur = cur->next;
  397. }
  398. STBRP_ASSERT(cur->next == NULL);
  399. {
  400. stbrp_node *L1 = NULL, *L2 = NULL;
  401. int count=0;
  402. cur = context->active_head;
  403. while (cur) {
  404. L1 = cur;
  405. cur = cur->next;
  406. ++count;
  407. }
  408. cur = context->free_head;
  409. while (cur) {
  410. L2 = cur;
  411. cur = cur->next;
  412. ++count;
  413. }
  414. STBRP_ASSERT(count == context->num_nodes+2);
  415. }
  416. #endif
  417. return res;
  418. }
  419. static int rect_height_compare(const void *a, const void *b)
  420. {
  421. stbrp_rect *p = (stbrp_rect *) a;
  422. stbrp_rect *q = (stbrp_rect *) b;
  423. if (p->h > q->h)
  424. return -1;
  425. if (p->h < q->h)
  426. return 1;
  427. return (p->w > q->w) ? -1 : (p->w < q->w);
  428. }
  429. static int rect_width_compare(const void *a, const void *b)
  430. {
  431. stbrp_rect *p = (stbrp_rect *) a;
  432. stbrp_rect *q = (stbrp_rect *) b;
  433. if (p->w > q->w)
  434. return -1;
  435. if (p->w < q->w)
  436. return 1;
  437. return (p->h > q->h) ? -1 : (p->h < q->h);
  438. }
  439. static int rect_original_order(const void *a, const void *b)
  440. {
  441. stbrp_rect *p = (stbrp_rect *) a;
  442. stbrp_rect *q = (stbrp_rect *) b;
  443. return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
  444. }
  445. #ifdef STBRP_LARGE_RECTS
  446. #define STBRP__MAXVAL 0xffffffff
  447. #else
  448. #define STBRP__MAXVAL 0xffff
  449. #endif
  450. STBRP_DEF void stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
  451. {
  452. int i;
  453. // we use the 'was_packed' field internally to allow sorting/unsorting
  454. for (i=0; i < num_rects; ++i) {
  455. rects[i].was_packed = i;
  456. #ifndef STBRP_LARGE_RECTS
  457. STBRP_ASSERT(rects[i].w <= 0xffff && rects[i].h <= 0xffff);
  458. #endif
  459. }
  460. // sort according to heuristic
  461. qsort(rects, num_rects, sizeof(rects[0]), rect_height_compare);
  462. for (i=0; i < num_rects; ++i) {
  463. stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
  464. if (fr.prev_link) {
  465. rects[i].x = (stbrp_coord) fr.x;
  466. rects[i].y = (stbrp_coord) fr.y;
  467. } else {
  468. rects[i].x = rects[i].y = STBRP__MAXVAL;
  469. }
  470. }
  471. // unsort
  472. qsort(rects, num_rects, sizeof(rects[0]), rect_original_order);
  473. // set was_packed flags
  474. for (i=0; i < num_rects; ++i)
  475. rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
  476. }
  477. #endif