cyborg/src/model.rs

97 lines
2.9 KiB
Rust

use crate::handle::*;
use crate::mesh::*;
use crate::pool::{MaterialData, TextureData};
use crate::renderer::Renderer;
use crate::scene::MeshInstance;
pub struct ObjModel {
pub mesh_handle: MeshHandle,
pub material_handle: MaterialHandle,
}
impl ObjModel {
pub fn load(ren: &mut Renderer) -> Self {
use tobj::*;
let model_data = include_bytes!("assets/viking_room/model.obj").to_vec();
let model_data = &mut model_data.as_slice();
let load_options = LoadOptions {
triangulate: true,
single_index: true,
..Default::default()
};
let (models, _mats) =
load_obj_buf(model_data, &load_options, |_| unimplemented!()).unwrap();
let mut vertices = Vec::new();
let mut indices = Vec::new();
let m = models.first().unwrap();
let index_base = vertices.len() as u32;
for i in 0..m.mesh.positions.len() / 3 {
let t = i * 3;
vertices.push(Vertex {
position: [
m.mesh.positions[t],
m.mesh.positions[t + 2],
-m.mesh.positions[t + 1],
],
normal: [
m.mesh.normals[t],
m.mesh.normals[t + 2],
-m.mesh.normals[t + 1],
],
tex_coords: [m.mesh.texcoords[i * 2], 1.0 - m.mesh.texcoords[i * 2 + 1]],
});
}
indices.extend(m.mesh.indices.iter().map(|i| i + index_base));
let mesh_data = MeshData { vertices, indices };
let mesh_handle = ren.mesh_pool.allocate(&ren.device, &mesh_data);
let albedo_data = include_bytes!("assets/viking_room/albedo.png");
let albedo = image::load_from_memory(albedo_data).unwrap();
use image::GenericImageView;
let dimensions = albedo.dimensions();
let albedo_rgb = albedo.as_rgb8().unwrap().to_vec();
let mut albedo_rgba = Vec::<u8>::new();
for rgb in albedo_rgb.chunks(3) {
albedo_rgba.extend_from_slice(rgb);
albedo_rgba.push(0xff);
}
let albedo_data = TextureData {
width: dimensions.0,
height: dimensions.1,
data: albedo_rgba,
};
let albedo = ren
.texture_pool
.allocate(&ren.device, &ren.queue, &albedo_data);
let material_data = MaterialData { albedo };
let material_handle =
ren.material_pool
.allocate(&ren.device, &ren.texture_pool, &material_data);
Self {
mesh_handle,
material_handle,
}
}
pub fn draw(&self, meshes: &mut Vec<MeshInstance>, transform: glam::Mat4) {
meshes.push(MeshInstance {
mesh: self.mesh_handle,
material: self.material_handle,
transform,
});
}
}