Advertisement
thureinfree

material group

Jun 7th, 2024
408
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. import hou
  2. from pxr import Usd, UsdGeom, Sdf, UsdShade
  3.  
  4. # Access the USD stage from the LOPS context
  5. stage = hou.pwd().editableStage()
  6.  
  7. def gather_mesh_prims(prim):
  8.     """Recursively gather all mesh prims under the given prim."""
  9.     mesh_prims = []
  10.     if prim.IsA(UsdGeom.Mesh):
  11.         mesh_prims.append(prim)
  12.    
  13.     for child in prim.GetAllChildren():
  14.         mesh_prims.extend(gather_mesh_prims(child))
  15.    
  16.     return mesh_prims
  17.  
  18. def get_bound_material(mesh_prim):
  19.     """Get the material bound to the given mesh prim."""
  20.     bindings = UsdShade.MaterialBindingAPI(mesh_prim)
  21.     bound_material = bindings.ComputeBoundMaterial()[0]
  22.     return bound_material
  23.  
  24. def group_mesh_prims_by_material(root_prim):
  25.     """Return a dictionary of mesh prims grouped by their bound materials."""
  26.     all_mesh_prims = gather_mesh_prims(root_prim)
  27.     mesh_prims_by_material = {}
  28.    
  29.     for mesh_prim in all_mesh_prims:
  30.         bound_material = get_bound_material(mesh_prim)
  31.         material_path = bound_material.GetPath() if bound_material else Sdf.Path.emptyPath
  32.         if material_path not in mesh_prims_by_material:
  33.             mesh_prims_by_material[material_path] = []
  34.         mesh_prims_by_material[material_path].append(mesh_prim)
  35.    
  36.     return mesh_prims_by_material
  37.  
  38. # Test with a root prim
  39. root_prim_path = "/geo"
  40. root_prim = stage.GetPrimAtPath(root_prim_path)
  41.  
  42. # Get the mesh prims grouped by their bound materials
  43. mesh_prims_by_material = group_mesh_prims_by_material(root_prim)
  44.  
  45. # Print the results
  46. for material_path, mesh_prims in mesh_prims_by_material.items():
  47.     material_path_str = str(material_path) if material_path != Sdf.Path.emptyPath else "No Material"
  48.     print(f"Material: {material_path_str}")
  49.     for mesh_prim in mesh_prims:
  50.         print(f"  Mesh Prim: {mesh_prim.GetPath()}")
  51.  
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement