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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
//! Tiny OBJ loader, inspired by Syoyo's excellent [tinyobjloader](https://github.com/syoyo/tinyobjloader). //! Aims to be a simple and lightweight option for loading OBJ files, just returns two vecs //! containing loaded models and materials. All models are made of triangles, any quad or polygon faces //! in an OBJ file will be converted to triangles. Note that only polygons that are trivially //! convertible to triangle fans are supported, arbitrary polygons may not behave as expected. //! The best solution would be to re-export your mesh using only triangles in your modeling software. //! //! It is assumed that all meshes will at least have positions, but normals and texture coordinates //! are optional. If no normals or texture coordinates were found then the corresponding vecs for //! the mesh will be empty. Values are stored packed as floats in vecs, eg. the positions member of //! a loaded mesh will contain `[x, y, z, x, y, z, ...]` which you can then use however you like. //! Indices are also loaded and may re-use vertices already existing in the mesh, this data is //! stored in the `indices` member. //! //! Standard MTL attributes are supported as well and any unrecognized parameters will be stored in a //! `HashMap` containing the key-value pairs of the unrecognized parameter and its value. //! //! # Example //! In this simple example we load the classic Cornell Box model that only defines positions and //! print out its attributes. This example is a slightly trimmed down version of `print_model_info` //! and `print_material_info` combined together, see them for a version that also prints out //! normals and texture coordinates if the model has them. //! //! ``` //! use std::path::Path; //! use tobj; //! //! let cornell_box = tobj::load_obj(&Path::new("cornell_box.obj")); //! assert!(cornell_box.is_ok()); //! let (models, materials) = cornell_box.unwrap(); //! //! println!("# of models: {}", models.len()); //! println!("# of materials: {}", materials.len()); //! for (i, m) in models.iter().enumerate() { //! let mesh = &m.mesh; //! println!("model[{}].name = \'{}\'", i, m.name); //! println!("model[{}].mesh.material_id = {:?}", i, mesh.material_id); //! //! println!("Size of model[{}].indices: {}", i, mesh.indices.len()); //! for f in 0..mesh.indices.len() / 3 { //! println!(" idx[{}] = {}, {}, {}.", f, mesh.indices[3 * f], //! mesh.indices[3 * f + 1], mesh.indices[3 * f + 2]); //! } //! //! // Normals and texture coordinates are also loaded, but not printed in this example //! println!("model[{}].vertices: {}", i, mesh.positions.len() / 3); //! assert!(mesh.positions.len() % 3 == 0); //! for v in 0..mesh.positions.len() / 3 { //! println!(" v[{}] = ({}, {}, {})", v, mesh.positions[3 * v], //! mesh.positions[3 * v + 1], mesh.positions[3 * v + 2]); //! } //! } //! for (i, m) in materials.iter().enumerate() { //! println!("material[{}].name = \'{}\'", i, m.name); //! println!(" material.Ka = ({}, {}, {})", m.ambient[0], m.ambient[1], m.ambient[2]); //! println!(" material.Kd = ({}, {}, {})", m.diffuse[0], m.diffuse[1], m.diffuse[2]); //! println!(" material.Ks = ({}, {}, {})", m.specular[0], m.specular[1], m.specular[2]); //! println!(" material.Ns = {}", m.shininess); //! println!(" material.d = {}", m.dissolve); //! println!(" material.map_Ka = {}", m.ambient_texture); //! println!(" material.map_Kd = {}", m.diffuse_texture); //! println!(" material.map_Ks = {}", m.specular_texture); //! println!(" material.map_Ns = {}", m.normal_texture); //! println!(" material.map_d = {}", m.dissolve_texture); //! for (k, v) in &m.unknown_param { //! println!(" material.{} = {}", k, v); //! } //! } //! ``` //! //! # Rendering Examples //! For an example of integration with [glium](https://github.com/tomaka/glium) to make a simple OBJ viewer, //! check out [tobj viewer](https://github.com/Twinklebear/tobj_viewer). Some sample images can be found in //! tobj viewer's readme or in [this gallery](http://imgur.com/a/xsg6v). //! //! The Rungholt model shown below is reasonably large (6.7M triangles, 12.3M vertices) and is loaded //! in ~7.47s using a peak of ~1.1GB of memory on a Windows 10 machine with an i7-4790k and 16GB of //! 1600Mhz DDR3 RAM with tobj 0.1.1 on rustc 1.6.0. //! The model can be found on [Morgan McGuire's](http://graphics.cs.williams.edu/data/meshes.xml) meshes page and //! was originally built by kescha. Future work will focus on improving performance and memory usage. //! //! <img src="http://i.imgur.com/wImyNG4.png" alt="Rungholt" //! style="display:block; max-width:100%; height:auto"> //! //! For an example of integration within a ray tracer, check out tray\_rust's //! [mesh module](https://github.com/Twinklebear/tray_rust/blob/master/src/geometry/mesh.rs). //! The Stanford Buddha and Dragon from the //! [Stanford 3D Scanning Repository](http://graphics.stanford.edu/data/3Dscanrep/) both load quite quickly. //! The Rust logo model was made by //! [Nylithius on BlenderArtists](http://blenderartists.org/forum/showthread.php?362836-Rust-language-3D-logo). //! The materials used are from the [MERL BRDF Database](http://www.merl.com/brdf/). //! //! <img src="http://i.imgur.com/E1ylrZW.png" alt="Rust logo with friends" //! style="display:block; max-width:100%; height:auto"> //! #![allow(dead_code)] #![cfg_attr(all(test, feature = "unstable"), feature(test))] #![cfg_attr(feature = "unstable", feature(plugin))] #![cfg_attr(feature = "unstable", plugin(clippy))] #[cfg(all(test, feature = "unstable"))] extern crate test; use std::io::prelude::*; use std::io::BufReader; use std::path::Path; use std::fs::File; use std::collections::HashMap; use std::str::{FromStr, SplitWhitespace}; use std::fmt; use std::error::Error; /// A mesh made up of triangles loaded from some OBJ file /// /// It is assumed that all meshes will at least have positions, but normals and texture coordinates /// are optional. If no normals or texture coordinates where found then the corresponding vecs for /// the mesh will be empty. Values are stored packed as floats in vecs, eg. the positions member of /// a loaded mesh will contain `[x, y, z, x, y, z, ...]` which you can then use however you like. /// Indices are also loaded and may re-use vertices already existing in the mesh, this data is /// stored in the `indices` member. /// /// # Example: /// Load the Cornell box and get the attributes of the first vertex. It's assumed all meshes will /// have positions (required), but normals and texture coordinates are optional, in which case the /// corresponding Vec will be empty. /// /// ``` /// use std::path::Path; /// /// let cornell_box = tobj::load_obj(&Path::new("cornell_box.obj")); /// assert!(cornell_box.is_ok()); /// let (models, materials) = cornell_box.unwrap(); /// /// let mesh = &models[0].mesh; /// let i = mesh.indices[0] as usize; /// // pos = [x, y, z] /// let pos = [mesh.positions[i * 3], mesh.positions[i * 3 + 1], /// mesh.positions[i * 3 + 2]]; /// /// if !mesh.normals.is_empty() { /// // normal = [x, y, z] /// let normal = [mesh.normals[i * 3], mesh.normals[i * 3 + 1], /// mesh.normals[i * 3 + 2]]; /// } /// /// if !mesh.texcoords.is_empty() { /// // texcoord = [u, v]; /// let texcoord = [mesh.texcoords[i * 2], mesh.texcoords[i * 2 + 1]]; /// } /// ``` #[derive(Debug, Clone)] pub struct Mesh { /// Flattened 3 component floating point vectors, storing positions of vertices in the mesh pub positions: Vec<f32>, /// Flattened 3 component floating point vectors, storing normals of vertices in the mesh. Not /// all meshes have normals, if no normals are specified this Vec will be empty pub normals: Vec<f32>, /// Flattened 2 component floating point vectors, storing texture coordinates of vertices in /// the mesh. Not all meshes have normals, if no texture coordinates are specified this Vec /// will be empty pub texcoords: Vec<f32>, /// Indices for vertices of each triangle. Each face in the mesh is a triangle and the indices /// specify the position, normal and texture coordinate for each vertex of the face. pub indices: Vec<u32>, /// Optional material id associated with this mesh. The material id indexes into the Vec of /// Materials loaded from the associated MTL file pub material_id: Option<usize>, } impl Mesh { /// Create a new mesh specifying the geometry for the mesh pub fn new(positions: Vec<f32>, normals: Vec<f32>, texcoords: Vec<f32>, indices: Vec<u32>, material_id: Option<usize>) -> Mesh { Mesh { positions, normals, texcoords, indices, material_id, } } /// Create a new empty mesh pub fn empty() -> Mesh { Mesh { positions: Vec::new(), normals: Vec::new(), texcoords: Vec::new(), indices: Vec::new(), material_id: None, } } } /// A named model within the file, associates some mesh with a name that was specified with an `o` /// or `g` keyword in the OBJ file #[derive(Clone, Debug)] pub struct Model { /// Mesh used by the model containing its geometry pub mesh: Mesh, /// Name assigned to this mesh pub name: String, } impl Model { /// Create a new model, associating a name with a mesh pub fn new(mesh: Mesh, name: String) -> Model { Model { mesh, name } } } /// A material that may be referenced by one or more meshes. Standard MTL attributes are supported. /// Any unrecognized parameters will be stored as key-value pairs in the `unknown_param` `HashMap`, /// which maps the unknown parameter to the value set for it. #[derive(Clone, Debug)] pub struct Material { /// Material name as specified in the MTL file pub name: String, /// Ambient color of the material pub ambient: [f32; 3], /// Diffuse color of the material pub diffuse: [f32; 3], /// Specular color of the material pub specular: [f32; 3], /// Material shininess attribute pub shininess: f32, /// Dissolve attribute is the alpha term for the material. Referred to as dissolve since that's /// what the MTL file format docs refer to it as pub dissolve: f32, /// Optical density also known as index of refraction. Called optical_density in the MTL specc. /// Takes on a value between 0.001 and 10.0. 1.0 means light does not bend as it passed through /// the object. pub optical_density: f32, /// Name of the ambient texture file for the material. No path is pre-pended to the texture /// file names specified in the MTL file pub ambient_texture: String, /// Name of the diffuse texture file for the material. No path is pre-pended to the texture /// file names specified in the MTL file pub diffuse_texture: String, /// Name of the specular texture file for the material. No path is pre-pended to the texture /// file names specified in the MTL file pub specular_texture: String, /// Name of the normal map texture file for the material. No path is pre-pended to the texture /// file names specified in the MTL file pub normal_texture: String, /// Name of the alpha map texture file for the material. No path is pre-pended to the texture /// file names specified in the MTL file. Referred to as dissolve to match the MTL file format /// specification pub dissolve_texture: String, /// The illumnination model to use for this material. The different illumnination models are /// specified in http://paulbourke.net/dataformats/mtl/ pub illumination_model: Option<u8>, /// Key value pairs of any unrecognized parameters encountered while parsing the material pub unknown_param: HashMap<String, String>, } impl Material { pub fn empty() -> Material { Material { name: String::new(), ambient: [0.0; 3], diffuse: [0.0; 3], specular: [0.0; 3], shininess: 0.0, dissolve: 1.0, optical_density: 1.0, ambient_texture: String::new(), diffuse_texture: String::new(), specular_texture: String::new(), normal_texture: String::new(), dissolve_texture: String::new(), illumination_model: None, unknown_param: HashMap::new(), } } } /// Possible errors that may occur while loading OBJ and MTL files #[derive(Debug)] pub enum LoadError { OpenFileFailed, ReadError, UnrecognizedCharacter, PositionParseError, NormalParseError, TexcoordParseError, FaceParseError, MaterialParseError, InvalidObjectName, GenericFailure, } impl fmt::Display for LoadError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { f.write_str(self.description()) } } impl Error for LoadError { fn description(&self) -> &str { match *self { LoadError::OpenFileFailed => "open file failed", LoadError::ReadError => "read error", LoadError::UnrecognizedCharacter => "unrecognized character", LoadError::PositionParseError => "position parse error", LoadError::NormalParseError => "normal parse error", LoadError::TexcoordParseError => "texcoord parse error", LoadError::FaceParseError => "face parse error", LoadError::MaterialParseError => "material parse error", LoadError::InvalidObjectName => "invalid object name", LoadError::GenericFailure => "generic failure", } } } /// `LoadResult` is a result containing all the models loaded from the file and any materials from /// referenced material libraries, or an error that occured while loading pub type LoadResult = Result<(Vec<Model>, Vec<Material>), LoadError>; /// `MTLLoadResult` is a result containing all the materials loaded from the file and a map of MTL /// name to index or the error that occured while loading pub type MTLLoadResult = Result<(Vec<Material>, HashMap<String, usize>), LoadError>; /// Struct storing indices corresponding to the vertex /// Some vertices may not have texcoords or normals, 0 is used to indicate this /// as OBJ indices begin at 1 #[derive(Hash, Eq, PartialEq, PartialOrd, Ord, Debug, Copy, Clone)] struct VertexIndices { pub v: isize, pub vt: isize, pub vn: isize, } impl VertexIndices { /// Parse the vertex indices from the face string /// Valid face strings are those that are valid for a Wavefront OBJ file /// Also handles relative face indices (negative values) which is why passing the number of /// positions, texcoords and normals is required /// Returns None if the face string is invalid fn parse(face_str: &str, pos_sz: usize, tex_sz: usize, norm_sz: usize) -> Option<VertexIndices> { let mut indices = [-1; 3]; for i in face_str.split('/').enumerate() { // Catch case of v//vn where we'll find an empty string in one of our splits // since there are no texcoords for the mesh if !i.1.is_empty() { match isize::from_str(i.1) { Ok(x) => { // Handle relative indices indices[i.0] = if x < 0 { match i.0 { 0 => x + pos_sz as isize, 1 => x + tex_sz as isize, 2 => x + norm_sz as isize, _ => panic!("Invalid number of elements for a face (> 3)!"), } } else { x - 1 }; } Err(_) => return None, } } } Some(VertexIndices { v: indices[0], vt: indices[1], vn: indices[2], }) } } /// Enum representing either a quad or triangle face, storing indices for the face vertices #[derive(Debug)] enum Face { Line(VertexIndices, VertexIndices), Triangle(VertexIndices, VertexIndices, VertexIndices), Quad(VertexIndices, VertexIndices, VertexIndices, VertexIndices), Polygon(Vec<VertexIndices>), } /// Parse the floatn information from the words, words is an iterator over the float strings /// Returns false if parsing failed fn parse_floatn(val_str: SplitWhitespace, vals: &mut Vec<f32>, n: usize) -> bool { let sz = vals.len(); for p in val_str { if sz + n == vals.len() { return true; } match FromStr::from_str(p) { Ok(x) => vals.push(x), Err(_) => return false, } } // Require that we found the desired number of floats sz + n == vals.len() } /// Parse the float3 into the array passed, returns false if parsing failed fn parse_float3(val_str: SplitWhitespace, vals: &mut [f32; 3]) -> bool { for (i, p) in val_str.enumerate().take(3) { match FromStr::from_str(p) { Ok(x) => vals[i] = x, Err(_) => return false, } } true } /// Parse vertex indices for a face and append it to the list of faces passed /// Also handles relative face indices (negative values) which is why passing the number of /// positions, texcoords and normals is required /// returns false if an error occured parsing the face fn parse_face(face_str: SplitWhitespace, faces: &mut Vec<Face>, pos_sz: usize, tex_sz: usize, norm_sz: usize) -> bool { let mut indices = Vec::new(); for f in face_str { match VertexIndices::parse(f, pos_sz, tex_sz, norm_sz) { Some(v) => indices.push(v), None => return false, } } // Check if we read a triangle or a quad face and push it on match indices.len() { 2 => faces.push(Face::Line(indices[0], indices[1])), 3 => faces.push(Face::Triangle(indices[0], indices[1], indices[2])), 4 => faces.push(Face::Quad(indices[0], indices[1], indices[2], indices[3])), _ => faces.push(Face::Polygon(indices)), } true } /// Add a vertex to a mesh by either re-using an existing index (eg. it's in the `index_map`) /// or appending the position, texcoord and normal as appropriate and creating a new vertex fn add_vertex(mesh: &mut Mesh, index_map: &mut HashMap<VertexIndices, u32>, vert: &VertexIndices, pos: &[f32], texcoord: &[f32], normal: &[f32]) { match index_map.get(vert) { Some(&i) => mesh.indices.push(i), None => { let v = vert.v as usize; // Add the vertex to the mesh mesh.positions.push(pos[v * 3]); mesh.positions.push(pos[v * 3 + 1]); mesh.positions.push(pos[v * 3 + 2]); if !texcoord.is_empty() && vert.vt > -1 { let vt = vert.vt as usize; mesh.texcoords.push(texcoord[vt * 2]); mesh.texcoords.push(texcoord[vt * 2 + 1]); } if !normal.is_empty() && vert.vn > -1 { let vn = vert.vn as usize; mesh.normals.push(normal[vn * 3]); mesh.normals.push(normal[vn * 3 + 1]); mesh.normals.push(normal[vn * 3 + 2]); } let next = index_map.len() as u32; mesh.indices.push(next); index_map.insert(*vert, next); } } } /// Export a list of faces to a mesh and return it, converting quads to tris fn export_faces(pos: &[f32], texcoord: &[f32], normal: &[f32], faces: &[Face], mat_id: Option<usize>) -> Mesh { let mut index_map = HashMap::new(); let mut mesh = Mesh::empty(); mesh.material_id = mat_id; for f in faces { // Optimized paths for Triangles and Quads, Polygon handles the general case of an unknown // length triangle fan match *f { Face::Line(ref a, ref b) => { add_vertex(&mut mesh, &mut index_map, a, pos, texcoord, normal); add_vertex(&mut mesh, &mut index_map, b, pos, texcoord, normal); } Face::Triangle(ref a, ref b, ref c) => { add_vertex(&mut mesh, &mut index_map, a, pos, texcoord, normal); add_vertex(&mut mesh, &mut index_map, b, pos, texcoord, normal); add_vertex(&mut mesh, &mut index_map, c, pos, texcoord, normal); } Face::Quad(ref a, ref b, ref c, ref d) => { add_vertex(&mut mesh, &mut index_map, a, pos, texcoord, normal); add_vertex(&mut mesh, &mut index_map, b, pos, texcoord, normal); add_vertex(&mut mesh, &mut index_map, c, pos, texcoord, normal); add_vertex(&mut mesh, &mut index_map, a, pos, texcoord, normal); add_vertex(&mut mesh, &mut index_map, c, pos, texcoord, normal); add_vertex(&mut mesh, &mut index_map, d, pos, texcoord, normal); } Face::Polygon(ref indices) => { let a = &indices[0]; let mut b = &indices[1]; for c in indices.iter().skip(2) { add_vertex(&mut mesh, &mut index_map, a, pos, texcoord, normal); add_vertex(&mut mesh, &mut index_map, b, pos, texcoord, normal); add_vertex(&mut mesh, &mut index_map, c, pos, texcoord, normal); b = c; } } } } mesh } /// Load the various objects specified in the OBJ file and any associated MTL file /// Returns a pair of Vecs containing the loaded models and materials from the file. pub fn load_obj(file_name: &Path) -> LoadResult { let file = match File::open(file_name) { Ok(f) => f, Err(_e) => { #[cfg(feature = "log")] log::error!("load_obj - failed to open {:?} due to {}", file_name, _e); return Err(LoadError::OpenFileFailed); } }; let mut reader = BufReader::new(file); load_obj_buf(&mut reader, |mat_path| { let full_path = if let Some(parent) = file_name.parent() { parent.join(mat_path) } else { mat_path.to_owned() }; self::load_mtl(&full_path) }) } /// Load the materials defined in a MTL file /// Returns a pair with a `Vec` holding all loaded materials and a `HashMap` containing a mapping of /// material names to indices in the Vec. pub fn load_mtl(file_name: &Path) -> MTLLoadResult { let file = match File::open(file_name) { Ok(f) => f, Err(_e) => { #[cfg(feature = "log")] log::error!("load_mtl - failed to open {:?} due to {}", file_name, _e); return Err(LoadError::OpenFileFailed); } }; let mut reader = BufReader::new(file); load_mtl_buf(&mut reader) } /// Load the various meshes in an OBJ buffer of some kind, e.g. a /// network stream, text file already in memory or so on. /// /// You must pass a "material loader" function, which will return a material /// given a name. A trivial material loader may just look at the file /// name and then call `load_mtl_buf` with the in-memory MTL file source. /// Alternatively it could pass an MTL file in memory to `load_mtl_buf` to /// parse materials from some buffer. /// /// # Example /// The test for `load_obj_buf` includes the OBJ and MTL files as strings /// and uses a `Cursor` to provide a `BufRead` interface on the buffer. /// /// ``` /// use std::env; /// use std::fs::File; /// use std::io::BufReader; /// /// let dir = env::current_dir().unwrap(); /// let mut cornell_box_obj = dir.clone(); /// cornell_box_obj.push("cornell_box.obj"); /// let mut cornell_box_file = BufReader::new(File::open(cornell_box_obj.as_path()).unwrap()); /// /// let mut cornell_box_mtl1 = dir.clone(); /// cornell_box_mtl1.push("cornell_box.mtl"); /// /// let mut cornell_box_mtl2 = dir.clone(); /// cornell_box_mtl2.push("cornell_box2.mtl"); /// /// let m = tobj::load_obj_buf(&mut cornell_box_file, |p| { /// match p.file_name().unwrap().to_str().unwrap() { /// "cornell_box.mtl" => { /// let f = File::open(cornell_box_mtl1.as_path()).unwrap(); /// tobj::load_mtl_buf(&mut BufReader::new(f)) /// }, /// "cornell_box2.mtl" => { /// let f = File::open(cornell_box_mtl2.as_path()).unwrap(); /// tobj::load_mtl_buf(&mut BufReader::new(f)) /// }, /// _ => unreachable!(), /// } /// }); /// ``` pub fn load_obj_buf<B, ML>(reader: &mut B, material_loader: ML) -> LoadResult where B: BufRead, ML: Fn(&Path) -> MTLLoadResult { let mut models = Vec::new(); let mut materials = Vec::new(); let mut mat_map = HashMap::new(); let mut tmp_pos = Vec::new(); let mut tmp_texcoord = Vec::new(); let mut tmp_normal = Vec::new(); let mut tmp_faces: Vec<Face> = Vec::new(); // name of the current object being parsed let mut name = "unnamed_object".to_owned(); // material used by the current object being parsed let mut mat_id = None; for line in reader.lines() { let (line, mut words) = match line { Ok(ref line) => (&line[..], line[..].split_whitespace()), Err(_e) => { #[cfg(feature = "log")] log::error!("load_obj - failed to read line due to {}", _e); return Err(LoadError::ReadError); } }; match words.next() { Some("#") | None => continue, Some("v") => { if !parse_floatn(words, &mut tmp_pos, 3) { return Err(LoadError::PositionParseError); } } Some("vt") => { if !parse_floatn(words, &mut tmp_texcoord, 2) { return Err(LoadError::TexcoordParseError); } } Some("vn") => { if !parse_floatn(words, &mut tmp_normal, 3) { return Err(LoadError::NormalParseError); } } Some("f") | Some("l") => { if !parse_face(words, &mut tmp_faces, tmp_pos.len() / 3, tmp_texcoord.len() / 2, tmp_normal.len() / 3) { return Err(LoadError::FaceParseError); } } // Just treating object and group tags identically. Should there be different behavior // for them? Some("o") | Some("g") => { // If we were already parsing an object then a new object name // signals the end of the current one, so push it onto our list of objects if !tmp_faces.is_empty() { models.push(Model::new(export_faces(&tmp_pos, &tmp_texcoord, &tmp_normal, &tmp_faces, mat_id), name)); tmp_faces.clear(); } name = line[1..].trim().to_owned(); if name.is_empty() { name = "unnamed_object".to_owned(); } } Some("mtllib") => { if let Some(mtllib) = words.next() { let mat_file = Path::new(mtllib).to_path_buf(); match material_loader(mat_file.as_path()) { Ok((mut mats, map)) => { // Merge the loaded material lib with any currently loaded ones, offsetting // the indices of the appended materials by our current length let mat_offset = materials.len(); materials.append(&mut mats); for m in map { mat_map.insert(m.0, m.1 + mat_offset); } } Err(e) => return Err(e), } } else { return Err(LoadError::MaterialParseError); } } Some("usemtl") => { if let Some(mat_name) = words.next() { let new_mat = mat_map.get(mat_name).cloned(); // As materials are returned per-model, a new material within an object // has to emit a new model with the same name but different material if mat_id != new_mat && !tmp_faces.is_empty() { models.push(Model::new(export_faces(&tmp_pos, &tmp_texcoord, &tmp_normal, &tmp_faces, mat_id), name.clone())); tmp_faces.clear(); } if new_mat.is_none() { #[cfg(feature = "log")] log::warn!("Object {} refers to unfound material: {}", name, mat_name); } mat_id = new_mat; } else { return Err(LoadError::MaterialParseError); } } // Just ignore unrecognized characters Some(_) => {} } } // For the last object in the file we won't encounter another object name to tell us when it's // done, so if we're parsing an object push the last one on the list as well models.push(Model::new(export_faces(&tmp_pos, &tmp_texcoord, &tmp_normal, &tmp_faces, mat_id), name)); Ok((models, materials)) } /// Load the various materials in a MTL buffer pub fn load_mtl_buf<B: BufRead>(reader: &mut B) -> MTLLoadResult { let mut materials = Vec::new(); let mut mat_map = HashMap::new(); // The current material being parsed let mut cur_mat = Material::empty(); for line in reader.lines() { let (line, mut words) = match line { Ok(ref line) => (line.trim(), line[..].split_whitespace()), Err(_e) => { #[cfg(feature = "log")] log::error!("load_obj - failed to read line due to {}", _e); return Err(LoadError::ReadError); } }; match words.next() { Some("#") | None => continue, Some("newmtl") => { // If we were passing a material save it out to our vector if !cur_mat.name.is_empty() { mat_map.insert(cur_mat.name.clone(), materials.len()); materials.push(cur_mat); } cur_mat = Material::empty(); cur_mat.name = line[6..].trim().to_owned(); if cur_mat.name.is_empty() { return Err(LoadError::InvalidObjectName); } } Some("Ka") => { if !parse_float3(words, &mut cur_mat.ambient) { return Err(LoadError::MaterialParseError); } } Some("Kd") => { if !parse_float3(words, &mut cur_mat.diffuse) { return Err(LoadError::MaterialParseError); } } Some("Ks") => { if !parse_float3(words, &mut cur_mat.specular) { return Err(LoadError::MaterialParseError); } } Some("Ns") => { if let Some(p) = words.next() { match FromStr::from_str(p) { Ok(x) => cur_mat.shininess = x, Err(_) => return Err(LoadError::MaterialParseError), } } else { return Err(LoadError::MaterialParseError); } } Some("Ni") => { if let Some(p) = words.next() { match FromStr::from_str(p) { Ok(x) => cur_mat.optical_density = x, Err(_) => return Err(LoadError::MaterialParseError), } } else { return Err(LoadError::MaterialParseError); } } Some("d") => { if let Some(p) = words.next() { match FromStr::from_str(p) { Ok(x) => cur_mat.dissolve = x, Err(_) => return Err(LoadError::MaterialParseError), } } else { return Err(LoadError::MaterialParseError); } } Some("map_Ka") => match line.get(6..).map(str::trim) { Some("") | None => return Err(LoadError::MaterialParseError), Some(tex) => cur_mat.ambient_texture = tex.to_owned(), }, Some("map_Kd") => match line.get(6..).map(str::trim) { Some("") | None => return Err(LoadError::MaterialParseError), Some(tex) => cur_mat.diffuse_texture = tex.to_owned(), }, Some("map_Ks") => match line.get(6..).map(str::trim) { Some("") | None => return Err(LoadError::MaterialParseError), Some(tex) => cur_mat.specular_texture = tex.to_owned(), }, Some("map_Ns") => match line.get(6..).map(str::trim) { Some("") | None => return Err(LoadError::MaterialParseError), Some(tex) => cur_mat.normal_texture = tex.to_owned(), }, Some("map_d") => match line.get(5..).map(str::trim) { Some("") | None => return Err(LoadError::MaterialParseError), Some(tex) => cur_mat.dissolve_texture = tex.to_owned(), }, Some("illum") => { if let Some(p) = words.next() { match FromStr::from_str(p) { Ok(x) => cur_mat.illumination_model = Some(x), Err(_) => return Err(LoadError::MaterialParseError), } } else { return Err(LoadError::MaterialParseError); } } Some(unknown) => { if !unknown.is_empty() { let param = line[unknown.len()..].trim().to_owned(); cur_mat.unknown_param.insert(unknown.to_owned(), param); } } } } // Finalize the last material we were parsing if !cur_mat.name.is_empty() { mat_map.insert(cur_mat.name.clone(), materials.len()); materials.push(cur_mat); } Ok((materials, mat_map)) } /// Print out all loaded properties of some models and associated materials pub fn print_model_info(models: &[Model], materials: &[Material]) { println!("# of models: {}", models.len()); println!("# of materials: {}", materials.len()); for (i, m) in models.iter().enumerate() { let mesh = &m.mesh; println!("model[{}].name = \'{}\'", i, m.name); println!("model[{}].mesh.material_id = {:?}", i, mesh.material_id); println!("Size of model[{}].indices: {}", i, mesh.indices.len()); for f in 0..mesh.indices.len() / 3 { println!(" idx[{}] = {}, {}, {}.", f, mesh.indices[3 * f], mesh.indices[3 * f + 1], mesh.indices[3 * f + 2]); } println!("model[{}].vertices: {}", i, mesh.positions.len() / 3); println!("model[{}].normals: {}", i, mesh.normals.len() / 3); println!("model[{}].texcoords: {}", i, mesh.texcoords.len() / 2); assert_eq!(mesh.positions.len() % 3, 0); assert_eq!(mesh.normals.len() % 3, 0); assert_eq!(mesh.texcoords.len() % 2, 0); for v in 0..mesh.positions.len() / 3 { println!(" v[{}] = ({}, {}, {})", v, mesh.positions[3 * v], mesh.positions[3 * v + 1], mesh.positions[3 * v + 2]); if !mesh.normals.is_empty() { println!(" vn[{}] = ({}, {}, {})", v, mesh.normals[3 * v], mesh.normals[3 * v + 1], mesh.normals[3 * v + 2]); } if !mesh.texcoords.is_empty() { println!(" vt[{}] = ({}, {})", v, mesh.texcoords[2 * v], mesh.texcoords[2 * v + 1]); } } } print_material_info(materials); } /// Print out all loaded properties of some materials pub fn print_material_info(materials: &[Material]) { for (i, m) in materials.iter().enumerate() { println!("material[{}].name = \'{}\'", i, m.name); println!(" material.Ka = ({}, {}, {})", m.ambient[0], m.ambient[1], m.ambient[2]); println!(" material.Kd = ({}, {}, {})", m.diffuse[0], m.diffuse[1], m.diffuse[2]); println!(" material.Ks = ({}, {}, {})", m.specular[0], m.specular[1], m.specular[2]); println!(" material.Ns = {}", m.shininess); println!(" material.d = {}", m.dissolve); println!(" material.map_Ka = {}", m.ambient_texture); println!(" material.map_Kd = {}", m.diffuse_texture); println!(" material.map_Ks = {}", m.specular_texture); println!(" material.map_Ns = {}", m.normal_texture); println!(" material.map_d = {}", m.dissolve_texture); for (k, v) in &m.unknown_param { println!(" material.{} = {}", k, v); } } } #[cfg(all(test, feature = "unstable"))] mod benches { use test::Bencher; use std::path::Path; use super::load_obj; #[bench] fn bench_cornell(b: &mut Bencher) { let path = Path::new("cornell_box.obj"); b.iter(|| { let m = load_obj(path); assert!(m.is_ok()); m.is_ok() }); } }