chore(all): fix warnings

This commit is contained in:
lisk77 2025-11-02 13:14:41 +01:00
parent c7f0412eff
commit 81bc1cb790
14 changed files with 471 additions and 513 deletions

View file

@ -1,120 +1,120 @@
use image::{DynamicImage, Rgba, RgbaImage};
use ab_glyph::{FontArc, PxScale, ScaleFont, Glyph, point, Font as AbFont};
use comet_log::debug;
use crate::texture_atlas::{TextureAtlas, TextureRegion};
use ab_glyph::{point, Font as AbFont, FontArc, Glyph, PxScale, ScaleFont};
use image::{DynamicImage, Rgba, RgbaImage};
pub struct GlyphData {
pub name: String,
pub render: DynamicImage,
pub advance: f32,
pub offset_x: f32,
pub offset_y: f32,
pub name: String,
pub render: DynamicImage,
pub advance: f32,
pub offset_x: f32,
pub offset_y: f32,
}
pub struct Font {
name: String,
size: f32,
line_height: f32,
glyphs: TextureAtlas,
name: String,
size: f32,
line_height: f32,
glyphs: TextureAtlas,
}
impl Font {
pub fn new(path: &str, size: f32) -> Self {
let (glyphs, line_height) = Self::generate_atlas(path, size);
Font {
name: path.to_string(),
size,
line_height,
glyphs
}
}
pub fn new(path: &str, size: f32) -> Self {
let (glyphs, line_height) = Self::generate_atlas(path, size);
Font {
name: path.to_string(),
size,
line_height,
glyphs,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn name(&self) -> &str {
&self.name
}
pub fn size(&self) -> f32 {
self.size
}
pub fn size(&self) -> f32 {
self.size
}
pub fn line_height(&self) -> f32 {
self.line_height
}
pub fn line_height(&self) -> f32 {
self.line_height
}
pub fn glyphs(&self) -> &TextureAtlas {
&self.glyphs
}
pub fn glyphs(&self) -> &TextureAtlas {
&self.glyphs
}
pub fn get_glyph(&self, ch: char) -> Option<&TextureRegion> {
self.glyphs.textures().get(&ch.to_string())
}
pub fn get_glyph(&self, ch: char) -> Option<&TextureRegion> {
self.glyphs.textures().get(&ch.to_string())
}
fn generate_atlas(path: &str, size: f32) -> (TextureAtlas, f32) {
let font_data = std::fs::read(path).expect("Failed to read font file");
let font = FontArc::try_from_vec(font_data).expect("Failed to load font");
fn generate_atlas(path: &str, size: f32) -> (TextureAtlas, f32) {
let font_data = std::fs::read(path).expect("Failed to read font file");
let font = FontArc::try_from_vec(font_data).expect("Failed to load font");
let scale = PxScale::from(size);
let scaled_font = font.as_scaled(scale);
let scale = PxScale::from(size);
let scaled_font = font.as_scaled(scale);
let mut glyphs: Vec<GlyphData> = Vec::new();
let mut glyphs: Vec<GlyphData> = Vec::new();
for code_point in 0x0020..=0x007E {
if let Some(ch) = std::char::from_u32(code_point) {
let glyph_id = font.glyph_id(ch);
if glyph_id.0 == 0 {
continue;
}
for code_point in 0x0020..=0x007E {
if let Some(ch) = std::char::from_u32(code_point) {
let glyph_id = font.glyph_id(ch);
if glyph_id.0 == 0 {
continue;
}
if ch == ' ' {
let advance = scaled_font.h_advance(glyph_id);
glyphs.push(GlyphData {
name: ch.to_string(),
render: DynamicImage::new_rgba8(0, 0), // no bitmap
advance,
offset_x: 0.0,
offset_y: 0.0,
});
continue;
}
if ch == ' ' {
let advance = scaled_font.h_advance(glyph_id);
glyphs.push(GlyphData {
name: ch.to_string(),
render: DynamicImage::new_rgba8(0, 0), // no bitmap
advance,
offset_x: 0.0,
offset_y: 0.0,
});
continue;
}
let glyph = Glyph {
id: glyph_id,
scale,
position: point(0.0, 0.0),
};
let glyph = Glyph {
id: glyph_id,
scale,
position: point(0.0, 0.0),
};
if let Some(outline) = scaled_font.outline_glyph(glyph.clone()) {
let bounds = outline.px_bounds();
let width = bounds.width().ceil() as u32;
let height = bounds.height().ceil() as u32;
if let Some(outline) = scaled_font.outline_glyph(glyph.clone()) {
let bounds = outline.px_bounds();
let width = bounds.width().ceil() as u32;
let height = bounds.height().ceil() as u32;
if width == 0 || height == 0 {
continue;
}
if width == 0 || height == 0 {
continue;
}
let mut image = RgbaImage::new(width, height);
for pixel in image.pixels_mut() {
*pixel = Rgba([0, 0, 0, 0]);
}
let mut image = RgbaImage::new(width, height);
for pixel in image.pixels_mut() {
*pixel = Rgba([0, 0, 0, 0]);
}
outline.draw(|x, y, v| {
let alpha = (v * 255.0) as u8;
image.put_pixel(x, y, Rgba([255, 255, 255, alpha]));
});
outline.draw(|x, y, v| {
let alpha = (v * 255.0) as u8;
image.put_pixel(x, y, Rgba([255, 255, 255, alpha]));
});
glyphs.push(
GlyphData {
name: ch.to_string(),
render: DynamicImage::ImageRgba8(image),
advance: scaled_font.h_advance(glyph_id),
offset_x: bounds.min.x,
offset_y: bounds.min.y,
}
)
}
}
}
glyphs.push(GlyphData {
name: ch.to_string(),
render: DynamicImage::ImageRgba8(image),
advance: scaled_font.h_advance(glyph_id),
offset_x: bounds.min.x,
offset_y: bounds.min.y,
})
}
}
}
(TextureAtlas::from_glyphs(glyphs), scaled_font.ascent() - scaled_font.descent())
}
}
(
TextureAtlas::from_glyphs(glyphs),
scaled_font.ascent() - scaled_font.descent(),
)
}
}

View file

@ -1,182 +1,181 @@
use std::{
collections::HashMap, path::Path
use std::{collections::HashMap, path::Path};
use crate::{
texture,
texture_atlas::{TextureAtlas, TextureRegion},
};
use wgpu::{Device, FilterMode, Queue, TextureFormat, TextureUsages};
use crate::{texture, Texture};
use crate::texture_atlas::{TextureAtlas, TextureRegion};
pub struct ResourceManager {
texture_atlas: TextureAtlas,
data_files: HashMap<String, String>
texture_atlas: TextureAtlas,
data_files: HashMap<String, String>,
}
impl ResourceManager {
pub fn new() -> Self {
Self {
texture_atlas: TextureAtlas::empty(),
data_files: HashMap::new()
}
}
pub fn new() -> Self {
Self {
texture_atlas: TextureAtlas::empty(),
data_files: HashMap::new(),
}
}
pub fn texture_atlas(&self) -> &TextureAtlas {
&self.texture_atlas
}
pub fn texture_atlas(&self) -> &TextureAtlas {
&self.texture_atlas
}
pub fn texture_locations(&self) -> &HashMap<String, TextureRegion> {
&self.texture_atlas.textures()
}
pub fn texture_locations(&self) -> &HashMap<String, TextureRegion> {
&self.texture_atlas.textures()
}
pub fn data_files(&self) -> &HashMap<String, String> {
&self.data_files
}
pub fn data_files(&self) -> &HashMap<String, String> {
&self.data_files
}
pub fn set_texture_atlas(&mut self, texture_atlas: TextureAtlas) {
self.texture_atlas = texture_atlas;
pub fn set_texture_atlas(&mut self, texture_atlas: TextureAtlas) {
self.texture_atlas = texture_atlas;
// This is just for testing purposes
//self.texture_locations.insert("normal_comet.png".to_string(), ([0,0], [15,15]));
//self.texture_locations.insert("green_comet.png".to_string(), ([0,15], [15,31]));
}
// This is just for testing purposes
//self.texture_locations.insert("normal_comet.png".to_string(), ([0,0], [15,15]));
//self.texture_locations.insert("green_comet.png".to_string(), ([0,15], [15,31]));
}
pub fn create_texture_atlas(&mut self, paths: Vec<String>) {
self.texture_atlas = TextureAtlas::from_texture_paths(paths)
}
pub fn create_texture_atlas(&mut self, paths: Vec<String>) {
self.texture_atlas = TextureAtlas::from_texture_paths(paths)
}
pub async fn load_string(&self, file_name: &str) -> anyhow::Result<String> {
let path = Path::new(std::env::var("OUT_DIR")?.as_str())
.join("res")
.join(file_name);
let txt = std::fs::read_to_string(path)?;
pub async fn load_string(&self, file_name: &str) -> anyhow::Result<String> {
let path = Path::new(std::env::var("OUT_DIR")?.as_str())
.join("res")
.join(file_name);
let txt = std::fs::read_to_string(path)?;
Ok(txt)
}
Ok(txt)
}
pub async fn load_binary(&self, file_name: &str) -> anyhow::Result<Vec<u8>> {
let path = Path::new(std::env::var("OUT_DIR").unwrap().as_str())
.join("res")
.join(file_name);
let data = std::fs::read(path)?;
pub async fn load_binary(&self, file_name: &str) -> anyhow::Result<Vec<u8>> {
let path = Path::new(std::env::var("OUT_DIR").unwrap().as_str())
.join("res")
.join(file_name);
let data = std::fs::read(path)?;
Ok(data)
}
Ok(data)
}
pub async fn load_texture(
&self,
file_name: &str,
is_normal_map: bool,
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> anyhow::Result<texture::Texture> {
let data = self.load_binary(file_name).await?;
texture::Texture::from_bytes(device, queue, &data, file_name, is_normal_map)
}
pub async fn load_texture(
&self,
file_name: &str,
is_normal_map: bool,
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> anyhow::Result<texture::Texture> {
let data = self.load_binary(file_name).await?;
texture::Texture::from_bytes(device, queue, &data, file_name, is_normal_map)
}
/*pub async fn load_model(
&self,
file_name: &str,
device: &wgpu::Device,
queue: &wgpu::Queue,
layout: &wgpu::BindGroupLayout,
) -> anyhow::Result<model::Model> {
let obj_text = self.load_string(file_name).await?;
let obj_cursor = Cursor::new(obj_text);
let mut obj_reader = BufReader::new(obj_cursor);
/*pub async fn load_model(
&self,
file_name: &str,
device: &wgpu::Device,
queue: &wgpu::Queue,
layout: &wgpu::BindGroupLayout,
) -> anyhow::Result<model::Model> {
let obj_text = self.load_string(file_name).await?;
let obj_cursor = Cursor::new(obj_text);
let mut obj_reader = BufReader::new(obj_cursor);
let (models, obj_materials) = tobj::load_obj_buf_async(
&mut obj_reader,
&tobj::LoadOptions {
triangulate: true,
single_index: true,
..Default::default()
},
|p| async move {
let mat_text = self.load_string(&p).await.unwrap();
tobj::load_mtl_buf(&mut BufReader::new(Cursor::new(mat_text)))
},
)
.await?;
let (models, obj_materials) = tobj::load_obj_buf_async(
&mut obj_reader,
&tobj::LoadOptions {
triangulate: true,
single_index: true,
..Default::default()
},
|p| async move {
let mat_text = self.load_string(&p).await.unwrap();
tobj::load_mtl_buf(&mut BufReader::new(Cursor::new(mat_text)))
},
)
.await?;
let mut materials = Vec::new();
for m in obj_materials? {
let diffuse_texture = self.load_texture(&m.diffuse_texture, false, device, queue).await?;
let normal_texture = self.load_texture(&m.normal_texture, true, device, queue).await?;
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&diffuse_texture.view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&diffuse_texture.sampler),
},
],
label: None,
});
let mut materials = Vec::new();
for m in obj_materials? {
let diffuse_texture = self.load_texture(&m.diffuse_texture, false, device, queue).await?;
let normal_texture = self.load_texture(&m.normal_texture, true, device, queue).await?;
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&diffuse_texture.view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&diffuse_texture.sampler),
},
],
label: None,
});
materials.push(model::Material {
name: m.name,
diffuse_texture,
bind_group,
});
}
materials.push(model::Material {
name: m.name,
diffuse_texture,
bind_group,
});
}
let meshes = models
.into_iter()
.map(|m| {
let vertices = (0..m.mesh.positions.len() / 3)
.map(|i| {
if m.mesh.normals.is_empty() {
model::ModelVertex {
position: [
m.mesh.positions[i * 3],
m.mesh.positions[i * 3 + 1],
m.mesh.positions[i * 3 + 2],
],
tex_coords: [m.mesh.texcoords[i * 2], 1.0 - m.mesh.texcoords[i * 2 + 1]],
normal: [0.0, 0.0, 0.0],
}
} else {
model::ModelVertex {
position: [
m.mesh.positions[i * 3],
m.mesh.positions[i * 3 + 1],
m.mesh.positions[i * 3 + 2],
],
tex_coords: [m.mesh.texcoords[i * 2], 1.0 - m.mesh.texcoords[i * 2 + 1]],
normal: [
m.mesh.normals[i * 3],
m.mesh.normals[i * 3 + 1],
m.mesh.normals[i * 3 + 2],
],
}
}
})
.collect::<Vec<_>>();
let meshes = models
.into_iter()
.map(|m| {
let vertices = (0..m.mesh.positions.len() / 3)
.map(|i| {
if m.mesh.normals.is_empty() {
model::ModelVertex {
position: [
m.mesh.positions[i * 3],
m.mesh.positions[i * 3 + 1],
m.mesh.positions[i * 3 + 2],
],
tex_coords: [m.mesh.texcoords[i * 2], 1.0 - m.mesh.texcoords[i * 2 + 1]],
normal: [0.0, 0.0, 0.0],
}
} else {
model::ModelVertex {
position: [
m.mesh.positions[i * 3],
m.mesh.positions[i * 3 + 1],
m.mesh.positions[i * 3 + 2],
],
tex_coords: [m.mesh.texcoords[i * 2], 1.0 - m.mesh.texcoords[i * 2 + 1]],
normal: [
m.mesh.normals[i * 3],
m.mesh.normals[i * 3 + 1],
m.mesh.normals[i * 3 + 2],
],
}
}
})
.collect::<Vec<_>>();
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(&format!("{:?} Vertex Buffer", file_name)),
contents: bytemuck::cast_slice(&vertices),
usage: wgpu::BufferUsages::VERTEX,
});
let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(&format!("{:?} Index Buffer", file_name)),
contents: bytemuck::cast_slice(&m.mesh.indices),
usage: wgpu::BufferUsages::INDEX,
});
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(&format!("{:?} Vertex Buffer", file_name)),
contents: bytemuck::cast_slice(&vertices),
usage: wgpu::BufferUsages::VERTEX,
});
let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(&format!("{:?} Index Buffer", file_name)),
contents: bytemuck::cast_slice(&m.mesh.indices),
usage: wgpu::BufferUsages::INDEX,
});
model::Mesh {
name: file_name.to_string(),
vertex_buffer,
index_buffer,
num_elements: m.mesh.indices.len() as u32,
material: m.mesh.material_id.unwrap_or(0),
}
})
.collect::<Vec<_>>();
model::Mesh {
name: file_name.to_string(),
vertex_buffer,
index_buffer,
num_elements: m.mesh.indices.len() as u32,
material: m.mesh.material_id.unwrap_or(0),
}
})
.collect::<Vec<_>>();
Ok(model::Model { meshes, materials })
}*/
Ok(model::Model { meshes, materials })
}*/
}

View file

@ -334,7 +334,7 @@ impl TextureAtlas {
for glyph_name in glyph_names {
let region = font.glyphs().textures().get(&glyph_name).unwrap();
let (u0, v0, u1, v1) = (region.u0(), region.v0(), region.u1(), region.v1());
let (u0, v0) = (region.u0(), region.v0());
let (width, height) = region.dimensions();
let src_x = (u0 * font.glyphs().atlas().width() as f32) as u32;

View file

@ -1,55 +1,53 @@
use wgpu::Color;
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable, PartialEq)]
pub struct Vertex {
position: [f32; 3],
tex_coords: [f32; 2],
color: [f32; 4]
position: [f32; 3],
tex_coords: [f32; 2],
color: [f32; 4],
}
impl Vertex {
pub fn new(position: [f32; 3], tex_coords: [f32; 2], color: [f32; 4]) -> Self {
Self {
position,
tex_coords,
color
}
}
pub fn new(position: [f32; 3], tex_coords: [f32; 2], color: [f32; 4]) -> Self {
Self {
position,
tex_coords,
color,
}
}
pub fn set_position(&mut self, new_position: [f32;3]) {
self.position = new_position
}
pub fn set_position(&mut self, new_position: [f32; 3]) {
self.position = new_position
}
pub fn set_tex_coords(&mut self, new_tex_coords: [f32; 2]) {
self.tex_coords = new_tex_coords
}
pub fn set_tex_coords(&mut self, new_tex_coords: [f32; 2]) {
self.tex_coords = new_tex_coords
}
pub fn set_color(&mut self, new_color: [f32; 4]) {
self.color = new_color
}
pub fn set_color(&mut self, new_color: [f32; 4]) {
self.color = new_color
}
pub fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 1,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 5]>() as wgpu::BufferAddress,
shader_location: 2,
format: wgpu::VertexFormat::Float32x4,
}
]
}
}
}
pub fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 1,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 5]>() as wgpu::BufferAddress,
shader_location: 2,
format: wgpu::VertexFormat::Float32x4,
},
],
}
}
}