code_test/usd设置关键帧.txt
2024-10-04 13:00:10 +08:00

1154 lines
32 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from pxr import Usd, UsdGeom, Gf
import random
# 创建一个新的USD场景
stage = Usd.Stage.CreateNew('HelloWorld.usda')
# 定义一个变换和一个球体
xformPrim = UsdGeom.Xform.Define(stage, '/hello')
spherePrim = UsdGeom.Sphere.Define(stage, '/hello/world')
# 获取球体的变换属性
xformAttr = UsdGeom.Xformable(spherePrim).AddTranslateOp()
# 在随机位置移动球体并设置十个关键帧
for frame in range(1, 11):
# 生成随机位置
pos = Gf.Vec3f(random.uniform(-10, 10), random.uniform(-10, 10), random.uniform(-10, 10))
# 设置关键帧
xformAttr.Set(pos, frame)
# 保存场景
stage.GetRootLayer().Save()
import maya.cmds as cmds
# 创建一个pxrUsdReferenceAssembly节点
usdNode = cmds.createNode('mayaUsdProxyShape')
# 加载USD文件
cmds.setAttr(usdNode + '.filePath', '/home/jcen/PycharmProjects/pythonProject4/sphere_animation.usda', type='string')
# 刷新节点以加载USD文件
cmds.refresh(usdNode)
https://github.com/kiryha/Houdini/wiki/Pixar-USD-Python-API#save-mesh-object-to-usd-file
from pxr import Usd, UsdGeom, Sdf
# 创建一个新的USD文件
stage = Usd.Stage.CreateNew('box.usda')
# 创建一个Box
box = UsdGeom.Xform.Define(stage, '/Box')
# 创建一个variantSet
variantSet = box.GetPrim().GetVariantSets().AddVariantSet('geo')
# 添加variant
for variantName in ['base', 'client_model', 'collision', 'deform_high', 'deform_low', 'display_high', 'display_low', 'garment', 'maquette', 'muscles', 'pose', 'render_high', 'scan_base', 'scan_high', 'scan_low', 'scan_mid', 'sculpt_bind', 'sculpt_pose', 'sculpt_symm', 'shapes_high']:
variantSet.AddVariant(variantName)
variantSet.SetVariantSelection(variantName)
with variantSet.GetVariantEditContext():
if variantName in ['base', 'deform_high', 'display_high', 'pose', 'render_high']:
# 在这些variant中我们添加一个extentsHint属性
box.GetPrim().CreateAttribute('extentsHint', Sdf.ValueTypeNames.Float3Array).Set([(-16.629925, -0.035511017, -11.017016), (16.459915, 3.3556676, 11.016925)])
# if variantName == 'base':
# # 在base变体中我们添加一个payload
# with stage.GetEditTarget().GetLayer().PermissionToEdit():
# box.GetPrim().GetPayloads().AddPayload(r"C:\Users\ARTIST\Desktop\tstProj\s.usda")
# 保存USD文件
stage.GetRootLayer().Save()
# -*- coding: utf-8 Jcen -*-
import os, shutil
import re
#
# file_size = 0
#
# for root, dirs, files in os.walk('W:/LFC'):
# try:
# if dirs[0] == 'render' and re.search('write', root.lower()):
# # print(root, dirs, files)
# # print()
# if re.search(r'v\d+', os.listdir(os.path.join(root.replace('\\', '/'), dirs[0]))[0]):
# # print(os.listdir(os.path.join(root.replace('\\', '/'), dirs[0])))
# # print(root, dirs, files, os.listdir(os.path.join(root.replace('\\', '/'), dirs[0]))[0])
#
# if re.search(r'.*[a-zA-Z]\d{2}_\d{3}.*', os.listdir(os.path.join(root, dirs[0], os.listdir(os.path.join(root.replace('\\', '/'), dirs[0]))[0]))[0]):
# path = os.path.join(root, dirs[0], os.listdir(os.path.join(root.replace('\\', '/'), dirs[0]))[0])
# file = os.listdir(path)
# for f in file:
# match1 = re.search(r'\.\d{4}\.exr|\.\d{3}\.exr', f)
# if match1:
# frame = match1.group()
# if len(frame) == 8:
# frame = frame[:1] + '0' + frame[1:]
# file_path = os.path.join(path, f).replace('\\', '/')
# new_file_path = ['T:/proj/LFC/FIND_EXR', root.replace('\\', '/').split('/')[2], root.replace('\\', '/').split('/')[3], 'render_' + root.replace('\\', '/').split('/')[3] + frame]
# # print(root.replace('\\', '/').split('/')[2], 'render_' + root.replace('\\', '/').split('/')[3], match1.group())
# file_size += os.path.getsize(file_path)
# print(file_path, '/'.join(new_file_path))
# print('/'.join('/'.join(new_file_path).split('/')[:-1]))
# # if not os.path.exists('/'.join('/'.join(new_file_path).split('/')[:-1])):
# # os.makedirs('/'.join('/'.join(new_file_path).split('/')[:-1]))
# shutil.copy2(file_path, '/'.join(new_file_path))
# except:
# pass
#
# print(file_size / (1024**3))
# for i in os.listdir(r'T:\proj\LFC\FIND_EXR\q30'):
# # os.rename()
# os.rename(os.path.join('T:\proj\LFC\FIND_EXR\q30', i), os.path.join('T:\proj\LFC\FIND_EXR\q30', 'render_'+i))
# from pxr import Usd, UsdGeom
# stage = Usd.Stage.CreateNew('HelloWorld.usda')
# xformPrim = UsdGeom.Xform.Define(stage, '/hello')
# spherePrim = UsdGeom.Sphere.Define(stage, '/hello/world')
# stage.GetRootLayer().Save()
# from pxr import Usd, UsdGeom
# stage = Usd.Stage.Open('Hello_World1.usda')
# colorAttr = UsdGeom.Gprim.Get(stage, '/Root/Mesh').GetDisplayColorAttr()
# colorAttr.Clear()
# print(stage.GetRootLayer().ExportToString())
#
# rootPrim = stage.GetPrimAtPath('/Root')
# vset = rootPrim.GetVariantSets().AddVariantSet('shadingVariant')
# print(stage.GetRootLayer().ExportToString())
#
#
# vset.AddVariant('red')
# vset.AddVariant('blue')
# vset.AddVariant('green')
# print(stage.GetRootLayer().ExportToString())
#
# vset.SetVariantSelection('red')
# with vset.GetVariantEditContext():
# colorAttr.Set([(1,0,0)])
#
# print(stage.GetRootLayer().ExportToString())
#
# vset.SetVariantSelection('blue')
# with vset.GetVariantEditContext():
# colorAttr.Set([(0,0,1)])
#
# vset.SetVariantSelection('green')
# with vset.GetVariantEditContext():
# colorAttr.Set([(0,1,0)])
#
# print(stage.GetRootLayer().ExportToString())
# stage.GetRootLayer().Export('HelloWorldWithVariants1.usda')
# from pxr import Usd, UsdGeom, Sdf
#
# def crate_geometry():
# """
# Procedurally create geometry and save it to the USDA file
# """
#
# # Create USD
# stage = Usd.Stage.CreateNew('hello_world1.usda')
#
# # Build mesh object
# root_xform = UsdGeom.Xform.Define(stage, '/Root')
# mesh = UsdGeom.Mesh.Define(stage, '/Root/Mesh')
#
# # Build mesh geometry. Here polygon creation magic should happen
# geometry_data = {'points': [(-1, 0, 1), (1, 0, 1), (1, 0, -1), (-1, 0, -1)],
# 'face_vertex_counts': [4],
# 'face_vertex_indices': [0, 1, 2, 3]}
#
# # Set mesh attributes
# mesh.GetPointsAttr().Set(geometry_data['points'])
# mesh.GetFaceVertexCountsAttr().Set(geometry_data['face_vertex_counts'])
# mesh.GetFaceVertexIndicesAttr().Set(geometry_data['face_vertex_indices'])
#
# # Save USD
# stage.GetRootLayer().Save()
#
#
# crate_geometry()
#
# from pxr import Usd, UsdGeom, Sdf, Gf, UsdShade
# import random
# stage = Usd.Stage.Open('HelloWorldWithVariants1.usda')
# material = UsdShade.Material.Define(stage, '/Root/Mesh')
#
# pbrShader = UsdShade.Shader.Define(stage, '/Root/Mesh/PBRShader')
# pbrShader.CreateIdAttr("UsdPreviewSurface")
# pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.4)
# pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
#
# # material.CreateSurfaceOutput().ConnectToSource(pbrShader.ConnectableAPI(), "surface")
# # stReader = UsdShade.Shader.Define(stage, '/Root/Mesh/stReader')
# # stReader.CreateIdAttr('UsdPrimvarReader_float2')
# # # 定义一个变换和一个球体
# # spherePrim = stage.GetPrimAtPath('/Root/Mesh')
# # # 获取球体的变换属性
# # xformAttr = UsdGeom.Xformable(spherePrim).AddTranslateOp()
# #
# # # 在随机位置移动球体并设置十个关键帧
# # for frame in range(1, 11):
# # # 生成随机位置
# # pos = Gf.Vec3f(random.uniform(-10, 10), random.uniform(-10, 10), random.uniform(-10, 10))
# #
# # # 设置关键帧
# # xformAttr.Set(pos, frame)
# #
# # 保存场景
# stage.GetRootLayer().Save()
from pxr import Usd, UsdGeom, Sdf, UsdShade
# 创建一个新的USD文件
stage = Usd.Stage.CreateNew('box.usda')
# 创建一个Box
box = UsdGeom.Xform.Define(stage, '/Box')
# stage = Usd.Stage.Open('box1.usda')
#
# print(dir(UsdGeom.Xform))
# try:
# print(UsdGeom.Xform.Get(stage, ''))
# except:
# pass
# # print(box)
# print(dir(stage))
# 创建一个variantSet
variantSet = box.GetPrim().GetVariantSets().AddVariantSet('geo')
# 添加variant
for variantName in ['base']:
# ', client_model', 'collision', 'deform_high', 'deform_low', 'display_high', 'display_low', 'garment', 'maquette', 'muscles', 'pose', 'render_high', 'scan_base', 'scan_high', 'scan_low', 'scan_mid', 'sculpt_bind', 'sculpt_pose', 'sculpt_symm', 'shapes_high']:
variantSet.AddVariant(variantName)
variantSet.SetVariantSelection(variantName)
if variantSet.GetVariantSelection() == 'base':
with variantSet.GetVariantEditContext():
new_xform = UsdGeom.Mesh.Define(stage, '/Box/NewXform')
new_xform.GetPrim().GetPayloads().AddPayload(r"C:\Users\ARTIST\Desktop\tstProj\s.usda")
with variantSet.GetVariantEditContext():
if variantName in ['base', 'deform_high', 'display_high', 'pose', 'render_high']:
# 在这些variant中我们添加一个extentsHint属性
box.GetPrim().CreateAttribute('extentsHint', Sdf.ValueTypeNames.Float3Array).Set([(-16.629925, -0.035511017, -11.017016), (16.459915, 3.3556676, 11.016925)])
# if variantName == 'base':
# box.GetPrim().CreateAttribute('extentsHint', Sdf.ValueTypeNames.Float3Array).Set(
# [(-16.629925, -0.035511017, -11.017016), (16.459915, 3.3556676, 11.016925)])
# # 在base变体中我们添加一个payload
# with stage.GetEditTarget().GetLayer().PermissionToEdit():
# box.GetPrim().GetPayloads().AddPayload(r"C:\Users\ARTIST\Desktop\tstProj\s.usda")
# 保存USD文件
stage.GetRootLayer().Save()
"""
Export geometry from Maya scene to USD file
"""
import random
from pxr import Usd, UsdGeom
import pymel.core as pm
def get_geometry_data(mesh):
"""
Get points data for each face for USD file record
"""
points = [] # World position coordinates (tuples) for each geometry point (point3f[] points)
face_vertex_counts = [] # Number of vertices in each geometry face (int[] faceVertexCounts)
face_vertex_indices = [] # List of geometry vertex indexes (int[] faceVertexIndices)
# Get vertex data for each face
vertex_index = 0
for face in mesh.faces:
vertex_indexes = []
for vertex in face.getVertices():
position = tuple(mesh.vtx[vertex].getPosition(space='world'))
points.append(position)
vertex_indexes.append(vertex_index)
vertex_index += 1
face_vertex_counts.append(len(vertex_indexes))
face_vertex_indices.extend(vertex_indexes)
return points, face_vertex_counts, face_vertex_indices
def process_geometry(stage, root_xform):
"""
Iterate over all scene meshes and record them to the USD stage
"""
for mesh in pm.ls(type='mesh'):
# Create a USD Mesh primitive for the mesh object
usd_mesh = UsdGeom.Mesh.Define(stage, root_xform.GetPath().AppendChild(mesh.getParent().name()))
# Get geometry data
points, face_vertex_counts, face_vertex_indices = get_geometry_data(mesh)
# Set the collected attributes for the USD Mesh
usd_mesh.GetPointsAttr().Set(points)
usd_mesh.GetFaceVertexCountsAttr().Set(face_vertex_counts)
usd_mesh.GetFaceVertexIndicesAttr().Set(face_vertex_indices)
def export_geometry():
"""
Create USD file and record geometry data
"""
# Create USD stage
usd_file_path = r"D:\Test\temp5.usda"
# Create USD stage and root object
stage = Usd.Stage.CreateNew(usd_file_path)
spherePrim = UsdGeom.Xform.Define(stage, '/pSphere1')
rootPrim = stage.GetPrimAtPath('/pSphere1')
stage.SetDefaultPrim(rootPrim)
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)
stage.SetMetadata('metersPerUnit', 0.01)
stage.GetRootLayer().documentation = "Generated from Composed Stage of pSphere1 layer"
root_xform = UsdGeom.Xform.Define(stage, '/')
process_geometry(stage, spherePrim)
# Save the USD stage to the file
stage.GetRootLayer().Save()
print(f'>> {usd_file_path}')
export_geometry()
# print(get_geometry_data(pm.ls(type='mesh')[0]))
"""
Export geometry from Maya scene to USD file
"""
import random
from pxr import Usd, UsdGeom
import pymel.core as pm
def get_geometry_data(mesh):
"""
Get points data for each face for USD file record
"""
points = []
face_vertex_counts = []
face_vertex_indices = []
uv_coords = []
vertex_index = 0
for face in mesh.faces:
vertex_indexes = []
for vertex in face.getVertices():
position = tuple(mesh.vtx[vertex].getPosition(space='world'))
points.append(position)
vertex_indexes.append(vertex_index)
vertex_index += 1
face_vertex_counts.append(len(vertex_indexes))
face_vertex_indices.extend(vertex_indexes)
uvs = mesh.getUVs()
for i in range(len(uvs[0])):
uv = (uvs[0][i], uvs[1][i])
uv_coords.append(uv)
return points, face_vertex_counts, face_vertex_indices, uv_coords
def process_geometry(stage, root_xform):
"""
Iterate over all scene meshes and record them to the USD stage
"""
for mesh in pm.ls(type='mesh'):
# Create a USD Mesh primitive for the mesh object
usd_mesh = UsdGeom.Mesh.Define(stage, root_xform.GetPath().AppendChild(mesh.getParent().name()))
# Get geometry data
points, face_vertex_counts, face_vertex_indices, uv_coords = get_geometry_data(mesh)
# Set the collected attributes for the USD Mesh
usd_mesh.GetPointsAttr().Set(points)
usd_mesh.GetFaceVertexCountsAttr().Set(face_vertex_counts)
usd_mesh.GetFaceVertexIndicesAttr().Set(face_vertex_indices)
stAttr = usd_mesh.GetPrim().CreateAttribute("primvars:st", Sdf.ValueTypeNames.TexCoord2fArray, False)
stAttr.Set(uv_coords)
def export_geometry():
"""
Create USD file and record geometry data
"""
# Create USD stage
usd_file_path = r"D:\Test\temp11.usda"
# Create USD stage and root object
stage = Usd.Stage.CreateNew(usd_file_path)
spherePrim = UsdGeom.Xform.Define(stage, '/pSphere1')
rootPrim = stage.GetPrimAtPath('/pSphere1')
stage.SetDefaultPrim(rootPrim)
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)
stage.SetMetadata('metersPerUnit', 0.01)
stage.GetRootLayer().documentation = "Generated from Composed Stage of pSphere1 layer"
root_xform = UsdGeom.Xform.Define(stage, '/')
process_geometry(stage, spherePrim)
# Save the USD stage to the file
stage.GetRootLayer().Save()
print(f'>> {usd_file_path}')
export_geometry()
# print(get_geometry_data(pm.ls(type='mesh')[0]))
"""
Export geometry from Maya scene to USD file
"""
import random
from pxr import Usd, UsdGeom, Sdf
import pymel.core as pm
def get_geometry_data(mesh):
"""
Get points data for each face for USD file record
"""
points = []
face_vertex_counts = []
face_vertex_indices = []
uv_coords = []
vertex_index = 0
for face in mesh.faces:
vertex_indexes = []
for vertex in face.getVertices():
position = tuple(mesh.vtx[vertex].getPosition(space='world'))
points.append(position)
vertex_indexes.append(vertex_index)
vertex_index += 1
face_vertex_counts.append(len(vertex_indexes))
face_vertex_indices.extend(vertex_indexes)
uvs = mesh.getUVs()
for i in range(len(uvs[0])):
uv = (uvs[0][i], uvs[1][i])
uv_coords.append(uv)
return points, face_vertex_counts, face_vertex_indices, uv_coords
def process_geometry(stage, root_xform):
"""
Iterate over all scene meshes and record them to the USD stage
"""
for mesh in pm.ls(type='mesh'):
# Create a USD Mesh primitive for the mesh object
usd_mesh = UsdGeom.Mesh.Define(stage, root_xform.GetPath().AppendChild(mesh.getParent().name()))
# Get geometry data
points, face_vertex_counts, face_vertex_indices, uv_coords = get_geometry_data(mesh)
# Set the collected attributes for the USD Mesh
usd_mesh.GetPointsAttr().Set(points)
usd_mesh.GetFaceVertexCountsAttr().Set(face_vertex_counts)
usd_mesh.GetFaceVertexIndicesAttr().Set(face_vertex_indices)
stAttr = usd_mesh.GetPrim().CreateAttribute("primvars:st", Sdf.ValueTypeNames.TexCoord2fArray, False)
stAttr.Set(uv_coords)
# 添加自定义数据
# 定义自定义数据
customData = {
"dictionary Maya": {
"token name": "map1"
}
}
stAttr.SetCustomData(customDataDict)
# 修改插值方式
# 修改插值方式的元数据
stAttr.SetMetadata("interpolation", UsdGeom.Tokens.faceVarying)
def export_geometry():
"""
Create USD file and record geometry data
"""
# Create USD stage
usd_file_path = r"C:\Users\Jcen\Desktop\USD\temp22.usda"
# Create USD stage and root object
stage = Usd.Stage.CreateNew(usd_file_path)
spherePrim = UsdGeom.Xform.Define(stage, '/pSphere1')
rootPrim = stage.GetPrimAtPath('/pSphere1')
stage.SetDefaultPrim(rootPrim)
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)
stage.SetMetadata('metersPerUnit', 0.01)
stage.GetRootLayer().documentation = "Generated from Composed Stage of pSphere1 layer"
root_xform = UsdGeom.Xform.Define(stage, '/')
process_geometry(stage, spherePrim)
# Save the USD stage to the file
stage.GetRootLayer().Save()
print(f'>> {usd_file_path}')
export_geometry()
# print(get_geometry_data(pm.ls(type='mesh')[0]))
import os
import tempfile
from pathlib import Path
import pymel.core as pm
from pxr import Kind, Sdf, Tf, Usd, UsdGeom, UsdShade
USD_ROOT = Path("Z:/Test_USD")
COMPONENT_NAME = "my_component"
def extract_geo_proxy(src_usd_stage: Usd.Stage, dst_usd_file: Path):
src_root_prim = src_usd_stage.GetDefaultPrim()
src_proxy_prim = src_root_prim.GetPrimAtPath("geo/proxy")
if not src_proxy_prim:
return
dst_usd_stage = Usd.Stage.CreateInMemory()
dst_proxy_prim = dst_usd_stage.DefinePrim("/proxy", "Scope")
dst_usd_stage.SetDefaultPrim(dst_proxy_prim)
UsdGeom.SetStageMetersPerUnit(dst_usd_stage, UsdGeom.LinearUnits.centimeters)
UsdGeom.SetStageUpAxis(dst_usd_stage, UsdGeom.Tokens.y)
UsdGeom.Imageable(dst_proxy_prim).GetPurposeAttr().Set(UsdGeom.Tokens.proxy)
# reference to the source proxy prim and then flatten the stage
dst_proxy_prim.GetReferences().AddReference(
assetPath=src_usd_stage.GetRootLayer().realPath,
primPath=src_proxy_prim.GetPath(),
)
dst_usd_stage.Flatten().Export(dst_usd_file.as_posix())
def extract_geo_render(src_usd_stage: Usd.Stage, dst_usd_file: Path):
src_root_prim = src_usd_stage.GetDefaultPrim()
src_render_prim = src_root_prim.GetPrimAtPath("geo/render")
if not src_render_prim:
return
dst_usd_stage = Usd.Stage.CreateInMemory()
dst_render_prim = dst_usd_stage.DefinePrim("/render", "Scope")
dst_usd_stage.SetDefaultPrim(dst_render_prim)
UsdGeom.SetStageMetersPerUnit(dst_usd_stage, UsdGeom.LinearUnits.centimeters)
UsdGeom.SetStageUpAxis(dst_usd_stage, UsdGeom.Tokens.y)
UsdGeom.Imageable(dst_render_prim).GetPurposeAttr().Set(UsdGeom.Tokens.render)
# reference to the source render prim and then flatten the stage
dst_render_prim.GetReferences().AddReference(
assetPath=src_usd_stage.GetRootLayer().realPath,
primPath=src_render_prim.GetPath(),
)
dst_usd_stage.Flatten().Export(dst_usd_file.as_posix())
def extract_material(src_usd_stage: Usd.Stage, dst_usd_file: Path):
src_root_prim = src_usd_stage.GetDefaultPrim()
src_material_prim = src_root_prim.GetPrimAtPath("mtl")
if not src_material_prim:
return
dst_usd_stage = Usd.Stage.CreateInMemory()
dst_usd_stage.OverridePrim("/root")
dst_mlt_prim = dst_usd_stage.DefinePrim("/root/mtl", "Scope")
dst_usd_stage.SetDefaultPrim(dst_mlt_prim)
# reference to the source material prim
dst_mlt_prim.GetReferences().AddReference(
assetPath=src_usd_stage.GetRootLayer().realPath,
primPath=src_material_prim.GetPath(),
)
# Iterate over all the prims under /root/geo and extract the material binding
for src_prim in Usd.PrimRange(src_root_prim.GetPrimAtPath("geo")):
if not src_prim.HasAPI(UsdShade.MaterialBindingAPI):
continue
# get the bound material from the source prim
src_material_binding_api = UsdShade.MaterialBindingAPI(src_prim)
material, relationship = src_material_binding_api.ComputeBoundMaterial()
if not material:
continue
# create override prim for the destination prim and set the material binding
dst_prim = dst_usd_stage.OverridePrim(src_prim.GetPath())
dst_material_binding_api = UsdShade.MaterialBindingAPI(dst_prim)
dst_material_binding_api.Bind(material)
dst_root_layer = dst_usd_stage.Flatten()
print(dst_root_layer.ExportToString())
dst_root_layer.Export(dst_usd_file.as_posix())
def construct_modelling_usd(
modelling_usd_file: Path,
proxy_usd_file: Path,
render_usd_file: Path,
):
usd_stage = Usd.Stage.CreateNew(modelling_usd_file.as_posix())
# create prims
root_prim = usd_stage.DefinePrim("/root", "Xform")
geo_prim = usd_stage.DefinePrim("/root/geo", "Scope")
proxy_prim = usd_stage.DefinePrim("/root/geo/proxy", "Scope")
render_prim = usd_stage.DefinePrim("/root/geo/render", "Scope")
# set root prim metadata
model_api = Usd.ModelAPI(root_prim)
model_api.SetKind(Kind.Tokens.component)
root_prim.SetInstanceable(True)
# use relative path to reference the proxy and render usd files
proxy_relative_path = os.path.relpath(proxy_usd_file, modelling_usd_file.parent)
proxy_prim.GetPayloads().SetPayloads([Sdf.Payload(proxy_relative_path)])
render_relative_path = os.path.relpath(render_usd_file, modelling_usd_file.parent)
render_prim.GetPayloads().SetPayloads([Sdf.Payload(render_relative_path)])
# set the metadata for the stage
usd_stage.SetDefaultPrim(root_prim)
UsdGeom.SetStageMetersPerUnit(usd_stage, UsdGeom.LinearUnits.centimeters)
UsdGeom.SetStageUpAxis(usd_stage, UsdGeom.Tokens.y)
# save the stage
usd_stage.Save()
def construct_component_usd(
component_usd_file: Path,
modelling_usd_file: Path,
material_usd_file: Path,
):
usd_stage = Usd.Stage.CreateNew(component_usd_file.as_posix())
# add modelling usd file and material usd file as sublayers
sub_layer_paths = usd_stage.GetRootLayer().subLayerPaths
sub_layer_paths.append(
os.path.relpath(material_usd_file, component_usd_file.parent)
)
sub_layer_paths.append(
os.path.relpath(modelling_usd_file, component_usd_file.parent)
)
usd_stage.Save()
def export_usd(dag_object):
# temp_dir = tempfile.mkdtemp(prefix="usd_export_")
# usd_file = os.path.join(temp_dir, "temp.usda")
usd_file = r"D:\Test\temp.usda"
pm.mayaUSDExport(
file=usd_file,
exportRoots=dag_object,
defaultUSDFormat="usda",
jobContext="Arnold",
stripNamespaces=True,
materialsScopeName="mtl",
)
print(usd_file)
return usd_file
usd_file = export_usd(pm.selected()[0])
src_usd_stage = Usd.Stage.Open(usd_file)
extract_geo_proxy(src_usd_stage, Path(r"D:\Test\proxy.usda"))
extract_geo_render(src_usd_stage, Path(r"D:\Test\render.usda"))
extract_material(src_usd_stage, Path(r"D:\Test\material.usda"))
construct_modelling_usd(
Path("D:/Test/modelling.usda"),
Path("D:/Test/proxy.usda"),
Path("D:/Test/render.usda"),
)
construct_component_usd(
Path("D:/Test/component.usda"),
Path("D:/Test/modelling.usda"),
Path("D:/Test/material.usda"),
)
def maya_export_usd_geo(path, startTime, endTime):
import maya.mel as mel
import os
mel.eval(
f'file -force -options ";exportUVs=1;exportSkels=none;exportSkin=none;exportBlendShapes=0;exportDisplayColor=0;;exportColorSets=1;exportComponentTags=1;defaultMeshScheme=catmullClark;animation=1;eulerFilter=0;staticSingleSample=0;startTime={startTime};endTime={endTime};frameStride=1;frameSample=0.0;defaultUSDFormat=usda;parentScope=;defaultPrim={};shadingMode=useRegistry;convertMaterialsTo=[UsdPreviewSurface];exportRelativeTextures=automatic;exportInstances=1;exportVisibility=1;mergeTransformAndShape=1;stripNamespaces=0;worldspace=0;excludeExportTypes=[]" -typ "USD Export" -pr -es "{path}";'
)
os.rename(path, path + 'a')
from pxr import Usd, UsdGeom, Sdf
import maya.cmds as cmds
import maya.mel as mel
# 创建一个新的USD Stage
stage = Usd.Stage.CreateNew('C:/Users/Jcen/Desktop/USD/yourStage10.usda')
# 在Maya中创建一个代表这个Stage的节点
mayaUsdNode = cmds.createNode('mayaUsdProxyShape', name='MyUSDStage')
cmds.setAttr(f'{mayaUsdNode}.filePath', 'C:/Users/Jcen/Desktop/USD/yourStage10.usda', type='string')
# 将sublayer文件添加到主Stage的层级中
stage.GetRootLayer().subLayerPaths.append("C:/Users/Jcen/PycharmProjects/USD/assembly/cube.usda")
# 创建一个新的USD Stage
sublayer1 = Usd.Stage.CreateNew('C:/Users/Jcen/Desktop/USD/sublayer7.usda')
stage.GetRootLayer().subLayerPaths.append('C:/Users/Jcen/Desktop/USD/sublayer7.usda')
Sdf.Layer.FindOrOpen("C:/Users/Jcen/PycharmProjects/USD/assembly/cube.usda").SetPermissionToEdit(False)
# 假设你已经知道要操作的层的名字或路径
layer_path = 'C:/Users/Jcen/Desktop/USD/sublayer7.usda'
# 使用MEL命令选中层
# 注意这里的命令可能需要根据实际的UI组件和层次结构进行调整
mel.eval(f'''mayaUsdEditTarget -edit -editTarget "{layer_path}" "|mayaUsdProxy1|MyUSDStage";''')
# 添加一个Xform和一个Cube
# xformPath = Sdf.Path('/World')
# cubePath = xformPath.AppendChild('Cube')
# xform = UsdGeom.Xform.Define(stage, xformPath)
# cube = UsdGeom.Cube.Define(stage, cubePath)
# 设置Cube的属性
# cube.GetSizeAttr().Set(1.0)
# 保存Stage
stage.GetRootLayer().Save()
# 刷新Maya视图以显示新的USD内容
cmds.refresh()
from pxr import Usd, UsdGeom, Sdf
import maya.cmds as cmds
import maya.mel as mel
# 创建一个新的USD Stage
stage = Usd.Stage.CreateNew('C:/Users/Jcen/Desktop/USD/yourStage10.usda')
# 在Maya中创建一个代表这个Stage的节点
mayaUsdNode = cmds.createNode('mayaUsdProxyShape', name='MyUSDStage')
cmds.setAttr(f'{mayaUsdNode}.filePath', 'C:/Users/Jcen/Desktop/USD/yourStage10.usda', type='string')
# 将sublayer文件添加到主Stage的层级中
stage.GetRootLayer().subLayerPaths.append("C:/Users/Jcen/PycharmProjects/USD/assembly/cube.usda")
# 创建一个新的USD Stage
sublayer1 = Usd.Stage.CreateNew('C:/Users/Jcen/Desktop/USD/sublayer7.usda')
stage.GetRootLayer().subLayerPaths.append('C:/Users/Jcen/Desktop/USD/sublayer7.usda')
Sdf.Layer.FindOrOpen("C:/Users/Jcen/PycharmProjects/USD/assembly/cube.usda").SetPermissionToEdit(False)
# 假设你已经知道要操作的层的名字或路径
layer_path = 'C:/Users/Jcen/Desktop/USD/sublayer7.usda'
# 使用MEL命令选中层
# 注意这里的命令可能需要根据实际的UI组件和层次结构进行调整
mel.eval(f'''mayaUsdEditTarget -edit -editTarget "{layer_path}" "|mayaUsdProxy1|MyUSDStage";''')
# 添加一个Xform和一个Cube
# xformPath = Sdf.Path('/World')
# cubePath = xformPath.AppendChild('Cube')
# xform = UsdGeom.Xform.Define(stage, xformPath)
# cube = UsdGeom.Cube.Define(stage, cubePath)
# 设置Cube的属性
# cube.GetSizeAttr().Set(1.0)
# 保存Stage
stage.GetRootLayer().Save()
# 刷新Maya视图以显示新的USD内容
cmds.refresh()
from pxr import Usd, UsdGeom, Sdf
import maya.cmds as cmds
import maya.mel as mel
path = 'C:/Users/Jcen/Desktop/USD/yourStage15.usda'
main = "C:/Users/Jcen/PycharmProjects/USD/assembly/cube.usda"
edit = 'C:/Users/Jcen/Desktop/USD/sublayer13.usda'
# 创建一个新的USD Stage
stage = Usd.Stage.CreateNew(path)
# 在Maya中创建一个代表这个Stage的节点
mayaUsdNode = cmds.createNode('mayaUsdProxyShape', name='MyUSDStage')
cmds.setAttr(f'{mayaUsdNode}.filePath', path, type='string')
# 将sublayer文件添加到主Stage的层级中
# workingLayer = Sdf.Layer.FindOrOpen(main)
# stage.SetEditTarget(workingLayer)
# workingLayer1 = Sdf.Layer.FindOrOpen("C:/Users/Jcen/Desktop/USD/sublayer8.usda")
# stage.SetEditTarget(workingLayer1)
stage.GetRootLayer().subLayerPaths.append(main)
# 创建一个新的USD Stage
sublayer1 = Usd.Stage.CreateNew(edit)
sublayer1.GetRootLayer().Save()
stage.GetRootLayer().subLayerPaths.append(edit)
Sdf.Layer.FindOrOpen(main).SetPermissionToEdit(False)
Sdf.Layer.FindOrOpen(path).SetPermissionToEdit(False)
# 假设你已经知道要操作的层的名字或路径
layer_path = edit
# 使用MEL命令选中层
# 注意这里的命令可能需要根据实际的UI组件和层次结构进行调整
mel.eval(f'''mayaUsdEditTarget -edit -editTarget "{layer_path}" "|mayaUsdProxy1|MyUSDStage";''')
# 添加一个Xform和一个Cube
# xformPath = Sdf.Path('/World')
# cubePath = xformPath.AppendChild('Cube')
# xform = UsdGeom.Xform.Define(stage, xformPath)
# cube = UsdGeom.Cube.Define(stage, cubePath)
# 设置Cube的属性
# cube.GetSizeAttr().Set(1.0)
# 保存Stage
# stage.GetRootLayer().Save()
# 刷新Maya视图以显示新的USD内容
cmds.refresh()
from pxr import Usd, UsdGeom, Sdf
stage = Usd.Stage.Open(r"C:\Users\Jcen\Desktop\test11111.usd")
rootPrim = stage.GetPrimAtPath('/pCube3')
stAttr = rootPrim.GetPrim().CreateAttribute("primvars:arnold:visibility:camera", Sdf.ValueTypeNames.Bool, False)
stAttr.Set(False)
stage.GetRootLayer().Save()
import maya.app.renderSetup.model.renderSetup as renderSetup
rs = renderSetup.instance()
selectedLayer = rs.getVisibleRenderLayer()
print("当前选择的 Render Setup 层是:", selectedLayer.name())
import maya.cmds as cmds
def customCallback():
print("Custom callback function executed before rendering")
# 在这里可以添加你想要在渲染前执行的操作
# 注册渲染前的回调函数
jobNum = cmds.scriptJob(event=["renderLayerManagerChange", customCallback], protected=True)
# 在这里可以添加其他需要执行的操作
# 删除回调函数
# cmds.scriptJob(kill=jobNum)
import ufe
for i in range(100):
print(i)
globalSelection = ufe.GlobalSelection.get()
print(globalSelection)
tt = globalSelection.front()
print(tt.path())
import mayaUsd.ufe
stage = mayaUsd.ufe.getStage(str(tt.path()).split('/')[0])
print(stage)
s = stage.GetRootLayer().realPath
print(s)
python("exec(open('C:/Users/Jcen/PycharmProjects/USD/renderseting/tstmel.py').read())");
from pxr import Usd, Sdf
# 创建源Stage并添加一个Prim
source_stage = Usd.Stage.CreateNew("source.usda")
source_prim = source_stage.DefinePrim("/SourcePrim", "Xform")
source_prim.CreateAttribute("exampleAttr", Sdf.ValueTypeNames.String).Set("Hello, USD")
# 创建新的Stage
new_stage = Usd.Stage.CreateNew("target.usda")
# 获取源Stage和新Stage的根Layer
source_layer = source_stage.GetRootLayer()
target_layer = new_stage.GetRootLayer()
# 复制Spec从源Layer到目标Layer
if Sdf.CopySpec(source_layer, source_prim.GetPath(), target_layer, "/TargetPrim"):
print("复制成功")
else:
print("复制失败")
# 保存新Stage
new_stage.GetRootLayer().Save()