File size: 1,813 Bytes
2edf277 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | // FCS Glass - src/core/atlas.cpp. See atlas.h.
#include "core/atlas.h"
namespace fcs {
namespace core {
ShelfPacker::ShelfPacker(int width, int max_height, int padding)
: width_(width < 1 ? 1 : width),
max_height_(max_height < 1 ? 1 : max_height),
padding_(padding < 0 ? 0 : padding) {}
void ShelfPacker::Reset() {
shelves_.clear();
next_y_ = 0;
}
void ShelfPacker::SetMaxHeight(int max_height) {
if (max_height > max_height_) max_height_ = max_height;
}
bool ShelfPacker::Pack(int w, int h, AtlasRect* out) {
if (out == nullptr) return false;
*out = AtlasRect();
if (w <= 0 || h <= 0) return true; // nothing to store
// Compare before adding the padding so a huge w cannot overflow.
if (w > width_ - 2 * padding_ || h > max_height_ - 2 * padding_) return false;
const int ow = w + 2 * padding_;
const int oh = h + 2 * padding_;
// Best fit: the shortest existing shelf that is tall enough and has room.
int best = -1;
for (int i = 0; i < static_cast<int>(shelves_.size()); ++i) {
const Shelf& s = shelves_[static_cast<size_t>(i)];
if (s.h >= oh && s.x + ow <= width_ &&
(best < 0 || s.h < shelves_[static_cast<size_t>(best)].h)) {
best = i;
}
}
int cell_x = 0;
int cell_y = 0;
if (best >= 0) {
Shelf& s = shelves_[static_cast<size_t>(best)];
cell_x = s.x;
cell_y = s.y;
s.x += ow;
} else {
if (next_y_ + oh > max_height_) return false;
Shelf s;
s.y = next_y_;
s.h = oh;
s.x = ow;
shelves_.push_back(s);
cell_x = 0;
cell_y = next_y_;
next_y_ += oh;
}
out->x = cell_x + padding_;
out->y = cell_y + padding_;
out->w = w;
out->h = h;
return true;
}
} // namespace core
} // namespace fcs
|