Skip to content

Commit

Permalink
resolver type hints
Browse files Browse the repository at this point in the history
  • Loading branch information
mikedh committed Jun 17, 2024
1 parent ed9de89 commit 5df249f
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 21 deletions.
7 changes: 2 additions & 5 deletions trimesh/exchange/gltf.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@
from .. import rendering, resources, transformations, util, visual
from ..caching import hash_fast
from ..constants import log, tol
from ..resolvers import Resolver, ZipResolver
from ..resolvers import ResolverLike, ZipResolver
from ..scene.cameras import Camera
from ..typed import Mapping, NDArray, Optional, Stream, Union
from ..typed import NDArray, Optional, Stream
from ..util import triangle_strips_to_faces, unique_name
from ..visual.gloss import specular_to_pbr

Expand Down Expand Up @@ -50,9 +50,6 @@
}
}

# we can accept dict resolvers
ResolverLike = Union[Resolver, Mapping]

# GL geometry modes
_GL_LINES = 1
_GL_POINTS = 0
Expand Down
39 changes: 27 additions & 12 deletions trimesh/exchange/load.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
import os
import warnings

import numpy as np

Expand All @@ -9,7 +10,7 @@
from ..parent import Geometry
from ..points import PointCloud
from ..scene.scene import Scene, append_scenes
from ..typed import Dict, Loadable, Optional, Union
from ..typed import Loadable, Optional
from ..util import log
from . import misc
from .binvox import _binvox_loaders
Expand Down Expand Up @@ -71,11 +72,11 @@ def available_formats() -> set:
def load(
file_obj: Loadable,
file_type: Optional[str] = None,
resolver: Union[resolvers.Resolver, Dict, None] = None,
resolver: Optional[resolvers.ResolverLike] = None,
force: Optional[str] = None,
allow_remote: bool = False,
**kwargs,
) -> Scene:
):
"""
Load a mesh or vectorized path into objects like
Trimesh, Path2D, Path3D, Scene
Expand Down Expand Up @@ -117,6 +118,9 @@ def load(
is_remote, # is this a URL
) = _parse_file_args(file_obj=file_obj, file_type=file_type, resolver=resolver)

if is_remote and not allow_remote:
raise ValueError("URL passed with `allow_remote=False`")

try:
if isinstance(file_obj, dict):
# if we've been passed a dict treat it as kwargs
Expand Down Expand Up @@ -147,7 +151,7 @@ def load(
else:
raise ValueError(f"File type: {file_type} not supported")
finally:
# close any opened files even if we crashed out
# close any opened files even if we crashed
if opened:
file_obj.close()

Expand All @@ -159,21 +163,32 @@ def load(
elif isinstance(getattr(loaded, "metadata", None), dict):
loaded.metadata.update(metadata)

# if we opened the file in this function ourselves from a
# file name clean up after ourselves by closing it
if opened:
file_obj.close()
if force is None:
# old behavior
return loaded

# combine a scene into a single mesh
if force == "mesh" and isinstance(loaded, Scene):
return util.concatenate(loaded.dump())
if force == "mesh":
warnings.warn(
"``trimesh.load(... force='mesh')`"
+ "and should be replaced with `trimesh.load_mesh`"
+ "current functionality may be replaced June 2025.",
category=DeprecationWarning,
stacklevel=2,
)
# coerce values into a mesh
return Scene(loaded).to_mesh()

if not isinstance(loaded, Scene):
return Scene(loaded)

return loaded


def load_scene(*args, **kwargs) -> Scene:
""" """


def load_mesh(*args, **kwargs) -> Trimesh:
"""
Load a mesh file into a Trimesh object.
Expand All @@ -192,7 +207,7 @@ def load_mesh(*args, **kwargs) -> Trimesh:
mesh
Loaded geometry data.
"""
return load(*args, **kwargs).dump_mesh()
return load(*args, **kwargs, force="scene").to_mesh()


def _load_compressed(file_obj, file_type=None, resolver=None, mixed=False, **kwargs):
Expand Down Expand Up @@ -484,7 +499,7 @@ def handle_pointcloud():
def _parse_file_args(
file_obj: Loadable,
file_type: Optional[str],
resolver: Union[None, Dict, resolvers.Resolver] = None,
resolver: Optional[resolvers.ResolverLike] = None,
**kwargs,
):
"""
Expand Down
8 changes: 6 additions & 2 deletions trimesh/resolvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import os

from . import caching, util
from .typed import Dict, Optional
from .typed import Dict, Mapping, Optional, Union

# URL parsing for remote resources via WebResolver
try:
Expand Down Expand Up @@ -167,7 +167,7 @@ class ZipResolver(Resolver):
Resolve files inside a ZIP archive.
"""

def __init__(self, archive:Optional[Dict]=None, namespace: Optional[str]=None):
def __init__(self, archive: Optional[Dict] = None, namespace: Optional[str] = None):
"""
Resolve files inside a ZIP archive as loaded by
trimesh.util.decompress
Expand Down Expand Up @@ -569,3 +569,7 @@ def trim(prefix, item):
strip = namespace.strip("/").split("/")[: -name.count("..")]
strip.extend(name.split("..")[-1].strip("/").split("/"))
yield "/".join(strip)


# most loaders can use a mapping in additon to a resolver
ResolverLike = Union[Resolver, Mapping]
3 changes: 1 addition & 2 deletions trimesh/scene/scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -847,8 +847,7 @@ def rezero(self) -> None:
self.graph.base_frame = new_base

def dump_mesh(self):
"""
"""
""" """
return self.dump(concatenate=True)

def dump(self, concatenate: bool = False) -> Union[Geometry, List[Geometry]]:
Expand Down

0 comments on commit 5df249f

Please sign in to comment.