Skip to content
Snippets Groups Projects
Commit 231ab08a authored by Gino Valente's avatar Gino Valente
Browse files

Formatting

parent 74ff2849
No related branches found
No related tags found
No related merge requests found
...@@ -21,29 +21,22 @@ pub fn extract_texts( ...@@ -21,29 +21,22 @@ pub fn extract_texts(
_dpi: f32, _dpi: f32,
) -> Vec<ExtractQuadBundle> { ) -> Vec<ExtractQuadBundle> {
let mut extracted_texts = Vec::new(); let mut extracted_texts = Vec::new();
let (background_color, text_layout, layout, font, properties) = let (background_color, text_layout, layout, font, properties) = match render_primitive {
match render_primitive { RenderPrimitive::Text {
RenderPrimitive::Text { color,
color, text_layout,
text_layout, layout,
layout, font,
font, properties,
properties, ..
.. } => (color, text_layout, layout, font, *properties),
} => ( _ => panic!(""),
color, };
text_layout,
layout,
font,
*properties,
),
_ => panic!(""),
};
let font_handle = font_mapping.get_handle(font.clone()).unwrap(); let font_handle = font_mapping.get_handle(font.clone()).unwrap();
let font = match fonts.get(font_handle.clone()) { let font = match fonts.get(font_handle.clone()) {
Some(font) => font, Some(font) => font,
None => return Vec::new() None => return Vec::new(),
}; };
let base_position = Vec2::new(layout.posx, layout.posy + properties.font_size); let base_position = Vec2::new(layout.posx, layout.posy + properties.font_size);
......
use kayak_font::{TextLayout, TextProperties};
use crate::{ use crate::{
color::Color, color::Color,
layout_cache::Rect, layout_cache::Rect,
render_command::RenderCommand, render_command::RenderCommand,
styles::{Corner, Edge, Style}, styles::{Corner, Edge, Style},
}; };
use kayak_font::{TextLayout, TextProperties};
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum RenderPrimitive { pub enum RenderPrimitive {
......
use bevy::{ use bevy::{
DefaultPlugins,
math::{const_vec2, Vec2}, math::{const_vec2, Vec2},
prelude::{App as BevyApp, AssetServer, Commands, Component, Handle, Input, KeyCode, Query, Res, ResMut, Sprite, SpriteBundle, Transform, With, Without}, prelude::{
App as BevyApp, AssetServer, Commands, Component, Handle, Input, KeyCode, Query, Res,
ResMut, Sprite, SpriteBundle, Transform, With, Without,
},
render::{camera::OrthographicCameraBundle, color::Color}, render::{camera::OrthographicCameraBundle, color::Color},
window::WindowDescriptor, window::WindowDescriptor,
DefaultPlugins,
}; };
use kayak_font::{Alignment, bevy::KayakFontPlugin, KayakFont}; use kayak_font::{bevy::KayakFontPlugin, Alignment, KayakFont};
use renderer::{FontRenderPlugin, Text}; use renderer::{FontRenderPlugin, Text};
mod renderer; mod renderer;
...@@ -14,7 +17,8 @@ mod renderer; ...@@ -14,7 +17,8 @@ mod renderer;
const FONT_SIZE: f32 = 24.0; const FONT_SIZE: f32 = 24.0;
const INITIAL_SIZE: Vec2 = const_vec2!([400.0, 300.0]); const INITIAL_SIZE: Vec2 = const_vec2!([400.0, 300.0]);
const INITIAL_POS: Vec2 = const_vec2!([-200.0, 0.0]); const INITIAL_POS: Vec2 = const_vec2!([-200.0, 0.0]);
const INSTRUCTIONS: &str = "Press 'A' and 'D' to shrink and grow the text box.\nPress 'Space' to cycle text alignment."; const INSTRUCTIONS: &str =
"Press 'A' and 'D' to shrink and grow the text box.\nPress 'Space' to cycle text alignment.";
#[derive(Component)] #[derive(Component)]
struct Instructions; struct Instructions;
...@@ -37,16 +41,19 @@ fn startup(mut commands: Commands, asset_server: Res<AssetServer>) { ...@@ -37,16 +41,19 @@ fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
}) })
.insert(font_handle.clone()); .insert(font_handle.clone());
commands.spawn() commands.spawn().insert_bundle(SpriteBundle {
.insert_bundle(SpriteBundle { sprite: Sprite {
sprite: Sprite { color: Color::DARK_GRAY,
color: Color::DARK_GRAY, custom_size: Some(INITIAL_SIZE),
custom_size: Some(INITIAL_SIZE),
..Default::default()
},
transform: Transform::from_xyz((INITIAL_SIZE.x / 2.0) + INITIAL_POS.x, (-INITIAL_SIZE.y / 4.0) - 20.0, -0.05),
..Default::default() ..Default::default()
}); },
transform: Transform::from_xyz(
(INITIAL_SIZE.x / 2.0) + INITIAL_POS.x,
(-INITIAL_SIZE.y / 4.0) - 20.0,
-0.05,
),
..Default::default()
});
commands commands
.spawn() .spawn()
...@@ -63,12 +70,18 @@ fn startup(mut commands: Commands, asset_server: Res<AssetServer>) { ...@@ -63,12 +70,18 @@ fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
.insert(font_handle.clone()); .insert(font_handle.clone());
} }
fn control_text(keyboard_input: ResMut<Input<KeyCode>>, mut text_box: Query<&mut Text, Without<Instructions>>, mut instructions: Query<&mut Text, With<Instructions>>, mut bg: Query<&mut Sprite>) { fn control_text(
let speed = if keyboard_input.pressed(KeyCode::LShift) || keyboard_input.pressed(KeyCode::RShift) { keyboard_input: ResMut<Input<KeyCode>>,
2.5 mut text_box: Query<&mut Text, Without<Instructions>>,
} else { mut instructions: Query<&mut Text, With<Instructions>>,
1.0 mut bg: Query<&mut Sprite>,
}; ) {
let speed =
if keyboard_input.pressed(KeyCode::LShift) || keyboard_input.pressed(KeyCode::RShift) {
2.5
} else {
1.0
};
if keyboard_input.just_pressed(KeyCode::Space) { if keyboard_input.just_pressed(KeyCode::Space) {
for mut text in text_box.iter_mut() { for mut text in text_box.iter_mut() {
...@@ -95,7 +108,9 @@ fn control_text(keyboard_input: ResMut<Input<KeyCode>>, mut text_box: Query<&mut ...@@ -95,7 +108,9 @@ fn control_text(keyboard_input: ResMut<Input<KeyCode>>, mut text_box: Query<&mut
let mut instructions = instructions.single_mut(); let mut instructions = instructions.single_mut();
instructions.content = String::from(INSTRUCTIONS); instructions.content = String::from(INSTRUCTIONS);
instructions.content.push_str(&format!("\nSize: {}", text.size.x)); instructions
.content
.push_str(&format!("\nSize: {}", text.size.x));
} }
for mut sprite in bg.iter_mut() { for mut sprite in bg.iter_mut() {
...@@ -117,4 +132,4 @@ fn main() { ...@@ -117,4 +132,4 @@ fn main() {
.add_startup_system(startup) .add_startup_system(startup)
.add_system(control_text) .add_system(control_text)
.run(); .run();
} }
\ No newline at end of file
...@@ -19,7 +19,6 @@ pub fn extract( ...@@ -19,7 +19,6 @@ pub fn extract(
for (text, font_handle) in texts.iter() { for (text, font_handle) in texts.iter() {
if let Some(font) = fonts.get(font_handle) { if let Some(font) = fonts.get(font_handle) {
let properties = TextProperties { let properties = TextProperties {
font_size: text.font_size, font_size: text.font_size,
line_height: text.line_height, line_height: text.line_height,
...@@ -28,10 +27,7 @@ pub fn extract( ...@@ -28,10 +27,7 @@ pub fn extract(
..Default::default() ..Default::default()
}; };
let text_layout = font.measure( let text_layout = font.measure(&text.content, properties);
&text.content,
properties
);
for glyph_rect in text_layout.glyphs() { for glyph_rect in text_layout.glyphs() {
let mut position = Vec2::from(glyph_rect.position); let mut position = Vec2::from(glyph_rect.position);
......
...@@ -5,8 +5,8 @@ use bevy::{prelude::Handle, reflect::TypeUuid, render::texture::Image}; ...@@ -5,8 +5,8 @@ use bevy::{prelude::Handle, reflect::TypeUuid, render::texture::Image};
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
use crate::layout::{Alignment, Line, TextLayout}; use crate::layout::{Alignment, Line, TextLayout};
use crate::{utility, Sdf, TextProperties, Glyph, GlyphRect};
use crate::utility::{BreakableWord, MISSING, SPACE}; use crate::utility::{BreakableWord, MISSING, SPACE};
use crate::{utility, Glyph, GlyphRect, Sdf, TextProperties};
#[cfg(feature = "bevy_renderer")] #[cfg(feature = "bevy_renderer")]
#[derive(Debug, Clone, TypeUuid, PartialEq)] #[derive(Debug, Clone, TypeUuid, PartialEq)]
...@@ -31,9 +31,17 @@ pub struct KayakFont { ...@@ -31,9 +31,17 @@ pub struct KayakFont {
impl KayakFont { impl KayakFont {
pub fn new(sdf: Sdf, #[cfg(feature = "bevy_renderer")] atlas_image: Handle<Image>) -> Self { pub fn new(sdf: Sdf, #[cfg(feature = "bevy_renderer")] atlas_image: Handle<Image>) -> Self {
let max_glyph_size = sdf.max_glyph_size(); let max_glyph_size = sdf.max_glyph_size();
assert!(sdf.glyphs.len() < u32::MAX as usize, "SDF contains too many glyphs"); assert!(
sdf.glyphs.len() < u32::MAX as usize,
let char_ids: HashMap<char, u32> = sdf.glyphs.iter().enumerate().map(|(idx, glyph)| (glyph.unicode, idx as u32)).collect(); "SDF contains too many glyphs"
);
let char_ids: HashMap<char, u32> = sdf
.glyphs
.iter()
.enumerate()
.map(|(idx, glyph)| (glyph.unicode, idx as u32))
.collect();
let missing_glyph = if char_ids.contains_key(&MISSING) { let missing_glyph = if char_ids.contains_key(&MISSING) {
Some(MISSING) Some(MISSING)
...@@ -43,7 +51,6 @@ impl KayakFont { ...@@ -43,7 +51,6 @@ impl KayakFont {
None None
}; };
Self { Self {
sdf, sdf,
#[cfg(feature = "bevy_renderer")] #[cfg(feature = "bevy_renderer")]
...@@ -127,7 +134,6 @@ impl KayakFont { ...@@ -127,7 +134,6 @@ impl KayakFont {
let words = utility::split_breakable_words(content).collect::<Vec<_>>(); let words = utility::split_breakable_words(content).collect::<Vec<_>>();
for (index, word) in words.iter().enumerate() { for (index, word) in words.iter().enumerate() {
// Check if this is the last word of the line. // Check if this is the last word of the line.
let mut will_break = break_index.map(|idx| index + 1 == idx).unwrap_or_default(); let mut will_break = break_index.map(|idx| index + 1 == idx).unwrap_or_default();
...@@ -147,7 +153,8 @@ impl KayakFont { ...@@ -147,7 +153,8 @@ impl KayakFont {
// Skip finding a line break since we're guaranteed not to find one until `idx` // Skip finding a line break since we're guaranteed not to find one until `idx`
} }
_ => { _ => {
let (next_break, next_skip) = self.find_next_break(index, line.width, properties, &words); let (next_break, next_skip) =
self.find_next_break(index, line.width, properties, &words);
break_index = next_break; break_index = next_break;
skip_until_index = next_skip; skip_until_index = next_skip;
will_break |= break_index.map(|idx| index + 1 == idx).unwrap_or_default(); will_break |= break_index.map(|idx| index + 1 == idx).unwrap_or_default();
...@@ -175,10 +182,12 @@ impl KayakFont { ...@@ -175,10 +182,12 @@ impl KayakFont {
} else if utility::is_tab(c) { } else if utility::is_tab(c) {
line.width += tab_width; line.width += tab_width;
} else { } else {
let glyph = self.get_glyph(c).or_else(|| if let Some(missing) = self.missing_glyph { let glyph = self.get_glyph(c).or_else(|| {
self.get_glyph(missing) if let Some(missing) = self.missing_glyph {
} else { self.get_glyph(missing)
None } else {
None
}
}); });
if let Some(glyph) = glyph { if let Some(glyph) = glyph {
...@@ -262,7 +271,13 @@ impl KayakFont { ...@@ -262,7 +271,13 @@ impl KayakFont {
/// * `properties`: The associated text properties /// * `properties`: The associated text properties
/// * `words`: The list of breakable words /// * `words`: The list of breakable words
/// ///
fn find_next_break(&self, curr_index: usize, line_width: f32, properties: TextProperties, words: &[BreakableWord]) -> (Option<usize>, Option<usize>) { fn find_next_break(
&self,
curr_index: usize,
line_width: f32,
properties: TextProperties,
words: &[BreakableWord],
) -> (Option<usize>, Option<usize>) {
// Line Break Rules: // Line Break Rules:
// //
// Break before Next if... // Break before Next if...
...@@ -396,7 +411,9 @@ impl KayakFont { ...@@ -396,7 +411,9 @@ impl KayakFont {
/// ///
/// Returns `None` if no glyph was found. /// Returns `None` if no glyph was found.
pub fn get_glyph(&self, c: char) -> Option<&Glyph> { pub fn get_glyph(&self, c: char) -> Option<&Glyph> {
self.char_ids.get(&c).and_then(|index| self.sdf.glyphs.get(*index as usize)) self.char_ids
.get(&c)
.and_then(|index| self.sdf.glyphs.get(*index as usize))
} }
/// Calculates the appropriate glyph size for a desired font size. /// Calculates the appropriate glyph size for a desired font size.
...@@ -405,6 +422,9 @@ impl KayakFont { ...@@ -405,6 +422,9 @@ impl KayakFont {
/// in the atlas. /// in the atlas.
fn calc_glyph_size(&self, font_size: f32) -> (f32, f32) { fn calc_glyph_size(&self, font_size: f32) -> (f32, f32) {
let font_scale = font_size / self.sdf.atlas.font_size; let font_scale = font_size / self.sdf.atlas.font_size;
(self.max_glyph_size.0 * font_scale, self.max_glyph_size.1 * font_scale) (
self.max_glyph_size.0 * font_scale,
self.max_glyph_size.1 * font_scale,
)
} }
} }
...@@ -92,8 +92,18 @@ pub struct TextLayout { ...@@ -92,8 +92,18 @@ pub struct TextLayout {
impl TextLayout { impl TextLayout {
/// Create a new [`TextLayout`]. /// Create a new [`TextLayout`].
pub fn new(glyphs: Vec<GlyphRect>, lines: Vec<Line>, size: (f32, f32), properties: TextProperties) -> Self { pub fn new(
Self { glyphs, lines, size, properties } glyphs: Vec<GlyphRect>,
lines: Vec<Line>,
size: (f32, f32),
properties: TextProperties,
) -> Self {
Self {
glyphs,
lines,
size,
properties,
}
} }
/// Returns the calculated lines for the text content. /// Returns the calculated lines for the text content.
......
...@@ -55,7 +55,11 @@ pub struct BreakableWordIter<'a> { ...@@ -55,7 +55,11 @@ pub struct BreakableWordIter<'a> {
impl<'a> BreakableWordIter<'a> { impl<'a> BreakableWordIter<'a> {
pub fn new(text: &'a str) -> Self { pub fn new(text: &'a str) -> Self {
Self { text, iter: LineBreakIterator::new(text), index: 0 } Self {
text,
iter: LineBreakIterator::new(text),
index: 0,
}
} }
} }
...@@ -78,4 +82,3 @@ impl<'a> Iterator for BreakableWordIter<'a> { ...@@ -78,4 +82,3 @@ impl<'a> Iterator for BreakableWordIter<'a> {
self.iter.size_hint() self.iter.size_hint()
} }
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment