use wgpu_glyph::{GlyphBrush, ab_glyph::FontArc, GlyphBrushBuilder, Section, Text}; use wgpu::util::StagingBelt; use futures::executor::LocalPool; use futures::task::SpawnExt; const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0]; pub struct UserInterface { // Glyph drawing staging_belt: StagingBelt, local_pool: LocalPool, brush: GlyphBrush<()>, // Texts fps_text: String } impl UserInterface { pub fn new(device: &mut wgpu::Device, render_format: wgpu::TextureFormat) -> Self { let font = FontArc::try_from_slice(include_bytes!("../../assets/font.ttf")).unwrap(); Self { staging_belt: StagingBelt::new(1024), local_pool: LocalPool::new(), brush: GlyphBrushBuilder::using_font(font).build(device, render_format), fps_text: "-".to_string() } } fn print(&mut self, x: u32, y: u32, msg: &str) { let text = Text::new(msg).with_color(WHITE); self.brush.queue(Section { screen_position: (x as f32, y as f32), bounds: (text.scale.x * text.text.len() as f32, text.scale.y), text: vec![text], ..Section::default() }); } pub fn set_fps(&mut self, fps: f32) { self.fps_text = format!("FPS: {}", fps); } pub fn render(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, width: u32, height: u32) { // Print texts self.print(5, 5, &self.fps_text.clone()); // Draw self.brush.draw_queued(&device, &mut self.staging_belt, encoder, target, width, height).expect("Draw queued"); self.staging_belt.finish(); } pub fn recall(&mut self) { // Reset staging belt after drawing self.local_pool.spawner().spawn(self.staging_belt.recall()).expect("Recall staging belt"); self.local_pool.run_until_stalled(); } }