zenyx-engine/src/model.rs

57 lines
1.8 KiB
Rust

use crate::Vertex;
use crate::texture::Texture;
use cgmath::{Vector2, Vector3, Zero};
use tobj::Model;
pub struct Material {
pub name: String,
pub diffuse_texture: Texture,
pub bind_group: wgpu::BindGroup,
}
pub struct Mesh {
pub name: String,
pub vertex_buffer: wgpu::Buffer,
pub index_buffer: wgpu::Buffer,
pub num_elements: u32,
pub material: usize,
}
pub fn parse_obj(obj: &Vec<Model>) -> (Vec<Vertex>, Vec<u32>) {
let mut combined_vertices = Vec::new();
let mut combined_indices = Vec::new();
let mut vertex_offset = 0;
for object in obj {
let mesh: &_ = &object.mesh;
let vertices: Vec<Vertex> = (0..mesh.positions.len() / 3)
.map(|i| Vertex {
position: Vector3::from([
mesh.positions[i * 3],
mesh.positions[i * 3 + 1],
mesh.positions[i * 3 + 2],
]),
color: cgmath::Vector3::from([1.0, 1.0, 1.0]),
normal: if !mesh.normals.is_empty() {
Vector3::from([
mesh.normals[i * 3],
mesh.normals[i * 3 + 1],
mesh.normals[i * 3 + 2],
])
} else {
Vector3::zero()
},
tex_coords: if !mesh.texcoords.is_empty() {
Vector2::from([mesh.texcoords[i * 2], mesh.texcoords[i * 2 + 1]])
} else {
Vector2::zero()
},
})
.collect();
combined_vertices.extend(vertices);
combined_indices.extend(mesh.indices.iter().map(|&index| index + vertex_offset));
vertex_offset += (mesh.positions.len() as u32) / 3;
}
(combined_vertices, combined_indices)
}