Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Ports/iOSPort/nativeSources/CN1MetalGlyphAtlas.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,17 @@
@property (nonatomic, assign) float bearingY; // bbox.origin.y — distance baseline → bbox bottom (CT y-up)
@property (nonatomic, assign) float bboxWidth; // bbox.size.width (no padding)
@property (nonatomic, assign) float bboxHeight; // bbox.size.height (no padding)
// Non-nil for a glyph too large to pack (bigger than the per-glyph cap,
// e.g. a 20mm Material icon at 360+ px): it is rasterised into a texture
// of its own at (0, 0), and atlasX/atlasY index that texture instead of
// the atlas. Retained by the slot.
@property (nonatomic, retain, nullable) id<MTLTexture> ownTexture;
// Bitmap pixels per font pixel. 1 for every packed glyph; below 1 for a glyph
// so large (TV-size display text, a full-screen icon) that its bitmap would
// pass CN1_METAL_GLYPH_RASTER_MAX: it is rasterised smaller and the quad
// scales it back up. width/height/atlasX/atlasY are BITMAP pixels; bearings
// and bbox stay in font pixels. 0 (never set) reads as 1.
@property (nonatomic, assign) float rasterScale;
@end

@interface CN1MetalGlyphAtlas : NSObject
Expand Down
153 changes: 119 additions & 34 deletions Ports/iOSPort/nativeSources/CN1MetalGlyphAtlas.m
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,21 @@
#define CN1_METAL_ATLAS_MAX_W 2048
#define CN1_METAL_ATLAS_MAX_H 2048
#define CN1_METAL_ATLAS_PADDING 1
#define CN1_METAL_ATLAS_GLYPH_MAX 256 // sanity limit on per-glyph bitmap dim
#define CN1_METAL_ATLAS_GLYPH_MAX 256 // largest glyph packed into the shared atlas
// Glyphs above CN1_METAL_ATLAS_GLYPH_MAX get a texture of their own instead of
// being dropped (issue #6393: a 20mm Material icon is 360-400px on an iPhone
// and drew nothing at all). A glyph's bitmap never passes
// CN1_METAL_GLYPH_RASTER_MAX on its longer side: past that it is rasterised
// smaller and drawn scaled up (slot.rasterScale < 1), so a huge glyph on a TV
// costs at most 1024x1024 (4 MB for a colour emoji) and never approaches a
// device's texture limit. At that size a scaled-up edge is not visible.
#define CN1_METAL_GLYPH_RASTER_MAX 1024
// Bytes of oversized-glyph textures one atlas may hold. Each oversized glyph is
// up to 1 MB (R8) or 4 MB (BGRA emoji), so a TV screen of display text or an 8x
// zoom over a paragraph would otherwise pin tens of MB until the atlas itself
// is evicted. Past the budget every oversized slot is dropped and re-rasterised
// on next use, the same as tryGrowAtlas dropping packed slots.
#define CN1_METAL_OWN_TEXTURE_BUDGET (32u * 1024u * 1024u)

extern id<MTLDevice> CN1MetalDevice(void);

Expand Down Expand Up @@ -75,6 +89,12 @@
static uint64_t atlasCacheTick = 0;

@implementation CN1MetalGlyphSlot
- (void)dealloc {
[_ownTexture release]; _ownTexture = nil;
#ifndef CN1_USE_ARC
[super dealloc];
#endif
}
@end

@interface CN1MetalGlyphAtlas () {
Expand All @@ -89,6 +109,7 @@ @interface CN1MetalGlyphAtlas () {
int _shelfY;
int _shelfHeight;
int _cursorX;
size_t _ownTextureBytes; // see CN1_METAL_OWN_TEXTURE_BUDGET
}
@end

Expand Down Expand Up @@ -279,6 +300,7 @@ - (BOOL)tryGrowAtlas {

// Drop slots; next reference re-rasterises into the larger atlas.
[_slots removeAllObjects];
_ownTextureBytes = 0; // the oversized slots went with them
_shelfY = CN1_METAL_ATLAS_PADDING;
_shelfHeight = 0;
_cursorX = CN1_METAL_ATLAS_PADDING;
Expand Down Expand Up @@ -317,40 +339,88 @@ - (CN1MetalGlyphSlot *)slotForGlyph:(CGGlyph)glyph {
return empty;
}

// Reject absurd metrics before any float-to-int conversion: (int)ceilf of
// NaN, inf or a value past INT_MAX is undefined behaviour in C. No real
// glyph is a million pixels across, even at the 8x transform cap.
if (!isfinite(bbox.size.width) || !isfinite(bbox.size.height) ||
bbox.size.width > 1.0e6 || bbox.size.height > 1.0e6) return nil;
int gw = (int)ceilf((float)bbox.size.width) + 2 * CN1_METAL_ATLAS_PADDING;
int gh = (int)ceilf((float)bbox.size.height) + 2 * CN1_METAL_ATLAS_PADDING;
// Refuse oversized glyphs: protects the bitmap allocation if a font
// returns absurd metrics. A 256x256 cap is plenty for system text.
if (gw > CN1_METAL_ATLAS_GLYPH_MAX || gh > CN1_METAL_ATLAS_GLYPH_MAX) return nil;

// Shelf-pack: open a new shelf if current one is too narrow to fit.
if (_cursorX + gw > _textureWidth - CN1_METAL_ATLAS_PADDING) {
_shelfY += _shelfHeight + CN1_METAL_ATLAS_PADDING;
_cursorX = CN1_METAL_ATLAS_PADDING;
_shelfHeight = 0;
// A glyph above the packing cap (large icon-font glyphs, display-size
// text) is rasterised into a texture of its own. Dropping it, as this
// once did, left the space reserved and drew nothing (#6393).
BOOL oversize = (gw > CN1_METAL_ATLAS_GLYPH_MAX || gh > CN1_METAL_ATLAS_GLYPH_MAX);
// rasterScale maps font pixels to bitmap pixels; 1 unless the glyph is
// larger than CN1_METAL_GLYPH_RASTER_MAX.
float rasterScale = 1.0f;
if (gw > CN1_METAL_GLYPH_RASTER_MAX || gh > CN1_METAL_GLYPH_RASTER_MAX) {
float longer = (float)MAX(bbox.size.width, bbox.size.height);
// One pixel of slack below the cap: float rounding can push
// ceilf(longer * rasterScale) one past the target, and the MIN clamp
// below would then cut the glyph's last column or row.
rasterScale = (float)(CN1_METAL_GLYPH_RASTER_MAX - 2 * CN1_METAL_ATLAS_PADDING - 1) / longer;
gw = MIN(CN1_METAL_GLYPH_RASTER_MAX,
(int)ceilf((float)bbox.size.width * rasterScale) + 2 * CN1_METAL_ATLAS_PADDING);
gh = MIN(CN1_METAL_GLYPH_RASTER_MAX,
(int)ceilf((float)bbox.size.height * rasterScale) + 2 * CN1_METAL_ATLAS_PADDING);
}
// Grow while the glyph fails to fit in EITHER dimension. Testing height
// alone was sufficient only because the atlas used to start at 1024 with
// glyphs capped at CN1_METAL_ATLAS_GLYPH_MAX (256), so a fresh shelf always
// had room across and the width test could never fire. At the smaller
// starting sizes cn1AtlasInitialDim now allows, a glyph can be as wide as
// the whole atlas -- and without a width test the slot below is handed to
// replaceRegion: as a region running past the texture edge.
//
// tryGrowAtlas drops every slot and resets the shelf cursor to the origin
// of the new, larger texture, so each iteration re-tests against it and the
// loop terminates either by fitting or by hitting the growth ceiling.
while (_cursorX + gw > _textureWidth - CN1_METAL_ATLAS_PADDING ||
_shelfY + gh > _textureHeight - CN1_METAL_ATLAS_PADDING) {
if (![self tryGrowAtlas]) {
return nil;
id<MTLTexture> targetTex = _texture;
id<MTLTexture> ownTex = nil;
size_t ownTexBytes = 0; // counted only once the slot is stored
int slotX = 0;
int slotY = 0;
if (oversize) {
id<MTLDevice> device = CN1MetalDevice();
if (device == nil) return nil;
MTLTextureDescriptor *desc = [MTLTextureDescriptor
texture2DDescriptorWithPixelFormat:(_isColor ? MTLPixelFormatBGRA8Unorm : MTLPixelFormatR8Unorm)
width:(NSUInteger)gw height:(NSUInteger)gh mipmapped:NO];
desc.usage = MTLTextureUsageShaderRead;
size_t texBytes = (size_t)gw * (size_t)gh * (_isColor ? 4u : 1u);
if (_ownTextureBytes + texBytes > CN1_METAL_OWN_TEXTURE_BUDGET) {
NSMutableArray *drop = [[NSMutableArray alloc] init];
for (NSNumber *k in _slots) {
if (_slots[k].ownTexture != nil) [drop addObject:k];
}
[_slots removeObjectsForKeys:drop];
[drop release];
_ownTextureBytes = 0;
}
}
if (gh > _shelfHeight) _shelfHeight = gh;
ownTex = [device newTextureWithDescriptor:desc];
CN1_TEX_NOTE("glyphOversize", ownTex);
if (ownTex == nil) return nil;
ownTexBytes = texBytes;
targetTex = ownTex;
} else {
// Shelf-pack: open a new shelf if current one is too narrow to fit.
if (_cursorX + gw > _textureWidth - CN1_METAL_ATLAS_PADDING) {
_shelfY += _shelfHeight + CN1_METAL_ATLAS_PADDING;
_cursorX = CN1_METAL_ATLAS_PADDING;
_shelfHeight = 0;
}
// Grow while the glyph fails to fit in EITHER dimension. Testing height
// alone was sufficient only because the atlas used to start at 1024 with
// glyphs capped at CN1_METAL_ATLAS_GLYPH_MAX (256), so a fresh shelf always
// had room across and the width test could never fire. At the smaller
// starting sizes cn1AtlasInitialDim now allows, a glyph can be as wide as
// the whole atlas -- and without a width test the slot below is handed to
// replaceRegion: as a region running past the texture edge.
//
// tryGrowAtlas drops every slot and resets the shelf cursor to the origin
// of the new, larger texture, so each iteration re-tests against it and the
// loop terminates either by fitting or by hitting the growth ceiling.
while (_cursorX + gw > _textureWidth - CN1_METAL_ATLAS_PADDING ||
_shelfY + gh > _textureHeight - CN1_METAL_ATLAS_PADDING) {
if (![self tryGrowAtlas]) {
return nil;
}
}
if (gh > _shelfHeight) _shelfHeight = gh;

int slotX = _cursorX;
int slotY = _shelfY;
_cursorX += gw + CN1_METAL_ATLAS_PADDING;
slotX = _cursorX;
slotY = _shelfY;
_cursorX += gw + CN1_METAL_ATLAS_PADDING;
}

// Rasterise into a local buffer. Monochrome fonts use DeviceGray +
// kCGImageAlphaNone + white fill: CTFontDrawGlyphs paints the glyph paths
Expand All @@ -372,7 +442,10 @@ - (CN1MetalGlyphSlot *)slotForGlyph:(CGGlyph)glyph {
int bytesPerPixel = _isColor ? 4 : 1;
size_t bytesPerRow = (size_t)gw * (size_t)bytesPerPixel;
void *pixels = calloc((size_t)gh * bytesPerRow, 1);
if (pixels == NULL) return nil;
if (pixels == NULL) {
[ownTex release];
return nil;
}
CGColorSpaceRef cs = _isColor ? CGColorSpaceCreateDeviceRGB()
: CGColorSpaceCreateDeviceGray();
CGBitmapInfo bitmapInfo = _isColor
Expand All @@ -384,6 +457,7 @@ - (CN1MetalGlyphSlot *)slotForGlyph:(CGGlyph)glyph {
CGColorSpaceRelease(cs);
if (ctx == NULL) {
free(pixels);
[ownTex release];
return nil;
}
if (!_isColor) {
Expand All @@ -392,8 +466,13 @@ - (CN1MetalGlyphSlot *)slotForGlyph:(CGGlyph)glyph {
CGContextSetGrayFillColor(ctx, 1.0, 1.0);
}

CGPoint origin = CGPointMake((CGFloat)CN1_METAL_ATLAS_PADDING - bbox.origin.x,
(CGFloat)CN1_METAL_ATLAS_PADDING - bbox.origin.y);
// Under a rasterScale the context is scaled, so the origin is expressed
// in font pixels: the padding band stays exactly one BITMAP pixel.
if (rasterScale != 1.0f) {
CGContextScaleCTM(ctx, rasterScale, rasterScale);
}
CGPoint origin = CGPointMake((CGFloat)CN1_METAL_ATLAS_PADDING / rasterScale - bbox.origin.x,
(CGFloat)CN1_METAL_ATLAS_PADDING / rasterScale - bbox.origin.y);
// Monochrome glyphs go through the CGFont path rather than CTFontDrawGlyphs.
// CTFontDrawGlyphs checks every draw for glyphs that overlap in a connected
// script, and the first time it does that for a font it loads the font's
Expand All @@ -417,7 +496,7 @@ - (CN1MetalGlyphSlot *)slotForGlyph:(CGGlyph)glyph {
}
CGContextRelease(ctx);

[_texture replaceRegion:MTLRegionMake2D((NSUInteger)slotX, (NSUInteger)slotY,
[targetTex replaceRegion:MTLRegionMake2D((NSUInteger)slotX, (NSUInteger)slotY,
(NSUInteger)gw, (NSUInteger)gh)
mipmapLevel:0
withBytes:pixels
Expand All @@ -433,6 +512,12 @@ - (CN1MetalGlyphSlot *)slotForGlyph:(CGGlyph)glyph {
slot.bearingY = (float)bbox.origin.y;
slot.bboxWidth = (float)bbox.size.width;
slot.bboxHeight = (float)bbox.size.height;
slot.rasterScale = rasterScale;
if (ownTex != nil) {
slot.ownTexture = ownTex; // retained by the property
_ownTextureBytes += ownTexBytes;
[ownTex release]; // drop the +1 from newTextureWithDescriptor:
}
_slots[key] = slot;
return slot;
}
Expand Down
20 changes: 13 additions & 7 deletions Ports/iOSPort/nativeSources/CN1Metalcompat.m
Original file line number Diff line number Diff line change
Expand Up @@ -1433,9 +1433,10 @@ void CN1MetalDrawString(NSString *str, CN1Font *font, int color, int alpha, int
// can trigger tryGrowAtlas, which replaces the MTLTexture and
// doubles textureWidth/Height. Capturing before the loop would
// sample a freed texture / wrong UVs for everything past the grow.
id<MTLTexture> atlasTex = atlas.texture;
int textureW = atlas.textureWidth;
int textureH = atlas.textureHeight;
// An oversized glyph lives in a texture of its own (#6393).
id<MTLTexture> atlasTex = slot.ownTexture != nil ? slot.ownTexture : atlas.texture;
int textureW = slot.ownTexture != nil ? slot.width : atlas.textureWidth;
int textureH = slot.ownTexture != nil ? slot.height : atlas.textureHeight;

// Slot bitmap covers (bbox + 2px padding). Place the slot's
// top-left so the glyph art lines up with where CT expects:
Expand All @@ -1456,10 +1457,15 @@ void CN1MetalDrawString(NSString *str, CN1Font *font, int color, int alpha, int
float bearingX = slot.bearingX * invScale;
float bearingY = slot.bearingY * invScale;
float bboxHeight = slot.bboxHeight * invScale;
float gx = (float)x + posX + bearingX - invScale;
float gy = baselineY - posY - (bearingY + bboxHeight) - invScale;
float gw = (float)slot.width * invScale;
float gh = (float)slot.height * invScale;
// Slot width/height and the 1px padding are BITMAP pixels; a glyph
// rasterised below full size (slot.rasterScale < 1, see
// CN1_METAL_GLYPH_RASTER_MAX) is scaled back up by the quad.
float rs = slot.rasterScale > 0.0f ? slot.rasterScale : 1.0f;
float bitmapToCaller = invScale / rs;
float gx = (float)x + posX + bearingX - bitmapToCaller;
float gy = baselineY - posY - (bearingY + bboxHeight) - bitmapToCaller;
float gw = (float)slot.width * bitmapToCaller;
float gh = (float)slot.height * bitmapToCaller;

float vertices[8] = {
gx, gy,
Expand Down
7 changes: 6 additions & 1 deletion docs/website/data/port_status.json
Original file line number Diff line number Diff line change
Expand Up @@ -261,11 +261,12 @@
"id": "graphics-text-images",
"category": "2D graphics",
"name": "Text and image drawing",
"description": "Checks text decoration, glyph rendering, TrueType fonts loaded from bytes, image rectangles, and tiled images.",
"description": "Checks text decoration, glyph rendering (including glyphs hundreds of pixels tall), TrueType fonts loaded from bytes, image rectangles, and tiled images.",
"tests": [
"DrawImage",
"DrawString",
"DrawStringDecorated",
"LargeGlyphScreenshotTest",
"TileImage",
"TrueTypeFontFromDataTest"
]
Expand Down Expand Up @@ -1931,6 +1932,10 @@
"pattern": "AppReviewDialog",
"test": "AppReviewDialogScreenshotTest"
},
{
"pattern": "LargeGlyph",
"test": "LargeGlyphScreenshotTest"
},
{
"pattern": "FloatingActionButtonTheme_*",
"test": "FloatingActionButtonThemeScreenshotTest"
Expand Down
Binary file added scripts/android/screenshots/LargeGlyph.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,7 @@ private static int testTimeoutMs(BaseTest testClass) {
new ListThemeScreenshotTest(),
new DialogThemeScreenshotTest(),
new CenteredDialogTitleScreenshotTest(),
new LargeGlyphScreenshotTest(),
new CenteredInteractionDialogTitleScreenshotTest(),
new LoadingPlaceholdersScreenshotTest(),
new PickersAndInputsScreenshotTest(),
Expand Down
Loading
Loading