summary refs log tree commit diff
path: root/src/files/obj.rs
blob: 3ccc2ec5209ac57be518ef215159eb29523522d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#![forbid(unsafe_code)]
use crate::error::*;
use crate::graphics::{ Permanent, Model };
use crate::linear_algebra::{ Vec2, Vec3 };
use crate::shader_data::Vertex;

use std::io::Cursor;

use tobj::{ load_obj_buf, LoadOptions };


pub fn load_obj(obj: &[u8], permanent: &Permanent) -> Result<Model> {
  let load_options = LoadOptions {
    single_index: true,
    triangulate: true,
    ..Default::default()
  };
  let (models, materials) = load_obj_buf(&mut Cursor::new(obj), &load_options,
                                         |_| Ok(Default::default()))?;

  let _ = materials?;

  let mut vertices = Vec::new();
  let mut indices = Vec::new();

  for model in models {
    for index in 0 .. model.mesh.positions.len() / 3 {
      vertices.push(Vertex::new(Vec3::new(model.mesh.positions[index*3],
                                          model.mesh.positions[index*3 + 1],
                                          model.mesh.positions[index*3 + 2]),
                                Vec3::new(1.0, 1.0, 1.0),
                                Vec2::new(model.mesh.texcoords[index*2],
                                          model.mesh.texcoords[index*2 + 1])))
    }

    for index in model.mesh.indices {
      indices.push(index);
    }
  }

  Model::new(vertices, indices, permanent)
}