Read wavefront .obj file, without preprocessing. Why bothering having this read_obj() while we already have other libraries like `trimesh`? This function read the raw format from .obj file and keeps the order of vertices and faces, while trimesh which involves modification li
(
file : Union[str, Path, TextIOWrapper],
encoding: Union[str, None] = None,
ignore_unknown: bool = False
)
| 10 | ] |
| 11 | |
| 12 | def read_obj( |
| 13 | file : Union[str, Path, TextIOWrapper], |
| 14 | encoding: Union[str, None] = None, |
| 15 | ignore_unknown: bool = False |
| 16 | ): |
| 17 | """ |
| 18 | Read wavefront .obj file, without preprocessing. |
| 19 | |
| 20 | Why bothering having this read_obj() while we already have other libraries like `trimesh`? |
| 21 | This function read the raw format from .obj file and keeps the order of vertices and faces, |
| 22 | while trimesh which involves modification like merge/split vertices, which could break the orders of vertices and faces, |
| 23 | Those libraries are commonly aiming at geometry processing and rendering supporting various formats. |
| 24 | If you want mesh geometry processing, you may turn to `trimesh` for more features. |
| 25 | |
| 26 | ### Parameters |
| 27 | `file` (str, Path, TextIOWrapper): filepath or file object |
| 28 | encoding (str, optional): |
| 29 | |
| 30 | ### Returns |
| 31 | obj (dict): A dict containing .obj components |
| 32 | { |
| 33 | 'mtllib': [], |
| 34 | 'v': [[0,1, 0.2, 1.0], [1.2, 0.0, 0.0], ...], |
| 35 | 'vt': [[0.5, 0.5], ...], |
| 36 | 'vn': [[0., 0.7, 0.7], [0., -0.7, 0.7], ...], |
| 37 | 'f': [[0, 1, 2], [2, 3, 4],...], |
| 38 | 'usemtl': [{'name': 'mtl1', 'f': 7}] |
| 39 | } |
| 40 | """ |
| 41 | if hasattr(file,'read'): |
| 42 | lines = file.read().splitlines() |
| 43 | else: |
| 44 | with open(file, 'r', encoding=encoding) as fp: |
| 45 | lines = fp.read().splitlines() |
| 46 | mtllib = [] |
| 47 | v, vt, vn, vp = [], [], [], [] # Vertex coordinates, Vertex texture coordinate, Vertex normal, Vertex parameter |
| 48 | f, ft, fn = [], [], [] # Face indices, Face texture indices, Face normal indices |
| 49 | o = [] |
| 50 | s = [] |
| 51 | usemtl = [] |
| 52 | |
| 53 | def pad(l: list, n: Any): |
| 54 | return l + [n] * (3 - len(l)) |
| 55 | |
| 56 | for i, line in enumerate(lines): |
| 57 | sq = line.strip().split() |
| 58 | if len(sq) == 0: |
| 59 | continue |
| 60 | if sq[0] == 'v': |
| 61 | assert 4 <= len(sq) <= 5, f'Invalid format of line {i}: {line}' |
| 62 | v.append([float(e) for e in sq[1:]][:3]) |
| 63 | elif sq[0] == 'vt': |
| 64 | assert 3 <= len(sq) <= 4, f'Invalid format of line {i}: {line}' |
| 65 | vt.append([float(e) for e in sq[1:]][:2]) |
| 66 | elif sq[0] == 'vn': |
| 67 | assert len(sq) == 4, f'Invalid format of line {i}: {line}' |
| 68 | vn.append([float(e) for e in sq[1:]]) |
| 69 | elif sq[0] == 'vp': |