Euphoria
pack.cc
Go to the documentation of this file.
1 #include "core/pack.h"
2 
3 #include "base/cint.h"
4 
5 #include "stb_rect_pack.h"
6 
7 #ifndef STBRP_LARGE_RECTS
8 #error int is not available in stb rect packing
9 #endif
10 
11 
12 namespace eu::core
13 {
14  std::vector<std::optional<Recti>>
16  (
17  const size2i& container,
18  const std::vector<size2i>& to_pack
19  )
20  {
21  //init data
22  const int num_rects = c_sizet_to_int(to_pack.size());
23  auto packed_rects = std::vector<stbrp_rect>(num_rects);
24  {
25  int index = 0;
26  for(const auto s: to_pack)
27  {
28  auto& r = packed_rects[index];
29 
30  r.id = index;
31  r.w = s.width;
32  r.h = s.height;
33 
34  index +=1;
35  }
36  }
37 
38  // call stb pack
39  // documentation:
40  // to guarantee best results: make sure 'num_nodes' >= 'width'
41  const int num_nodes = container.width;
42  auto context = stbrp_context{};
43  auto nodes = std::vector<stbrp_node>(num_nodes);
44  stbrp_init_target
45  (
46  &context,
47  container.width,
48  container.height,
49  nodes.data(),
50  num_nodes
51  );
52  stbrp_pack_rects(&context, packed_rects.data(), num_rects);
53 
54  // get and return data
55  auto ret = std::vector<std::optional<Recti>>(to_pack.size());
56  for(int rect_index = 0; rect_index < num_rects; ++rect_index)
57  {
58  const stbrp_rect& rect = packed_rects[rect_index];
59  if(rect.was_packed == 0)
60  {
61  continue;
62  }
63  ret[rect_index] = Recti::from_top_left_width_height
64  (
65  vec2i{rect.x, container.height - rect.y - 1},
66  rect.w,
67  rect.h
68  );
69  }
70 
71  return ret;
72  }
73 }
74 
std::vector< std::optional< Recti > > pack(const size2i &container, const std::vector< size2i > &to_pack)
Definition: pack.cc:16
int c_sizet_to_int(size_t t)
Definition: cint.cc:11
static Recti from_top_left_width_height(const vec2i &topleft, int width, int height)
Definition: rect.cc:561
int width
Definition: size2.h:36
int height
Definition: size2.h:37
Definition: vec2.h:72
int x
Definition: vec2.h:73
UiText * nodes
Definition: ui_text.cc:132