bevy/crates/bevy_text/src/font.rs
François bcd5318247 color spaces and representation (#1572)
`Color` can now be from different color spaces or representation:
- sRGB
- linear RGB
- HSL

This fixes #1193 by allowing the creation of const colors of all types, and writing it to the linear RGB color space for rendering.

I went with an enum after trying with two different types (`Color` and `LinearColor`) to be able to use the different variants in all place where a `Color` is expected.

I also added the HLS representation because:
- I like it
- it's useful for some case, see example `contributors`: I can just change the saturation and lightness while keeping the hue of the color
- I think adding another variant not using `red`, `green`, `blue` makes it clearer there are differences

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2021-03-17 23:59:51 +00:00

40 lines
1.3 KiB
Rust

use ab_glyph::{FontArc, FontVec, InvalidFont, OutlinedGlyph};
use bevy_reflect::TypeUuid;
use bevy_render::texture::{Extent3d, Texture, TextureDimension, TextureFormat};
#[derive(Debug, TypeUuid)]
#[uuid = "97059ac6-c9ba-4da9-95b6-bed82c3ce198"]
pub struct Font {
pub font: FontArc,
}
impl Font {
pub fn try_from_bytes(font_data: Vec<u8>) -> Result<Self, InvalidFont> {
let font = FontVec::try_from_vec(font_data)?;
let font = FontArc::new(font);
Ok(Font { font })
}
pub fn get_outlined_glyph_texture(outlined_glyph: OutlinedGlyph) -> Texture {
let bounds = outlined_glyph.px_bounds();
let width = bounds.width() as usize;
let height = bounds.height() as usize;
let mut alpha = vec![0.0; width * height];
outlined_glyph.draw(|x, y, v| {
alpha[y as usize * width + x as usize] = v;
});
// TODO: make this texture grayscale
Texture::new(
Extent3d::new(width as u32, height as u32, 1),
TextureDimension::D2,
alpha
.iter()
.map(|a| vec![255, 255, 255, (*a * 255.0) as u8])
.flatten()
.collect::<Vec<u8>>(),
TextureFormat::Rgba8UnormSrgb,
)
}
}