Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qtextureglyphcache.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include <qmath.h>
6
8#include "private/qfontengine_p.h"
9#include "private/qnumeric_p.h"
10
11#include <QtGui/qpainterpath.h>
12
14
15// #define CACHE_DEBUG
16
17// out-of-line to avoid vtable duplication, breaking e.g. RTTI
18QTextureGlyphCache::~QTextureGlyphCache()
19{
20}
21
22int QTextureGlyphCache::calculateSubPixelPositionCount(glyph_t glyph) const
23{
24 // Test 12 different subpixel positions since it factors into 3*4 so it gives
25 // the coverage we need.
26
27 const int NumSubpixelPositions = 12;
28
29 QImage images[NumSubpixelPositions];
30 int numImages = 0;
31 for (int i = 0; i < NumSubpixelPositions; ++i) {
32 QImage img = textureMapForGlyph(glyph, QFixedPoint(QFixed::fromReal(i / 12.0), 0));
33
34 if (numImages == 0) {
35 QPainterPath path;
36 QFixedPoint point;
37 m_current_fontengine->addGlyphsToPath(&glyph, &point, 1, &path, QTextItem::RenderFlags());
38
39 // Glyph is space, return 0 to indicate that we need to keep trying
40 if (path.isEmpty())
41 break;
42
43 images[numImages++] = std::move(img);
44 } else {
45 bool found = false;
46 for (int j = 0; j < numImages; ++j) {
47 if (images[j] == img) {
48 found = true;
49 break;
50 }
51 }
52 if (!found)
53 images[numImages++] = std::move(img);
54 }
55 }
56
57 return numImages;
58}
59
60bool QTextureGlyphCache::populate(QFontEngine *fontEngine,
61 qsizetype numGlyphs,
62 const glyph_t *glyphs,
63 const QFixedPoint *positions,
64 QPainter::RenderHints renderHints,
65 bool includeGlyphCacheScale)
66{
67#ifdef CACHE_DEBUG
68 printf("Populating with %lld glyphs\n", static_cast<long long>(numGlyphs));
69 qDebug() << " -> current transformation: " << m_transform;
70#endif
71
72 m_current_fontengine = fontEngine;
73 const int padding = glyphPadding();
74 const int paddingDoubled = padding * 2;
75
76 bool supportsSubPixelPositions = fontEngine->supportsSubPixelPositions();
77 bool verticalSubPixelPositions = fontEngine->supportsVerticalSubPixelPositions()
78 && (renderHints & QPainter::VerticalSubpixelPositioning) != 0;
79 if (fontEngine->m_subPixelPositionCount == 0) {
80 if (!supportsSubPixelPositions) {
81 fontEngine->m_subPixelPositionCount = 1;
82 } else {
83 qsizetype i = 0;
84 while (fontEngine->m_subPixelPositionCount == 0 && i < numGlyphs)
85 fontEngine->m_subPixelPositionCount = calculateSubPixelPositionCount(glyphs[i++]);
86 }
87 }
88
89 if (m_cx == 0 && m_cy == 0) {
90 m_cx = padding;
91 m_cy = padding;
92 }
93
94 qreal glyphCacheScaleX = transform().m11();
95 qreal glyphCacheScaleY = transform().m22();
96
97 QHash<GlyphAndSubPixelPosition, Coord> listItemCoordinates;
98 int rowHeight = 0;
99
100 // check each glyph for its metrics and get the required rowHeight.
101 for (qsizetype i = 0; i < numGlyphs; ++i) {
102 const glyph_t glyph = glyphs[i];
103
104 QFixedPoint subPixelPosition;
105 if (supportsSubPixelPositions) {
106 QFixedPoint pos = positions != nullptr ? positions[i] : QFixedPoint();
107 if (includeGlyphCacheScale) {
108 pos = QFixedPoint(QFixed::fromReal(pos.x.toReal() * glyphCacheScaleX),
109 QFixed::fromReal(pos.y.toReal() * glyphCacheScaleY));
110 }
111 subPixelPosition = fontEngine->subPixelPositionFor(pos);
112 if (!verticalSubPixelPositions)
113 subPixelPosition.y = 0;
114 }
115
116 if (coords.contains(GlyphAndSubPixelPosition(glyph, subPixelPosition)))
117 continue;
118 if (listItemCoordinates.contains(GlyphAndSubPixelPosition(glyph, subPixelPosition)))
119 continue;
120
121 glyph_metrics_t metrics = fontEngine->alphaMapBoundingBox(glyph, subPixelPosition, m_transform, m_format);
122
123#ifdef CACHE_DEBUG
124 printf("(%4x): w=%.2f, h=%.2f, xoff=%.2f, yoff=%.2f, x=%.2f, y=%.2f\n",
125 glyph,
126 metrics.width.toReal(),
127 metrics.height.toReal(),
128 metrics.xoff.toReal(),
129 metrics.yoff.toReal(),
130 metrics.x.toReal(),
131 metrics.y.toReal());
132#endif
133 GlyphAndSubPixelPosition key(glyph, subPixelPosition);
134 int glyph_width = metrics.width.ceil().toInt();
135 int glyph_height = metrics.height.ceil().toInt();
136 if (glyph_height == 0 || glyph_width == 0
137 || QFontEngine::glyphBoundingBoxExceedsLimit(
138 metrics.width.toReal(), metrics.height.toReal(),
139 fontEngine->effectivePixelSizeSquared(m_transform))) {
140 // Avoid multiple calls to boundingBox() for non-printable or oversized glyphs
141 Coord c = { 0, 0, 0, 0, 0, 0 };
142 coords.insert(key, c);
143 continue;
144 }
145 // align to 8-bit boundary
146 if (m_format == QFontEngine::Format_Mono)
147 glyph_width = (glyph_width+7)&~7;
148
149 Coord c = { 0, 0, // will be filled in later
150 glyph_width,
151 glyph_height, // texture coords
152 metrics.x.truncate(),
153 -metrics.y.truncate() }; // baseline for horizontal scripts
154
155 listItemCoordinates.insert(key, c);
156 rowHeight = qMax(rowHeight, glyph_height);
157 }
158 if (listItemCoordinates.isEmpty())
159 return true;
160
161 rowHeight += paddingDoubled;
162
163 if (m_w == 0) {
164 if (fontEngine->maxCharWidth() <= QT_DEFAULT_TEXTURE_GLYPH_CACHE_WIDTH)
166 else
167 m_w = qNextPowerOfTwo(qCeil(fontEngine->maxCharWidth()) - 1);
168 }
169
170 // now actually use the coords and paint the wanted glyps into cache.
171 QHash<GlyphAndSubPixelPosition, Coord>::iterator iter = listItemCoordinates.begin();
172 int requiredWidth = m_w;
173 while (iter != listItemCoordinates.end()) {
174 Coord c = iter.value();
175
176 m_currentRowHeight = qMax(m_currentRowHeight, c.h);
177
178 if (m_cx + c.w + padding > requiredWidth) {
179 int new_width = requiredWidth*2;
180 while (new_width < m_cx + c.w + padding)
181 new_width *= 2;
182 if (new_width <= maxTextureWidth()) {
183 requiredWidth = new_width;
184 } else {
185 // no room on the current line, start new glyph strip
186 m_cx = padding;
187 m_cy += m_currentRowHeight + paddingDoubled;
188 m_currentRowHeight = c.h; // New row
189 }
190 }
191
192 if (maxTextureHeight() > 0 && m_cy + c.h + padding > maxTextureHeight()) {
193 // We can't make a cache of the required size, so we bail out
194 return false;
195 }
196
197 c.x = m_cx;
198 c.y = m_cy;
199
200 coords.insert(iter.key(), c);
201 m_pendingGlyphs.insert(iter.key(), c);
202
203 m_cx += c.w + paddingDoubled;
204 ++iter;
205 }
206 return true;
207
208}
209
210void QTextureGlyphCache::fillInPendingGlyphs()
211{
212 if (!hasPendingGlyphs())
213 return;
214
215 int requiredHeight = m_h;
216 int requiredWidth = m_w; // Use a minimum size to avoid a lot of initial reallocations
217 const int padding = glyphPadding();
218 {
219 QHash<GlyphAndSubPixelPosition, Coord>::iterator iter = m_pendingGlyphs.begin();
220 while (iter != m_pendingGlyphs.end()) {
221 Coord c = iter.value();
222 requiredHeight = qMax(requiredHeight, c.y + c.h + padding);
223 requiredWidth = qMax(requiredWidth, c.x + c.w + padding);
224 ++iter;
225 }
226 }
227
228 if (isNull() || requiredHeight > m_h || requiredWidth > m_w) {
229 if (isNull())
230 createCache(qNextPowerOfTwo(requiredWidth - 1), qNextPowerOfTwo(requiredHeight - 1));
231 else
232 resizeCache(qNextPowerOfTwo(requiredWidth - 1), qNextPowerOfTwo(requiredHeight - 1));
233 }
234
235 beginFillTexture();
236 {
237 QHash<GlyphAndSubPixelPosition, Coord>::iterator iter = m_pendingGlyphs.begin();
238 while (iter != m_pendingGlyphs.end()) {
239 GlyphAndSubPixelPosition key = iter.key();
240 fillTexture(iter.value(), key.glyph, key.subPixelPosition);
241
242 ++iter;
243 }
244 }
245 endFillTexture();
246
247 m_pendingGlyphs.clear();
248}
249
250QImage QTextureGlyphCache::textureMapForGlyph(glyph_t g, const QFixedPoint &subPixelPosition) const
251{
252 switch (m_format) {
253 case QFontEngine::Format_A32:
254 return m_current_fontengine->alphaRGBMapForGlyph(g, subPixelPosition, m_transform);
255 case QFontEngine::Format_ARGB:
256 return m_current_fontengine->bitmapForGlyph(g, subPixelPosition, m_transform, color());
257 default:
258 return m_current_fontengine->alphaMapForGlyph(g, subPixelPosition, m_transform);
259 }
260}
261
262/************************************************************************
263 * QImageTextureGlyphCache
264 */
265
266// out-of-line to avoid vtable duplication, breaking e.g. RTTI
267QImageTextureGlyphCache::~QImageTextureGlyphCache()
268{
269}
270
271void QImageTextureGlyphCache::resizeTextureData(int width, int height)
272{
273 m_image = m_image.copy(0, 0, width, height);
274 // Regions not part of the copy are initialized to 0, and that is just what
275 // we need.
276}
277
278void QImageTextureGlyphCache::createTextureData(int width, int height)
279{
280 switch (m_format) {
281 case QFontEngine::Format_Mono:
282 m_image = QImage(width, height, QImage::Format_Mono);
283 break;
284 case QFontEngine::Format_A8:
285 m_image = QImage(width, height, QImage::Format_Alpha8);
286 break;
287 case QFontEngine::Format_A32:
288 m_image = QImage(width, height, QImage::Format_RGB32);
289 break;
290 case QFontEngine::Format_ARGB:
291 m_image = QImage(width, height, QImage::Format_ARGB32_Premultiplied);
292 break;
293 default:
294 Q_UNREACHABLE();
295 }
296
297 // Regions not touched by the glyphs must be initialized to 0. (such
298 // locations may in fact be sampled with styled (shifted) text materials)
299 // When resizing, the QImage copy() does this implicitly but the initial
300 // contents must be zeroed out explicitly here.
301 m_image.fill(0);
302}
303
304void QImageTextureGlyphCache::fillTexture(const Coord &c,
305 glyph_t g,
306 const QFixedPoint &subPixelPosition)
307{
308 QImage mask = textureMapForGlyph(g, subPixelPosition);
309 if (mask.isNull())
310 return;
311
312#ifdef CACHE_DEBUG
313 printf("fillTexture of %dx%d at %d,%d in the cache of %dx%d\n", c.w, c.h, c.x, c.y, m_image.width(), m_image.height());
314 if (mask.width() > c.w || mask.height() > c.h) {
315 printf(" ERROR; mask is bigger than reserved space! %dx%d instead of %dx%d\n", mask.width(), mask.height(), c.w,c.h);
316 return;
317 }
318#endif
319 if (m_format == QFontEngine::Format_A32
320 || m_format == QFontEngine::Format_ARGB) {
321 QImage ref(m_image.bits() + (c.x * 4 + c.y * m_image.bytesPerLine()),
322 qMin(mask.width(), c.w), qMin(mask.height(), c.h), m_image.bytesPerLine(),
323 m_image.format());
324 QPainter p(&ref);
325 p.setCompositionMode(QPainter::CompositionMode_Source);
326 p.fillRect(0, 0, c.w, c.h, QColor(0,0,0,0)); // TODO optimize this
327 p.drawImage(0, 0, mask);
328 p.end();
329 } else if (m_format == QFontEngine::Format_Mono) {
330 if (mask.depth() > 1) {
331 // TODO optimize this
332 mask.convertTo(QImage::Format_Alpha8);
333 mask.reinterpretAsFormat(QImage::Format_Grayscale8);
334 mask.invertPixels();
335 mask.convertTo(QImage::Format_Mono, Qt::ThresholdDither);
336 }
337
338 int mw = qMin(mask.width(), c.w);
339 int mh = qMin(mask.height(), c.h);
340 uchar *d = m_image.bits();
341 qsizetype dbpl = m_image.bytesPerLine();
342
343 for (int y = 0; y < c.h; ++y) {
344 uchar *dest = d + (c.y + y) *dbpl + c.x/8;
345
346 if (y < mh) {
347 const uchar *src = mask.constScanLine(y);
348 for (int x = 0; x < c.w/8; ++x) {
349 if (x < (mw+7)/8)
350 dest[x] = src[x];
351 else
352 dest[x] = 0;
353 }
354 } else {
355 for (int x = 0; x < c.w/8; ++x)
356 dest[x] = 0;
357 }
358 }
359 } else { // A8
360 int mw = qMin(mask.width(), c.w);
361 int mh = qMin(mask.height(), c.h);
362 uchar *d = m_image.bits();
363 qsizetype dbpl = m_image.bytesPerLine();
364
365 if (mask.depth() == 1) {
366 for (int y = 0; y < c.h; ++y) {
367 uchar *dest = d + (c.y + y) *dbpl + c.x;
368 if (y < mh) {
369 const uchar *src = mask.constScanLine(y);
370 for (int x = 0; x < c.w; ++x) {
371 if (x < mw)
372 dest[x] = (src[x >> 3] & (1 << (7 - (x & 7)))) > 0 ? 255 : 0;
373 }
374 }
375 }
376 } else if (mask.depth() == 8) {
377 for (int y = 0; y < c.h; ++y) {
378 uchar *dest = d + (c.y + y) *dbpl + c.x;
379 if (y < mh) {
380 const uchar *src = mask.constScanLine(y);
381 for (int x = 0; x < c.w; ++x) {
382 if (x < mw)
383 dest[x] = src[x];
384 }
385 }
386 }
387 }
388 }
389
390#ifdef CACHE_DEBUG
391// QPainter p(&m_image);
392// p.drawLine(
393 int margin = m_current_fontengine ? m_current_fontengine->glyphMargin(m_format) : 0;
394 QPoint base(c.x + margin, c.y + margin + c.baseLineY-1);
395 if (m_image.rect().contains(base))
396 m_image.setPixel(base, 255);
397 m_image.save(QString::fromLatin1("cache-%1.png").arg(qint64(this)));
398#endif
399}
400
401QT_END_NAMESPACE
Combined button and popup list for selecting options.
#define QT_DEFAULT_TEXTURE_GLYPH_CACHE_WIDTH