1use std::{fmt, sync::Arc};
2
3use super::TextRunLimits;
4use bevy_ecs::prelude::Component;
5use sim_engine::{Color, Layer, LogicalScreenPosition, ShapedLine};
6
7use crate::screen::ScreenVisualError;
8
9use super::{TextError, TextFont, TextPreparationSession};
10
11#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
16pub enum TextAlignment {
17 #[default]
19 Left,
20 Center,
22 Right,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq)]
31pub struct TextMetrics {
32 advance: f32,
33 ascent: f32,
34 descent: f32,
35 line_height: f32,
36 glyph_count: usize,
37}
38
39impl TextMetrics {
40 pub const fn advance(self) -> f32 {
42 self.advance
43 }
44
45 pub const fn ascent(self) -> f32 {
47 self.ascent
48 }
49
50 pub const fn descent(self) -> f32 {
52 self.descent
53 }
54
55 pub const fn line_height(self) -> f32 {
57 self.line_height
58 }
59
60 pub const fn glyph_count(self) -> usize {
63 self.glyph_count
64 }
65
66 fn from_line(line: &ShapedLine) -> Self {
67 Self {
68 advance: line.advance(),
69 ascent: line.ascent(),
70 descent: line.descent(),
71 line_height: line.line_height(),
72 glyph_count: line.glyphs().len(),
73 }
74 }
75}
76
77struct PreparedText {
78 line: ShapedLine,
79 metrics: TextMetrics,
80 minimum_x: f32,
81 maximum_x: f32,
82 minimum_y: f32,
83 maximum_y: f32,
84}
85
86impl PreparedText {
87 fn new(font: &TextFont, text: &str) -> Result<Self, TextError> {
88 let settings = font.settings();
89 let line =
90 font.face()
91 .shape_line(text, &settings.style(1.0)?, &settings.layout_budget())?;
92 Self::from_line(font, line)
93 }
94
95 fn from_line(font: &TextFont, line: ShapedLine) -> Result<Self, TextError> {
96 let settings = font.settings();
97 line.validate_for(
98 font.face(),
99 &settings.style(1.0)?,
100 &settings.layout_budget(),
101 )?;
102 let metrics = TextMetrics::from_line(&line);
103 let run_budget = settings.atlas_limits().run_budget();
104 let required = metrics
105 .glyph_count
106 .checked_mul(TextRunLimits::RETAINED_BYTES_PER_GLYPH);
107 if metrics.glyph_count > run_budget.max_glyphs()
108 || required.is_none_or(|bytes| bytes > run_budget.max_retained_bytes())
109 {
110 return Err(TextError::RunBudgetExceeded {
111 glyphs: metrics.glyph_count,
112 max_glyphs: run_budget.max_glyphs(),
113 required_bytes: required.unwrap_or(usize::MAX),
114 max_retained_bytes: run_budget.max_retained_bytes(),
115 });
116 }
117 let mut result = Self {
118 line,
119 metrics,
120 minimum_x: metrics.advance.min(0.0),
121 maximum_x: metrics.advance.max(0.0),
122 minimum_y: -metrics.ascent,
123 maximum_y: -metrics.descent,
124 };
125 for glyph in result.line.glyphs() {
126 result.minimum_x = result.minimum_x.min(glyph.logical_x());
127 result.maximum_x = result.maximum_x.max(glyph.logical_x());
128 result.minimum_y = result.minimum_y.min(glyph.logical_y());
129 result.maximum_y = result.maximum_y.max(glyph.logical_y());
130 }
131 Ok(result)
132 }
133}
134
135impl fmt::Debug for PreparedText {
136 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
137 formatter
139 .debug_struct("PreparedText")
140 .field("text", &self.line.text())
141 .field("metrics", &self.metrics)
142 .finish_non_exhaustive()
143 }
144}
145
146impl PartialEq for PreparedText {
147 fn eq(&self, other: &Self) -> bool {
148 self.line.text() == other.line.text()
149 && self.line.style() == other.line.style()
150 && self.line.glyphs() == other.line.glyphs()
151 && self.metrics == other.metrics
152 && self.minimum_x == other.minimum_x
153 && self.maximum_x == other.maximum_x
154 && self.minimum_y == other.minimum_y
155 && self.maximum_y == other.maximum_y
156 }
157}
158
159#[derive(Debug, Clone, PartialEq, Component)]
185pub struct ScreenTextVisual {
186 font: TextFont,
187 prepared: Arc<PreparedText>,
188 position: LogicalScreenPosition,
189 alignment: TextAlignment,
190 tint: Color,
191 layer: Layer,
192 draw_order_depth: f32,
193 clip: crate::screen::ScreenClip,
194}
195
196impl ScreenTextVisual {
197 pub const fn clip(&self) -> crate::screen::ScreenClip {
199 self.clip
200 }
201
202 pub fn set_clip(&mut self, clip: crate::screen::ScreenClip) {
204 self.clip = clip;
205 }
206 pub fn new(
213 font: TextFont,
214 text: &str,
215 position: LogicalScreenPosition,
216 ) -> Result<Self, TextError> {
217 validate_position(position)?;
218 let prepared = PreparedText::new(&font, text)?;
219 Self::from_prepared(font, prepared, position)
220 }
221
222 pub fn new_with_session(
228 session: &mut TextPreparationSession<'_>,
229 text: &str,
230 position: LogicalScreenPosition,
231 ) -> Result<Self, TextError> {
232 validate_position(position)?;
233 let font = session.font().clone();
234 let prepared = PreparedText::from_line(&font, session.shape_line(text)?)?;
235 Self::from_prepared(font, prepared, position)
236 }
237
238 fn from_prepared(
239 font: TextFont,
240 prepared: PreparedText,
241 position: LogicalScreenPosition,
242 ) -> Result<Self, TextError> {
243 let prepared = Arc::new(prepared);
244 let result = Self {
245 font,
246 prepared,
247 position,
248 alignment: TextAlignment::Left,
249 tint: Color::WHITE,
250 layer: Layer::DEFAULT,
251 draw_order_depth: 0.0,
252 clip: crate::screen::ScreenClip::Unclipped,
253 };
254 result.validate()?;
255 Ok(result)
256 }
257
258 pub const fn font(&self) -> &TextFont {
260 &self.font
261 }
262
263 pub fn text(&self) -> &str {
265 self.prepared.line.text()
266 }
267
268 pub fn shaped_line(&self) -> &ShapedLine {
274 &self.prepared.line
275 }
276
277 pub fn metrics(&self) -> TextMetrics {
279 self.prepared.metrics
280 }
281
282 pub fn glyph_count(&self) -> usize {
284 self.metrics().glyph_count()
285 }
286
287 pub fn retained_text_bytes(&self) -> usize {
294 self.retained_layout_bytes()
295 }
296
297 pub fn retained_layout_bytes(&self) -> usize {
303 self.prepared.line.allocation_bytes()
304 }
305
306 pub const fn position(&self) -> LogicalScreenPosition {
308 self.position
309 }
310
311 pub fn baseline_origin(&self) -> LogicalScreenPosition {
314 let offset = match self.alignment {
315 TextAlignment::Left => 0.0,
316 TextAlignment::Center => self.metrics().advance() * 0.5,
317 TextAlignment::Right => self.metrics().advance(),
318 };
319 let position = self.position.to_vec2();
320 LogicalScreenPosition::new(position.x() - offset, position.y())
321 }
322
323 pub const fn alignment(&self) -> TextAlignment {
325 self.alignment
326 }
327
328 pub const fn tint(&self) -> Color {
330 self.tint
331 }
332
333 pub const fn layer(&self) -> Layer {
335 self.layer
336 }
337
338 pub const fn draw_order_depth(&self) -> f32 {
340 self.draw_order_depth
341 }
342
343 pub fn set_text(&mut self, text: &str) -> Result<(), TextError> {
349 if self.text() == text {
350 return Ok(());
351 }
352 let mut candidate = self.clone();
353 candidate.prepared = Arc::new(PreparedText::new(&self.font, text)?);
354 candidate.validate()?;
355 *self = candidate;
356 Ok(())
357 }
358
359 pub fn set_text_with_session(
367 &mut self,
368 session: &mut TextPreparationSession<'_>,
369 text: &str,
370 ) -> Result<(), TextError> {
371 if session.font() != &self.font {
372 return Err(sim_engine::ShapedLineError::FontMismatch.into());
373 }
374 if self.text() == text {
375 return Ok(());
376 }
377 let prepared = PreparedText::from_line(&self.font, session.shape_line(text)?)?;
378 let mut candidate = self.clone();
379 candidate.prepared = Arc::new(prepared);
380 candidate.validate()?;
381 *self = candidate;
382 Ok(())
383 }
384
385 pub fn set_font(&mut self, font: TextFont) -> Result<(), TextError> {
391 if self.font == font {
392 return Ok(());
393 }
394 let mut candidate = self.clone();
395 candidate.prepared = Arc::new(PreparedText::new(&font, self.text())?);
396 candidate.font = font;
397 candidate.validate()?;
398 *self = candidate;
399 Ok(())
400 }
401
402 pub fn set_position(&mut self, position: LogicalScreenPosition) -> Result<(), TextError> {
405 let mut candidate = self.clone();
406 candidate.position = position;
407 candidate.validate()?;
408 *self = candidate;
409 Ok(())
410 }
411
412 pub fn set_alignment(&mut self, alignment: TextAlignment) -> Result<(), TextError> {
415 let mut candidate = self.clone();
416 candidate.alignment = alignment;
417 candidate.validate()?;
418 *self = candidate;
419 Ok(())
420 }
421
422 pub fn set_tint(&mut self, tint: Color) -> Result<(), TextError> {
424 if !tint.is_normalized() {
425 return Err(ScreenVisualError::InvalidColor { value: tint }.into());
426 }
427 self.tint = tint;
428 Ok(())
429 }
430
431 pub fn set_layer(&mut self, layer: Layer) {
433 self.layer = layer;
434 }
435
436 pub fn set_draw_order_depth(&mut self, depth: f32) -> Result<(), TextError> {
439 if !depth.is_finite() {
440 return Err(ScreenVisualError::InvalidDrawOrderDepth { value: depth }.into());
441 }
442 self.draw_order_depth = depth;
443 Ok(())
444 }
445
446 pub(crate) fn validate(&self) -> Result<(), TextError> {
447 validate_position(self.position)?;
448 if !self.tint.is_normalized() {
449 return Err(ScreenVisualError::InvalidColor { value: self.tint }.into());
450 }
451 if !self.draw_order_depth.is_finite() {
452 return Err(ScreenVisualError::InvalidDrawOrderDepth {
453 value: self.draw_order_depth,
454 }
455 .into());
456 }
457 let baseline = self.baseline_origin().to_vec2();
458 let p = &self.prepared;
459 if !baseline.is_finite()
460 || !offset_is_representable(baseline.x(), p.minimum_x)
461 || !offset_is_representable(baseline.x(), p.maximum_x)
462 || !offset_is_representable(baseline.y(), p.minimum_y)
463 || !offset_is_representable(baseline.y(), p.maximum_y)
464 {
465 return Err(TextError::InvalidBounds {
466 position: self.position,
467 });
468 }
469 Ok(())
470 }
471}
472
473fn validate_position(position: LogicalScreenPosition) -> Result<(), TextError> {
474 if !position.is_finite() {
475 return Err(ScreenVisualError::InvalidPosition { value: position }.into());
476 }
477 Ok(())
478}
479
480fn offset_is_representable(origin: f32, offset: f32) -> bool {
481 let result = origin + offset;
482 result.is_finite() && (offset == 0.0 || result != origin)
483}