mod.rs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. //! GPU text rendering pipeline.
  19. //!
  20. //! Text is drawn as textured quads on the GPU; no platform text API is
  21. //! involved. The pipeline has three layers:
  22. //!
  23. //! * Layout (`make_layout`): parley shapes a string into glyph runs
  24. //! using the font stack (IBM Plex Mono, Noto Color Emoji, DarkIRC
  25. //! Emoji) registered in `GLOBAL_FONT_CTX`. Coordinates are physical
  26. //! pixels (window scale is baked in by parley); `TextLayout` remembers
  27. //! the scale, and consumers divide by it exactly once to get the
  28. //! virtual units the renderer expects. Rasterization still happens at
  29. //! physical resolution so text stays crisp while the renderer
  30. //! re-applies the scale via `SetScale`.
  31. //!
  32. //! * Rendering (`render`): two passes over a layout. First every glyph
  33. //! of every run is rasterized with swash and packed into an `Atlas`:
  34. //! one RGBA8 texture per call, color glyphs stored as RGBA and mask
  35. //! glyphs as alpha. Then each run becomes a `DrawMesh` of quads whose
  36. //! UVs reference that texture, so a whole run draws in one call. This
  37. //! atlas is transient (one per layout): the right trade-off for
  38. //! arbitrary dynamic text such as chat messages and labels, where
  39. //! layouts are short-lived and each draws from its own texture.
  40. //!
  41. //! * Batching for fixed sets (`string_atlas`): the opposite trade-off.
  42. //! `make_string_atlas` lays out many fixed strings up front and packs
  43. //! all their glyphs into a single shared atlas: one texture and one
  44. //! raster per glyph for the entire set, returning per-string quad
  45. //! geometry to the caller. Used by the emoji picker, where rendering
  46. //! each icon through the dynamic path allocated one texture plus a
  47. //! vertex/index buffer pair per emoji (~574 icons, ~2s of generation)
  48. //! for glyphs that only ever needed to reference a shared sheet.
  49. //!
  50. //! The packer itself lives in `atlas`: sprites are separated by a 2px
  51. //! gap on all sides to prevent UV bleed, and can optionally wrap into
  52. //! rows capped at `MAX_TEXTURE_DIMENSION` so large fixed sets stay
  53. //! within GPU texture size limits (GLES3/WebGL2 only guarantee 2048),
  54. //! failing loudly at build time instead of corrupting at draw time.
  55. use parley::fontique::{Collection, CollectionOptions, SourceCache, SourceCacheOptions};
  56. use std::{
  57. cell::RefCell,
  58. ops::Range,
  59. sync::{Arc, LazyLock},
  60. };
  61. use crate::mesh::Color;
  62. pub mod atlas;
  63. mod editor;
  64. pub use editor::Editor;
  65. mod render;
  66. #[cfg(not(target_os = "android"))]
  67. pub use render::render_raw_layout;
  68. pub use render::{render_backgrounds, render_layout, render_layout_with_opts, DebugRenderOptions};
  69. mod string_atlas;
  70. pub use string_atlas::make_string_atlas;
  71. pub static GLOBAL_FONT_CTX: LazyLock<parley::FontContext> = LazyLock::new(|| {
  72. let mut font_ctx = parley::FontContext {
  73. collection: Collection::new(CollectionOptions { shared: true, system_fonts: true }),
  74. source_cache: SourceCache::new(SourceCacheOptions { shared: true }),
  75. };
  76. let font_data = include_bytes!("../../data/font/ibm-plex-mono-regular.otf") as &[u8];
  77. font_ctx.collection.register_fonts(peniko::Blob::new(Arc::new(font_data)), None);
  78. let font_data = include_bytes!("../../data/font/NotoColorEmoji.ttf") as &[u8];
  79. font_ctx.collection.register_fonts(peniko::Blob::new(Arc::new(font_data)), None);
  80. let font_data = include_bytes!("../../data/font/darkfi-custom-emoji.ttf") as &[u8];
  81. font_ctx.collection.register_fonts(peniko::Blob::new(Arc::new(font_data)), None);
  82. font_ctx
  83. });
  84. thread_local! {
  85. pub static THREAD_LAYOUT_CTX: RefCell<parley::LayoutContext<Color>> =
  86. RefCell::new(parley::LayoutContext::new());
  87. }
  88. const FONT_STACK: &[parley::FontFamilyName<'_>] = &[
  89. parley::FontFamilyName::named("IBM Plex Mono"),
  90. parley::FontFamilyName::named("Noto Color Emoji"),
  91. parley::FontFamilyName::named("DarkIRC Emoji"),
  92. ];
  93. /// A parley layout paired with the window scale it was built with.
  94. ///
  95. /// Parley bakes the builder scale into every coordinate (font size,
  96. /// advances, glyph positions), so the underlying layout is in physical
  97. /// pixels. The renderer applies the window scale again via `SetScale`,
  98. /// so geometry consumed in virtual units must be divided by the scale
  99. /// exactly once. The accessors below do that division. Rendering code
  100. /// in `render.rs` divides when emitting meshes. Glyph rasterization
  101. /// still happens at physical resolution so text stays crisp.
  102. #[derive(Clone)]
  103. pub struct TextLayout {
  104. layout: parley::Layout<Color>,
  105. /// Scale parley baked into `layout`. Divide physical coords by this
  106. /// to get virtual units.
  107. scale: f32,
  108. }
  109. impl std::ops::Deref for TextLayout {
  110. type Target = parley::Layout<Color>;
  111. fn deref(&self) -> &Self::Target {
  112. &self.layout
  113. }
  114. }
  115. impl std::ops::DerefMut for TextLayout {
  116. fn deref_mut(&mut self) -> &mut Self::Target {
  117. &mut self.layout
  118. }
  119. }
  120. impl Default for TextLayout {
  121. fn default() -> Self {
  122. Self { layout: parley::Layout::default(), scale: 1. }
  123. }
  124. }
  125. impl TextLayout {
  126. pub fn scale(&self) -> f32 {
  127. self.scale
  128. }
  129. /// Height in virtual units
  130. pub fn height(&self) -> f32 {
  131. self.layout.height() / self.scale
  132. }
  133. /// Width in virtual units
  134. pub fn width(&self) -> f32 {
  135. self.layout.width() / self.scale
  136. }
  137. }
  138. pub fn make_layout(
  139. text: &str,
  140. text_color: Color,
  141. font_size: f32,
  142. lineheight: f32,
  143. window_scale: f32,
  144. width: Option<f32>,
  145. underlines: &[Range<usize>],
  146. ) -> TextLayout {
  147. make_layout2(
  148. text,
  149. text_color,
  150. font_size,
  151. lineheight,
  152. window_scale,
  153. width,
  154. underlines,
  155. &[],
  156. parley::Alignment::Start,
  157. parley::OverflowWrap::Normal,
  158. )
  159. }
  160. pub fn make_layout2(
  161. text: &str,
  162. text_color: Color,
  163. font_size: f32,
  164. lineheight: f32,
  165. window_scale: f32,
  166. width: Option<f32>,
  167. underlines: &[Range<usize>],
  168. foreground_colors: &[(Range<usize>, Color)],
  169. text_align: parley::Alignment,
  170. overflow_wrap: parley::OverflowWrap,
  171. ) -> TextLayout {
  172. THREAD_LAYOUT_CTX.with(|layout_ctx| {
  173. let mut layout_ctx = layout_ctx.borrow_mut();
  174. let mut font_ctx = GLOBAL_FONT_CTX.clone();
  175. let mut builder = layout_ctx.ranged_builder(&mut font_ctx, text, window_scale, false);
  176. builder.push_default(parley::LineHeight::FontSizeRelative(lineheight));
  177. builder.push_default(parley::StyleProperty::FontSize(font_size));
  178. builder.push_default(parley::StyleProperty::from(FONT_STACK));
  179. builder.push_default(parley::StyleProperty::Brush(text_color));
  180. builder.push_default(parley::StyleProperty::OverflowWrap(overflow_wrap));
  181. for underline in underlines {
  182. builder.push(parley::StyleProperty::Underline(true), underline.clone());
  183. }
  184. for (range, color) in foreground_colors {
  185. builder.push(parley::StyleProperty::Brush(*color), range.clone());
  186. }
  187. let mut layout: parley::Layout<Color> = builder.build(text);
  188. // The wrap width is given in virtual units while the layout
  189. // coordinates are physical, so scale it up before breaking.
  190. layout.break_all_lines(width.map(|w| w * window_scale));
  191. layout.align(text_align, parley::AlignmentOptions::default());
  192. TextLayout { layout, scale: window_scale }
  193. })
  194. }