ltk/gles_render/
glyph_atlas.rs

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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>

//! Glyph atlas shared by every canvas and sub-canvas on one GL context,
//! so a surface that is created again finds its glyphs already rasterised.
//!
//! The atlas is a set of pages rather than one large texture: a driver that
//! shadows a texture a pending draw still samples before writing to it
//! (panfrost copies the whole buffer) then copies one page, not the atlas.

use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::{ Arc, Weak };

use glow::HasContext;

use super::GlesVersion;

/// Side of a regular page, in texels.
pub( super ) const PAGE_SIZE: u32 = 512;
/// Largest glyph side the atlas accepts; a glyph that does not fit a regular page gets a page of its own.
const MAX_GLYPH_SIDE: u32 = 2048;
/// Texture memory all pages may use together, one byte per texel.
const MAX_BYTES: usize = 8 * 1024 * 1024;
const PAD: u32 = 1;

/// Cached glyph: rasterized bitmap placed in one page of the atlas.
pub( super ) struct GlyphEntry
{
	pub( super ) metrics:  crate::font_face::Metrics,
	pub( super ) tex_w:    i32,
	pub( super ) tex_h:    i32,
	pub( super ) page:     usize,
	pub( super ) atlas_x:  u32,
	pub( super ) atlas_y:  u32,
}

/// Cache key for the GLES glyph atlas — the GPU-side mirror of the
/// software canvas's `GlyphKey`. `glyph_id` is the per-font index
/// returned by HarfBuzz shaping; `size_bits` is `f32::to_bits` of
/// `size * dpi_scale`; `font_id` is the address of the
/// `Arc<FontFace>` used for rasterisation.
pub( super ) type GlyphAtlasKey = ( u16, u32, usize );

struct Page
{
	texture:    glow::Texture,
	width:      u32,
	height:     u32,
	cursor_x:   u32,
	cursor_y:   u32,
	row_height: u32,
}

impl Page
{
	fn new( gl: &glow::Context, internal: i32, format: u32, width: u32, height: u32 ) -> Self
	{
		// SAFETY: the GL context behind `gl` is current on this thread (canvas
		// invariant); the texture is created, specified and unbound here.
		let texture = unsafe
		{
			let tex = gl.create_texture().unwrap();
			gl.bind_texture( glow::TEXTURE_2D, Some( tex ) );
			gl.pixel_store_i32( glow::UNPACK_ALIGNMENT, 1 );
			gl.tex_image_2d(
				glow::TEXTURE_2D, 0, internal,
				width as i32, height as i32, 0,
				format, glow::UNSIGNED_BYTE,
				glow::PixelUnpackData::Slice( None ),
			);
			gl.pixel_store_i32( glow::UNPACK_ALIGNMENT, 4 );
			gl.tex_parameter_i32( glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, glow::NEAREST as i32 );
			gl.tex_parameter_i32( glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, glow::NEAREST as i32 );
			gl.tex_parameter_i32( glow::TEXTURE_2D, glow::TEXTURE_WRAP_S, glow::CLAMP_TO_EDGE as i32 );
			gl.tex_parameter_i32( glow::TEXTURE_2D, glow::TEXTURE_WRAP_T, glow::CLAMP_TO_EDGE as i32 );
			gl.bind_texture( glow::TEXTURE_2D, None );
			tex
		};
		Self { texture, width, height, cursor_x: 0, cursor_y: 0, row_height: 0 }
	}

	fn bytes( &self ) -> usize
	{
		( self.width as usize ) * ( self.height as usize )
	}

	/// Shelf-pack a `w × h` cell, padding included.
	fn alloc( &mut self, w: u32, h: u32 ) -> Option<( u32, u32 )>
	{
		if w > self.width || h > self.height { return None; }
		if self.cursor_x + w > self.width
		{
			self.cursor_x   = 0;
			self.cursor_y  += self.row_height;
			self.row_height = 0;
		}
		if self.cursor_y + h > self.height { return None; }
		let pos = ( self.cursor_x, self.cursor_y );
		self.cursor_x += w;
		if h > self.row_height { self.row_height = h; }
		Some( pos )
	}

	fn rewind( &mut self )
	{
		self.cursor_x   = 0;
		self.cursor_y   = 0;
		self.row_height = 0;
	}
}

pub( super ) struct GlyphAtlas
{
	/// GL_R8 / GL_RED on ES3 (GL_LUMINANCE is deprecated in ES3 core and
	/// some mobile drivers — Mali, certain Adreno — return GL_INVALID_ENUM
	/// for it), legacy GL_LUMINANCE on ES2 where the modern single-channel
	/// formats do not exist. The glyph shader samples `.r`, which carries
	/// the coverage byte with either.
	internal: i32,
	format:   u32,
	pages:    Vec<Page>,
	/// Regular page new glyphs are packed into; pages before it are full.
	current:  usize,
	bytes:    usize,
	// (glyph_id, size_key, font_id) → GlyphEntry. `glyph_id` is the
	// per-font glyph index returned by HarfBuzz shaping; the cache
	// therefore persists Arabic / Devanagari / CJK shaped forms
	// independently of the source codepoints.
	pub( super ) cache: HashMap<GlyphAtlasKey, GlyphEntry>,
}

impl GlyphAtlas
{
	fn new( version: GlesVersion ) -> Self
	{
		let ( internal, format ) = match version
		{
			GlesVersion::V3 => ( glow::R8 as i32,        glow::RED       ),
			GlesVersion::V2 => ( glow::LUMINANCE as i32, glow::LUMINANCE ),
		};
		Self { internal, format, pages: Vec::new(), current: 0, bytes: 0, cache: HashMap::new() }
	}

	pub( super ) fn page_texture( &self, page: usize ) -> glow::Texture
	{
		self.pages[ page ].texture
	}

	pub( super ) fn page_size( &self, page: usize ) -> ( f32, f32 )
	{
		let p = &self.pages[ page ];
		( p.width as f32, p.height as f32 )
	}

	/// Place a `w × h` glyph, returning its page and position, or `None`
	/// when the atlas is full and needs a [`Self::reset`].
	pub( super ) fn alloc( &mut self, gl: &glow::Context, w: u32, h: u32 ) -> Option<( usize, u32, u32 )>
	{
		let ( cw, ch ) = ( w + PAD, h + PAD );
		if cw > MAX_GLYPH_SIDE || ch > MAX_GLYPH_SIDE { return None; }
		if cw > PAGE_SIZE || ch > PAGE_SIZE
		{
			if self.bytes + ( cw as usize ) * ( ch as usize ) > MAX_BYTES { return None; }
			let mut page = Page::new( gl, self.internal, self.format, cw, ch );
			page.alloc( cw, ch );
			self.bytes += page.bytes();
			self.pages.push( page );
			return Some( ( self.pages.len() - 1, 0, 0 ) );
		}
		loop
		{
			if self.current == self.pages.len()
			{
				let page_bytes = ( PAGE_SIZE as usize ) * ( PAGE_SIZE as usize );
				if self.bytes + page_bytes > MAX_BYTES { return None; }
				self.pages.push( Page::new( gl, self.internal, self.format, PAGE_SIZE, PAGE_SIZE ) );
				self.bytes += page_bytes;
			}
			if let Some( ( x, y ) ) = self.pages[ self.current ].alloc( cw, ch )
			{
				return Some( ( self.current, x, y ) );
			}
			self.current += 1;
		}
	}

	/// Copy a rasterised glyph into its place in `page`.
	#[ allow( clippy::too_many_arguments ) ]
	pub( super ) fn upload( &self, gl: &glow::Context, page: usize, x: u32, y: u32, w: u32, h: u32, bitmap: &[u8] )
	{
		// SAFETY: the context is current (canvas invariant) and the page
		// texture was created through it in `Page::new`.
		unsafe
		{
			gl.bind_texture( glow::TEXTURE_2D, Some( self.pages[ page ].texture ) );
			gl.pixel_store_i32( glow::UNPACK_ALIGNMENT, 1 );
			gl.tex_sub_image_2d(
				glow::TEXTURE_2D, 0,
				x as i32, y as i32,
				w as i32, h as i32,
				self.format, glow::UNSIGNED_BYTE,
				glow::PixelUnpackData::Slice( Some( bitmap ) ),
			);
			gl.pixel_store_i32( glow::UNPACK_ALIGNMENT, 4 );
		}
	}

	/// Forget every glyph. Regular pages are kept for reuse; pages made
	/// for a single oversized glyph are freed.
	pub( super ) fn reset( &mut self, gl: &glow::Context )
	{
		self.cache.clear();
		let mut bytes = 0;
		self.pages.retain_mut( |p|
		{
			if p.width == PAGE_SIZE && p.height == PAGE_SIZE
			{
				p.rewind();
				bytes += p.bytes();
				return true;
			}
			// SAFETY: the texture was created through this context and is
			// leaving the atlas, so it is deleted exactly once.
			unsafe { gl.delete_texture( p.texture ); }
			false
		} );
		self.bytes   = bytes;
		self.current = 0;
	}
}

thread_local!
{
	static SHARED_ATLASES: RefCell<Vec<( Weak<glow::Context>, Rc<RefCell<GlyphAtlas>> )>> =
		const { RefCell::new( Vec::new() ) };
}

/// The atlas for the context behind `gl`, created on first use.
pub( super ) fn shared_glyph_atlas( gl: &Arc<glow::Context>, version: GlesVersion ) -> Rc<RefCell<GlyphAtlas>>
{
	SHARED_ATLASES.with( |atlases|
	{
		let mut atlases = atlases.borrow_mut();
		atlases.retain( |( ctx, _ )| ctx.strong_count() > 0 );
		if let Some( ( _, atlas ) ) = atlases.iter().find( |( ctx, _ )| std::ptr::eq( ctx.as_ptr(), Arc::as_ptr( gl ) ) )
		{
			return Rc::clone( atlas );
		}
		let atlas = Rc::new( RefCell::new( GlyphAtlas::new( version ) ) );
		atlases.push( ( Arc::downgrade( gl ), Rc::clone( &atlas ) ) );
		atlas
	} )
}