Create a Msh object from a .msh file.
(file: pathlib.Path)
| 40 | |
| 41 | @staticmethod |
| 42 | def create(file: pathlib.Path) -> "Msh": |
| 43 | """Create a Msh object from a .msh file.""" |
| 44 | if not file.exists(): |
| 45 | raise FileNotFoundError(f"{file} does not exist.") |
| 46 | |
| 47 | with open(file, "rb") as f: |
| 48 | nvertex = np.fromfile(f, dtype=np.int32, count=1)[0] |
| 49 | nnormal = np.fromfile(f, dtype=np.int32, count=1)[0] |
| 50 | ntexcoord = np.fromfile(f, dtype=np.int32, count=1)[0] |
| 51 | nface = np.fromfile(f, dtype=np.int32, count=1)[0] |
| 52 | vertex_positions = np.fromfile(f, dtype=np.float32, count=3 * nvertex) |
| 53 | vertex_normals = np.fromfile(f, dtype=np.float32, count=3 * nnormal) |
| 54 | vertex_texcoords = np.fromfile(f, dtype=np.float32, count=2 * ntexcoord) |
| 55 | face_vertex_indices = np.fromfile(f, dtype=np.int32, count=3 * nface) |
| 56 | |
| 57 | if vertex_positions.size != 3 * nvertex: |
| 58 | raise ValueError(f"Invalid number of vertices: {vertex_positions.size} != 3*{nvertex}.") |
| 59 | if vertex_normals.size != 3 * nnormal: |
| 60 | raise ValueError(f"Invalid number of normals: {vertex_normals.size} != 3*{nnormal}.") |
| 61 | if vertex_texcoords.size != 2 * ntexcoord: |
| 62 | raise ValueError(f"Invalid number of texcoords: {vertex_texcoords.size} != 2*{{ntexcoord}}.") |
| 63 | if face_vertex_indices.size != 3 * nface: |
| 64 | raise ValueError(f"Invalid number of faces: {face_vertex_indices.size} != 3*{nface}.") |
| 65 | |
| 66 | vertex_positions = vertex_positions.reshape(-1, 3) |
| 67 | vertex_normals = vertex_normals.reshape(-1, 3) |
| 68 | face_vertex_indices = face_vertex_indices.reshape(-1, 3) |
| 69 | |
| 70 | # Reshape texture coordinates and swap x,y while maintaining the flip |
| 71 | vertex_texcoords = vertex_texcoords.reshape(-1, 2) |
| 72 | vertex_texcoords = vertex_texcoords[:, ::-1] # Swap U and V |
| 73 | vertex_texcoords[:, 1] = 1 - vertex_texcoords[:, 1] # Flip V coordinate |
| 74 | |
| 75 | return Msh( |
| 76 | vertex_positions=vertex_positions, |
| 77 | vertex_normals=vertex_normals, |
| 78 | vertex_texcoords=vertex_texcoords, |
| 79 | face_vertex_indices=face_vertex_indices, |
| 80 | ) |
| 81 | |
| 82 | |
| 83 | def msh_to_obj(msh_file: pathlib.Path) -> str: |