use std::{fmt, sync::Arc};
use super::TextRunLimits;
use bevy_ecs::prelude::Component;
use sim_engine::{Color, Layer, LogicalScreenPosition, ShapedLine};
use crate::screen::ScreenVisualError;
use super::{TextError, TextFont, TextPreparationSession};
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum TextAlignment {
#[default]
Left,
Center,
Right,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextMetrics {
advance: f32,
ascent: f32,
descent: f32,
line_height: f32,
glyph_count: usize,
}
impl TextMetrics {
pub const fn advance(self) -> f32 {
self.advance
}
pub const fn ascent(self) -> f32 {
self.ascent
}
pub const fn descent(self) -> f32 {
self.descent
}
pub const fn line_height(self) -> f32 {
self.line_height
}
pub const fn glyph_count(self) -> usize {
self.glyph_count
}
fn from_line(line: &ShapedLine) -> Self {
Self {
advance: line.advance(),
ascent: line.ascent(),
descent: line.descent(),
line_height: line.line_height(),
glyph_count: line.glyphs().len(),
}
}
}
struct PreparedText {
line: ShapedLine,
metrics: TextMetrics,
minimum_x: f32,
maximum_x: f32,
minimum_y: f32,
maximum_y: f32,
}
impl PreparedText {
fn new(font: &TextFont, text: &str) -> Result<Self, TextError> {
let settings = font.settings();
let line =
font.face()
.shape_line(text, &settings.style(1.0)?, &settings.layout_budget())?;
Self::from_line(font, line)
}
fn from_line(font: &TextFont, line: ShapedLine) -> Result<Self, TextError> {
let settings = font.settings();
line.validate_for(
font.face(),
&settings.style(1.0)?,
&settings.layout_budget(),
)?;
let metrics = TextMetrics::from_line(&line);
let run_budget = settings.atlas_limits().run_budget();
let required = metrics
.glyph_count
.checked_mul(TextRunLimits::RETAINED_BYTES_PER_GLYPH);
if metrics.glyph_count > run_budget.max_glyphs()
|| required.is_none_or(|bytes| bytes > run_budget.max_retained_bytes())
{
return Err(TextError::RunBudgetExceeded {
glyphs: metrics.glyph_count,
max_glyphs: run_budget.max_glyphs(),
required_bytes: required.unwrap_or(usize::MAX),
max_retained_bytes: run_budget.max_retained_bytes(),
});
}
let mut result = Self {
line,
metrics,
minimum_x: metrics.advance.min(0.0),
maximum_x: metrics.advance.max(0.0),
minimum_y: -metrics.ascent,
maximum_y: -metrics.descent,
};
for glyph in result.line.glyphs() {
result.minimum_x = result.minimum_x.min(glyph.logical_x());
result.maximum_x = result.maximum_x.max(glyph.logical_x());
result.minimum_y = result.minimum_y.min(glyph.logical_y());
result.maximum_y = result.maximum_y.max(glyph.logical_y());
}
Ok(result)
}
}
impl fmt::Debug for PreparedText {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PreparedText")
.field("text", &self.line.text())
.field("metrics", &self.metrics)
.finish_non_exhaustive()
}
}
impl PartialEq for PreparedText {
fn eq(&self, other: &Self) -> bool {
self.line.text() == other.line.text()
&& self.line.style() == other.line.style()
&& self.line.glyphs() == other.line.glyphs()
&& self.metrics == other.metrics
&& self.minimum_x == other.minimum_x
&& self.maximum_x == other.maximum_x
&& self.minimum_y == other.minimum_y
&& self.maximum_y == other.maximum_y
}
}
#[derive(Debug, Clone, PartialEq, Component)]
pub struct ScreenTextVisual {
font: TextFont,
prepared: Arc<PreparedText>,
position: LogicalScreenPosition,
alignment: TextAlignment,
tint: Color,
layer: Layer,
draw_order_depth: f32,
clip: crate::screen::ScreenClip,
}
impl ScreenTextVisual {
pub const fn clip(&self) -> crate::screen::ScreenClip {
self.clip
}
pub fn set_clip(&mut self, clip: crate::screen::ScreenClip) {
self.clip = clip;
}
pub fn new(
font: TextFont,
text: &str,
position: LogicalScreenPosition,
) -> Result<Self, TextError> {
validate_position(position)?;
let prepared = PreparedText::new(&font, text)?;
Self::from_prepared(font, prepared, position)
}
pub fn new_with_session(
session: &mut TextPreparationSession<'_>,
text: &str,
position: LogicalScreenPosition,
) -> Result<Self, TextError> {
validate_position(position)?;
let font = session.font().clone();
let prepared = PreparedText::from_line(&font, session.shape_line(text)?)?;
Self::from_prepared(font, prepared, position)
}
fn from_prepared(
font: TextFont,
prepared: PreparedText,
position: LogicalScreenPosition,
) -> Result<Self, TextError> {
let prepared = Arc::new(prepared);
let result = Self {
font,
prepared,
position,
alignment: TextAlignment::Left,
tint: Color::WHITE,
layer: Layer::DEFAULT,
draw_order_depth: 0.0,
clip: crate::screen::ScreenClip::Unclipped,
};
result.validate()?;
Ok(result)
}
pub const fn font(&self) -> &TextFont {
&self.font
}
pub fn text(&self) -> &str {
self.prepared.line.text()
}
pub fn shaped_line(&self) -> &ShapedLine {
&self.prepared.line
}
pub fn metrics(&self) -> TextMetrics {
self.prepared.metrics
}
pub fn glyph_count(&self) -> usize {
self.metrics().glyph_count()
}
pub fn retained_text_bytes(&self) -> usize {
self.retained_layout_bytes()
}
pub fn retained_layout_bytes(&self) -> usize {
self.prepared.line.allocation_bytes()
}
pub const fn position(&self) -> LogicalScreenPosition {
self.position
}
pub fn baseline_origin(&self) -> LogicalScreenPosition {
let offset = match self.alignment {
TextAlignment::Left => 0.0,
TextAlignment::Center => self.metrics().advance() * 0.5,
TextAlignment::Right => self.metrics().advance(),
};
let position = self.position.to_vec2();
LogicalScreenPosition::new(position.x() - offset, position.y())
}
pub const fn alignment(&self) -> TextAlignment {
self.alignment
}
pub const fn tint(&self) -> Color {
self.tint
}
pub const fn layer(&self) -> Layer {
self.layer
}
pub const fn draw_order_depth(&self) -> f32 {
self.draw_order_depth
}
pub fn set_text(&mut self, text: &str) -> Result<(), TextError> {
if self.text() == text {
return Ok(());
}
let mut candidate = self.clone();
candidate.prepared = Arc::new(PreparedText::new(&self.font, text)?);
candidate.validate()?;
*self = candidate;
Ok(())
}
pub fn set_text_with_session(
&mut self,
session: &mut TextPreparationSession<'_>,
text: &str,
) -> Result<(), TextError> {
if session.font() != &self.font {
return Err(sim_engine::ShapedLineError::FontMismatch.into());
}
if self.text() == text {
return Ok(());
}
let prepared = PreparedText::from_line(&self.font, session.shape_line(text)?)?;
let mut candidate = self.clone();
candidate.prepared = Arc::new(prepared);
candidate.validate()?;
*self = candidate;
Ok(())
}
pub fn set_font(&mut self, font: TextFont) -> Result<(), TextError> {
if self.font == font {
return Ok(());
}
let mut candidate = self.clone();
candidate.prepared = Arc::new(PreparedText::new(&font, self.text())?);
candidate.font = font;
candidate.validate()?;
*self = candidate;
Ok(())
}
pub fn set_position(&mut self, position: LogicalScreenPosition) -> Result<(), TextError> {
let mut candidate = self.clone();
candidate.position = position;
candidate.validate()?;
*self = candidate;
Ok(())
}
pub fn set_alignment(&mut self, alignment: TextAlignment) -> Result<(), TextError> {
let mut candidate = self.clone();
candidate.alignment = alignment;
candidate.validate()?;
*self = candidate;
Ok(())
}
pub fn set_tint(&mut self, tint: Color) -> Result<(), TextError> {
if !tint.is_normalized() {
return Err(ScreenVisualError::InvalidColor { value: tint }.into());
}
self.tint = tint;
Ok(())
}
pub fn set_layer(&mut self, layer: Layer) {
self.layer = layer;
}
pub fn set_draw_order_depth(&mut self, depth: f32) -> Result<(), TextError> {
if !depth.is_finite() {
return Err(ScreenVisualError::InvalidDrawOrderDepth { value: depth }.into());
}
self.draw_order_depth = depth;
Ok(())
}
pub(crate) fn validate(&self) -> Result<(), TextError> {
validate_position(self.position)?;
if !self.tint.is_normalized() {
return Err(ScreenVisualError::InvalidColor { value: self.tint }.into());
}
if !self.draw_order_depth.is_finite() {
return Err(ScreenVisualError::InvalidDrawOrderDepth {
value: self.draw_order_depth,
}
.into());
}
let baseline = self.baseline_origin().to_vec2();
let p = &self.prepared;
if !baseline.is_finite()
|| !offset_is_representable(baseline.x(), p.minimum_x)
|| !offset_is_representable(baseline.x(), p.maximum_x)
|| !offset_is_representable(baseline.y(), p.minimum_y)
|| !offset_is_representable(baseline.y(), p.maximum_y)
{
return Err(TextError::InvalidBounds {
position: self.position,
});
}
Ok(())
}
}
fn validate_position(position: LogicalScreenPosition) -> Result<(), TextError> {
if !position.is_finite() {
return Err(ScreenVisualError::InvalidPosition { value: position }.into());
}
Ok(())
}
fn offset_is_representable(origin: f32, offset: f32) -> bool {
let result = origin + offset;
result.is_finite() && (offset == 0.0 || result != origin)
}