Skip to content

Commit

Permalink
add explicit converters for geometries and visuals
Browse files Browse the repository at this point in the history
  • Loading branch information
schlegelp committed May 12, 2024
1 parent 7a2fccc commit b9421b5
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
6 changes: 3 additions & 3 deletions octarine/conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
import trimesh as tm

from .utils import is_hashable, is_points, is_lines, is_volume, is_mesh_like, is_pygfx_visual, is_pygfx_geometry
from .visuals import points2gfx, lines2gfx, mesh2gfx, trimesh2gfx, volume2gfx, scene2gfx
from .visuals import points2gfx, lines2gfx, mesh2gfx, trimesh2gfx, volume2gfx, scene2gfx, geometry2gfx, visual_passthrough

CONVERTERS = {
is_pygfx_visual: lambda x: x, # pass-through
is_pygfx_geometry: lambda x: gfx.Mesh(x, gfx.MeshPhongMaterial()), # add default material and return
is_pygfx_visual: visual_passthrough, # pass-through
is_pygfx_geometry: geometry2gfx, # add default material and return
tm.Trimesh: trimesh2gfx,
tm.Scene: scene2gfx,
is_mesh_like: mesh2gfx,
Expand Down
38 changes: 38 additions & 0 deletions octarine/visuals.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,37 @@ def mesh2gfx(mesh, color, alpha=None):
return vis


def geometry2gfx(geometry, color, alpha=None):
"""Convert a pygfx.Geometry to a pygfx.Mesh.
Parameters
----------
geometry : pygfx.Geometry
Geometry to convert.
color : str | tuple | array
Color to use for plotting. If multiple colors,
must be a list of colors with the same length as
the number of faces or vertices.
alpha : float, optional
Opacity value [0-1]. If provided, will override
the alpha channel of the color.
"""
# Parse color
mat_color_kwargs, obj_color_kwargs = parse_mesh_color(geometry, color, alpha)

if "colors" in obj_color_kwargs:
geometry.colors = obj_color_kwargs["colors"]

vis = gfx.Mesh(geometry, gfx.MeshPhongMaterial(**mat_color_kwargs))

# Add custom attributes
vis._object_type = "mesh"
vis._object_id = uuid.uuid4()

return vis


def parse_mesh_color(mesh, color, alpha=None):
"""Parse color for mesh plotting."""
mat_color_kwargs = dict()
Expand Down Expand Up @@ -663,3 +694,10 @@ def text2gfx(
)
text.local.position = position
return text


def visual_passthrough(x, *args, **kwargs):
"""Pass-through converter."""
if any(args) or any(kwargs):
logger.info("Pygfx visuals are passed-through as is. Any additional arguments are ignored.")
return x

0 comments on commit b9421b5

Please sign in to comment.