File size: 2,238 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
71
72
73
74
75
76
77
// FCS Glass - src/core/glyph_cache.cpp. See glyph_cache.h.

#include "core/glyph_cache.h"

#include <cmath>

namespace fcs {
namespace core {

namespace {

std::uint16_t QuantizeTo16(double v, double step) {
  if (!(v > 0.0)) return 1;                       // also catches NaN
  const double q = std::floor(v * step + 0.5);    // round half up
  if (q < 1.0) return 1;
  if (q > 65535.0) return 65535;
  return static_cast<std::uint16_t>(q);
}

// Order-dependent mix, so (face=1, glyph=2) and (face=2, glyph=1) differ. A plain xor of
// the fields would collide on exactly that swap, which is the likeliest real collision.
std::uint64_t Mix(std::uint64_t h, std::uint64_t v) {
  h ^= v + 0x9e3779b97f4a7c15ULL + (h << 6) + (h >> 2);
  h *= 0xff51afd7ed558ccdULL;
  h ^= h >> 33;
  return h;
}

}  // namespace

std::uint16_t QuantizeEm(double em_dp) { return QuantizeTo16(em_dp, 16.0); }
std::uint16_t QuantizeScale(double scale) { return QuantizeTo16(scale, 256.0); }

std::size_t GlyphKeyHash::operator()(const GlyphKey& k) const {
  std::uint64_t h = 1469598103934665603ULL;
  h = Mix(h, k.face);
  h = Mix(h, k.glyph);
  h = Mix(h, k.em_q);
  h = Mix(h, k.scale_q);
  h = Mix(h, k.subpx);
  return static_cast<std::size_t>(h);
}

GlyphCache::GlyphCache(int atlas_width, int atlas_height, int padding)
    : packer_(atlas_width, atlas_height, padding) {}

const GlyphSlot* GlyphCache::Find(const GlyphKey& key) const {
  const auto it = map_.find(key);
  return it == map_.end() ? nullptr : &it->second;
}

const GlyphSlot* GlyphCache::Insert(const GlyphKey& key, int w, int h, int bearing_x,

                                    int bearing_y, int advance_px) {
  const auto existing = map_.find(key);
  if (existing != map_.end()) return &existing->second;

  GlyphSlot slot;
  if (!packer_.Pack(w, h, &slot.rect)) {
    overflowed_ = true;
    return nullptr;
  }
  slot.bearing_x = bearing_x;
  slot.bearing_y = bearing_y;
  slot.advance_px = advance_px;
  return &map_.emplace(key, slot).first->second;
}

void GlyphCache::Flush() {
  map_.clear();
  packer_.Reset();
  overflowed_ = false;
  ++generation_;
}

}  // namespace core
}  // namespace fcs