File size: 23,466 Bytes
b6045d5 | 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 | # This file was adapted from Pytorch3D to remove the dependency.
# Please see the original Pytorch3D licence below:
# BSD License
# For PyTorch3D software
# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name Meta nor the names of its contributors may be used to
# endorse or promote products derived from this software without specific
# prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# pyre-unsafe
"""This module implements utility functions for loading and saving meshes."""
import contextlib
import os
import warnings
from collections import namedtuple
from pathlib import Path
import pathlib
from typing import List, Optional, ContextManager, IO, Union
import torch
from iopath.common.file_io import PathManager
Device = Union[str, torch.device]
@contextlib.contextmanager
def nullcontext(x):
"""
This is just like contextlib.nullcontext but also works in Python 3.6.
"""
yield x
PathOrStr = Union[pathlib.Path, str]
def _open_file(f, path_manager: PathManager, mode: str = "r") -> ContextManager[IO]:
if isinstance(f, str):
f = path_manager.open(f, mode)
return contextlib.closing(f)
elif isinstance(f, pathlib.Path):
f = f.open(mode)
return contextlib.closing(f)
else:
return nullcontext(f)
def _make_tensor(
data, cols: int, dtype: torch.dtype, device: Device = "cpu"
) -> torch.Tensor:
"""
Return a 2D tensor with the specified cols and dtype filled with data,
even when data is empty.
"""
if not len(data):
return torch.zeros((0, cols), dtype=dtype, device=device)
return torch.tensor(data, dtype=dtype, device=device)
def _check_faces_indices(
faces_indices: torch.Tensor, max_index: int, pad_value: Optional[int] = None
) -> torch.Tensor:
if pad_value is None:
mask = torch.ones(faces_indices.shape[:-1]).bool() # Keep all faces
else:
mask = faces_indices.ne(pad_value).any(dim=-1)
if torch.any(faces_indices[mask] >= max_index) or torch.any(
faces_indices[mask] < 0
):
warnings.warn("Faces have invalid indices")
return faces_indices
# Faces & Aux type returned from load_obj function.
_Faces = namedtuple("Faces", "verts_idx normals_idx textures_idx materials_idx")
_Aux = namedtuple(
"Properties", "normals verts_uvs material_colors texture_images texture_atlas"
)
def _format_faces_indices(faces_indices, max_index: int, device, pad_value=None):
"""
Format indices and check for invalid values. Indices can refer to
values in one of the face properties: vertices, textures or normals.
See comments of the load_obj function for more details.
Args:
faces_indices: List of ints of indices.
max_index: Max index for the face property.
pad_value: if any of the face_indices are padded, specify
the value of the padding (e.g. -1). This is only used
for texture indices indices where there might
not be texture information for all the faces.
Returns:
faces_indices: List of ints of indices.
Raises:
ValueError if indices are not in a valid range.
"""
faces_indices = _make_tensor(
faces_indices, cols=3, dtype=torch.int64, device=device
)
if pad_value is not None:
mask = faces_indices.eq(pad_value).all(dim=-1)
# Change to 0 based indexing.
faces_indices[(faces_indices > 0)] -= 1
# Negative indexing counts from the end.
faces_indices[(faces_indices < 0)] += max_index
if pad_value is not None:
# pyre-fixme[61]: `mask` is undefined, or not always defined.
faces_indices[mask] = pad_value
return _check_faces_indices(faces_indices, max_index, pad_value)
def load_obj(
f,
load_textures: bool = True,
create_texture_atlas: bool = False,
texture_atlas_size: int = 4,
texture_wrap: Optional[str] = "repeat",
device: Device = "cpu",
path_manager: Optional[PathManager] = None,
):
"""
Load a mesh from a .obj file and optionally textures from a .mtl file.
Currently this handles verts, faces, vertex texture uv coordinates, normals,
texture images and material reflectivity values.
Note .obj files are 1-indexed. The tensors returned from this function
are 0-indexed. OBJ spec reference: http://www.martinreddy.net/gfx/3d/OBJ.spec
Example .obj file format:
::
# this is a comment
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 1.000000 -1.000000
vt 0.748573 0.750412
vt 0.749279 0.501284
vt 0.999110 0.501077
vt 0.999455 0.750380
vn 0.000000 0.000000 -1.000000
vn -1.000000 -0.000000 -0.000000
vn -0.000000 -0.000000 1.000000
f 5/2/1 1/2/1 4/3/1
f 5/1/1 4/3/1 2/4/1
The first character of the line denotes the type of input:
::
- v is a vertex
- vt is the texture coordinate of one vertex
- vn is the normal of one vertex
- f is a face
Faces are interpreted as follows:
::
5/2/1 describes the first vertex of the first triangle
- 5: index of vertex [1.000000 1.000000 -1.000000]
- 2: index of texture coordinate [0.749279 0.501284]
- 1: index of normal [0.000000 0.000000 -1.000000]
If there are faces with more than 3 vertices
they are subdivided into triangles. Polygonal faces are assumed to have
vertices ordered counter-clockwise so the (right-handed) normal points
out of the screen e.g. a proper rectangular face would be specified like this:
::
0_________1
| |
| |
3 ________2
The face would be split into two triangles: (0, 2, 1) and (0, 3, 2),
both of which are also oriented counter-clockwise and have normals
pointing out of the screen.
Args:
f: A file-like object (with methods read, readline, tell, and seek),
a pathlib path or a string containing a file name.
load_textures: Boolean indicating whether material files are loaded
create_texture_atlas: Bool, If True a per face texture map is created and
a tensor `texture_atlas` is also returned in `aux`.
texture_atlas_size: Int specifying the resolution of the texture map per face
when `create_texture_atlas=True`. A (texture_size, texture_size, 3)
map is created per face.
texture_wrap: string, one of ["repeat", "clamp"]. This applies when computing
the texture atlas.
If `texture_mode="repeat"`, for uv values outside the range [0, 1] the integer part
is ignored and a repeating pattern is formed.
If `texture_mode="clamp"` the values are clamped to the range [0, 1].
If None, then there is no transformation of the texture values.
device: Device (as str or torch.device) on which to return the new tensors.
path_manager: optionally a PathManager object to interpret paths.
Returns:
6-element tuple containing
- **verts**: FloatTensor of shape (V, 3).
- **faces**: NamedTuple with fields:
- verts_idx: LongTensor of vertex indices, shape (F, 3).
- normals_idx: (optional) LongTensor of normal indices, shape (F, 3).
- textures_idx: (optional) LongTensor of texture indices, shape (F, 3).
This can be used to index into verts_uvs.
- materials_idx: (optional) List of indices indicating which
material the texture is derived from for each face.
If there is no material for a face, the index is -1.
This can be used to retrieve the corresponding values
in material_colors/texture_images after they have been
converted to tensors or Materials/Textures data
structures - see textures.py and materials.py for
more info.
- **aux**: NamedTuple with fields:
- normals: FloatTensor of shape (N, 3)
- verts_uvs: FloatTensor of shape (T, 2), giving the uv coordinate per
vertex. If a vertex is shared between two faces, it can have
a different uv value for each instance. Therefore it is
possible that the number of verts_uvs is greater than
num verts i.e. T > V.
vertex.
- material_colors: if `load_textures=True` and the material has associated
properties this will be a dict of material names and properties of the form:
.. code-block:: python
{
material_name_1: {
"ambient_color": tensor of shape (1, 3),
"diffuse_color": tensor of shape (1, 3),
"specular_color": tensor of shape (1, 3),
"shininess": tensor of shape (1)
},
material_name_2: {},
...
}
If a material does not have any properties it will have an
empty dict. If `load_textures=False`, `material_colors` will None.
- texture_images: if `load_textures=True` and the material has a texture map,
this will be a dict of the form:
.. code-block:: python
{
material_name_1: (H, W, 3) image,
...
}
If `load_textures=False`, `texture_images` will None.
- texture_atlas: if `load_textures=True` and `create_texture_atlas=True`,
this will be a FloatTensor of the form: (F, texture_size, textures_size, 3)
If the material does not have a texture map, then all faces
will have a uniform white texture. Otherwise `texture_atlas` will be
None.
"""
data_dir = "./"
if isinstance(f, (str, bytes, Path)):
# pyre-fixme[6]: For 1st argument expected `PathLike[Variable[AnyStr <:
# [str, bytes]]]` but got `Union[Path, bytes, str]`.
data_dir = os.path.dirname(f)
if path_manager is None:
path_manager = PathManager()
with _open_file(f, path_manager, "r") as f:
return _load_obj(
f,
data_dir=data_dir,
load_textures=load_textures,
create_texture_atlas=create_texture_atlas,
texture_atlas_size=texture_atlas_size,
texture_wrap=texture_wrap,
path_manager=path_manager,
device=device,
)
def _parse_face(
line,
tokens,
material_idx,
faces_verts_idx,
faces_normals_idx,
faces_textures_idx,
faces_materials_idx,
) -> None:
face = tokens[1:]
face_list = [f.split("/") for f in face]
face_verts = []
face_normals = []
face_textures = []
for vert_props in face_list:
# Vertex index.
face_verts.append(int(vert_props[0]))
if len(vert_props) > 1:
if vert_props[1] != "":
# Texture index is present e.g. f 4/1/1.
face_textures.append(int(vert_props[1]))
if len(vert_props) > 2:
# Normal index present e.g. 4/1/1 or 4//1.
face_normals.append(int(vert_props[2]))
if len(vert_props) > 3:
raise ValueError(
"Face vertices can only have 3 properties. \
Face vert %s, Line: %s"
% (str(vert_props), str(line))
)
# Triplets must be consistent for all vertices in a face e.g.
# legal statement: f 4/1/1 3/2/1 2/1/1.
# illegal statement: f 4/1/1 3//1 2//1.
# If the face does not have normals or textures indices
# fill with pad value = -1. This will ensure that
# all the face index tensors will have F values where
# F is the number of faces.
if len(face_normals) > 0:
if not (len(face_verts) == len(face_normals)):
raise ValueError(
"Face %s is an illegal statement. \
Vertex properties are inconsistent. Line: %s"
% (str(face), str(line))
)
else:
face_normals = [-1] * len(face_verts) # Fill with -1
if len(face_textures) > 0:
if not (len(face_verts) == len(face_textures)):
raise ValueError(
"Face %s is an illegal statement. \
Vertex properties are inconsistent. Line: %s"
% (str(face), str(line))
)
else:
face_textures = [-1] * len(face_verts) # Fill with -1
# Subdivide faces with more than 3 vertices.
# See comments of the load_obj function for more details.
for i in range(len(face_verts) - 2):
faces_verts_idx.append((face_verts[0], face_verts[i + 1], face_verts[i + 2]))
faces_normals_idx.append(
(face_normals[0], face_normals[i + 1], face_normals[i + 2])
)
faces_textures_idx.append(
(face_textures[0], face_textures[i + 1], face_textures[i + 2])
)
faces_materials_idx.append(material_idx)
def _parse_obj(f, data_dir: str):
"""
Load a mesh from a file-like object. See load_obj function for more details
about the return values.
"""
verts, normals, verts_uvs = [], [], []
faces_verts_idx, faces_normals_idx, faces_textures_idx = [], [], []
faces_materials_idx = []
material_names = []
mtl_path = None
lines = [line.strip() for line in f]
# startswith expects each line to be a string. If the file is read in as
# bytes then first decode to strings.
if lines and isinstance(lines[0], bytes):
lines = [el.decode("utf-8") for el in lines]
materials_idx = -1
for line in lines:
tokens = line.strip().split()
if line.startswith("mtllib"):
if len(tokens) < 2:
raise ValueError("material file name is not specified")
# NOTE: only allow one .mtl file per .obj.
# Definitions for multiple materials can be included
# in this one .mtl file.
mtl_path = line[len(tokens[0]) :].strip() # Take the remainder of the line
mtl_path = os.path.join(data_dir, mtl_path)
elif len(tokens) and tokens[0] == "usemtl":
material_name = tokens[1]
# materials are often repeated for different parts
# of a mesh.
if material_name not in material_names:
material_names.append(material_name)
materials_idx = len(material_names) - 1
else:
materials_idx = material_names.index(material_name)
elif line.startswith("v "): # Line is a vertex.
vert = [float(x) for x in tokens[1:4]]
if len(vert) != 3:
msg = "Vertex %s does not have 3 values. Line: %s"
raise ValueError(msg % (str(vert), str(line)))
verts.append(vert)
elif line.startswith("vt "): # Line is a texture.
tx = [float(x) for x in tokens[1:3]]
if len(tx) != 2:
raise ValueError(
"Texture %s does not have 2 values. Line: %s" % (str(tx), str(line))
)
verts_uvs.append(tx)
elif line.startswith("vn "): # Line is a normal.
norm = [float(x) for x in tokens[1:4]]
if len(norm) != 3:
msg = "Normal %s does not have 3 values. Line: %s"
raise ValueError(msg % (str(norm), str(line)))
normals.append(norm)
elif line.startswith("f "): # Line is a face.
# Update face properties info.
_parse_face(
line,
tokens,
materials_idx,
faces_verts_idx,
faces_normals_idx,
faces_textures_idx,
faces_materials_idx,
)
return (
verts,
normals,
verts_uvs,
faces_verts_idx,
faces_normals_idx,
faces_textures_idx,
faces_materials_idx,
material_names,
mtl_path,
)
def _load_materials(
material_names: List[str],
f: Optional[str],
*,
data_dir: str,
load_textures: bool,
device: Device,
path_manager: PathManager,
):
"""
Load materials and optionally textures from the specified path.
Args:
material_names: a list of the material names found in the .obj file.
f: path to the material information.
data_dir: the directory where the material texture files are located.
load_textures: whether textures should be loaded.
device: Device (as str or torch.device) on which to return the new tensors.
path_manager: PathManager object to interpret paths.
Returns:
material_colors: dict of properties for each material.
texture_images: dict of material names and texture images.
"""
if not load_textures:
return None, None
if f is None:
warnings.warn("No mtl file provided")
return None, None
if not path_manager.exists(f):
warnings.warn(f"Mtl file does not exist: {f}")
return None, None
raise NotImplementedError("Please install Pytorch3D!")
# Texture mode uv wrap
# return load_mtl(
# f,
# material_names=material_names,
# data_dir=data_dir,
# path_manager=path_manager,
# device=device,
# )
def _load_obj(
f_obj,
*,
data_dir: str,
load_textures: bool = True,
create_texture_atlas: bool = False,
texture_atlas_size: int = 4,
texture_wrap: Optional[str] = "repeat",
path_manager: PathManager,
device: Device = "cpu",
):
"""
Load a mesh from a file-like object. See load_obj function more details.
Any material files associated with the obj are expected to be in the
directory given by data_dir.
"""
if texture_wrap is not None and texture_wrap not in ["repeat", "clamp"]:
msg = "texture_wrap must be one of ['repeat', 'clamp'] or None, got %s"
raise ValueError(msg % texture_wrap)
(
verts,
normals,
verts_uvs,
faces_verts_idx,
faces_normals_idx,
faces_textures_idx,
faces_materials_idx,
material_names,
mtl_path,
) = _parse_obj(f_obj, data_dir)
verts = _make_tensor(verts, cols=3, dtype=torch.float32, device=device) # (V, 3)
normals = _make_tensor(
normals,
cols=3,
dtype=torch.float32,
device=device,
) # (N, 3)
verts_uvs = _make_tensor(
verts_uvs,
cols=2,
dtype=torch.float32,
device=device,
) # (T, 2)
faces_verts_idx = _format_faces_indices(
faces_verts_idx, verts.shape[0], device=device
)
# Repeat for normals and textures if present.
if len(faces_normals_idx):
faces_normals_idx = _format_faces_indices(
faces_normals_idx, normals.shape[0], device=device, pad_value=-1
)
if len(faces_textures_idx):
faces_textures_idx = _format_faces_indices(
faces_textures_idx, verts_uvs.shape[0], device=device, pad_value=-1
)
if len(faces_materials_idx):
faces_materials_idx = torch.tensor(
faces_materials_idx, dtype=torch.int64, device=device
)
texture_atlas = None
material_colors, texture_images = _load_materials(
material_names,
mtl_path,
data_dir=data_dir,
load_textures=load_textures,
path_manager=path_manager,
device=device,
)
if material_colors and not material_names:
# usemtl was not present but single material was present in the .mtl file
material_names.append(next(iter(material_colors.keys())))
# replace all -1 by 0 material idx
if torch.is_tensor(faces_materials_idx):
faces_materials_idx.clamp_(min=0)
if create_texture_atlas:
raise NotImplementedError("Please install Pytorch3D!")
# # Using the images and properties from the
# # material file make a per face texture map.
# # Create an array of strings of material names for each face.
# # If faces_materials_idx == -1 then that face doesn't have a material.
# idx = faces_materials_idx.cpu().numpy()
# face_material_names = np.array(material_names)[idx] # (F,)
# face_material_names[idx == -1] = ""
# # Construct the atlas.
# texture_atlas = make_mesh_texture_atlas(
# material_colors,
# texture_images,
# face_material_names,
# faces_textures_idx,
# verts_uvs,
# texture_atlas_size,
# texture_wrap,
# )
faces = _Faces(
verts_idx=faces_verts_idx,
normals_idx=faces_normals_idx,
textures_idx=faces_textures_idx,
materials_idx=faces_materials_idx,
)
aux = _Aux(
normals=normals if len(normals) else None,
verts_uvs=verts_uvs if len(verts_uvs) else None,
material_colors=material_colors,
texture_images=texture_images,
texture_atlas=texture_atlas,
)
return verts, faces, aux
|