Team Fortress 2 Source Code as on 22/4/2020
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.

624 lines
20 KiB

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