couch-rust/src/model.rs

48 lines
1.4 KiB
Rust
Raw Normal View History

2022-04-07 16:18:46 -05:00
extern crate gltf;
2022-04-08 16:49:31 -05:00
use glium::{ VertexBuffer, IndexBuffer };
2022-04-07 16:18:46 -05:00
#[derive(Copy, Clone)]
struct Vertex {
position: [f32; 3],
2022-04-08 16:49:31 -05:00
normal: [f32; 3],
2022-04-07 16:18:46 -05:00
}
2022-04-08 16:49:31 -05:00
implement_vertex!(Vertex, position, normal);
2022-04-07 16:18:46 -05:00
pub struct Model {
vb: VertexBuffer<Vertex>,
ib: IndexBuffer<u32>,
2022-04-07 16:18:46 -05:00
}
impl Model {
pub fn new(display: &glium::Display, file: &str) -> Self {
let (document, buffers, _images) = gltf::import(file).expect("Could not load gltf file");
let mesh = document.meshes().next().unwrap();
let primitive = mesh.primitives().next().unwrap();
2022-04-07 16:18:46 -05:00
let reader = primitive.reader(|buffer| Some(&buffers[buffer.index()]));
2022-04-08 16:49:31 -05:00
let mut vertices: Vec<Vertex> = Vec::new();
let positions = reader.read_positions().unwrap();
let normals = reader.read_normals().unwrap();
for (position, normal) in positions.zip(normals) {
vertices.push(Vertex { position, normal });
}
2022-04-07 16:18:46 -05:00
let vb = VertexBuffer::new(display, &vertices).unwrap();
let indices: Vec<u32> = reader.read_indices().unwrap().into_u32().collect();
2022-04-07 16:18:46 -05:00
let ib = IndexBuffer::new(display, glium::index::PrimitiveType::TrianglesList, &indices).unwrap();
2022-04-07 16:18:46 -05:00
Model { vb, ib }
}
pub fn draw(&self,
2022-04-08 16:49:31 -05:00
target: &mut impl glium::Surface,
program: &glium::Program,
uniforms: &impl glium::uniforms::Uniforms,
params: &glium::DrawParameters
2022-04-07 16:18:46 -05:00
) {
2022-04-08 16:49:31 -05:00
target.draw(&self.vb, &self.ib, program, uniforms, params).unwrap()
2022-04-07 16:18:46 -05:00
}
}