Maya –通过Python在视口中选择对象

时间:2019-04-04 11:51:48

标签: python viewport maya

有人可以帮助我吗?是否可以使用Python创建脚本以自动选择Maya视口中的每个对象?

有可能吗?

2 个答案:

答案 0 :(得分:4)

这很有可能,尽管您必须使用Maya的api来完成。您可以使用OpenMayaUI.MDrawTraversal收集相机视锥中的所有对象。

与使用OpenMaya.MGlobal.selectFromScreen相比,这似乎需要更长的时间,但是它可以为您带来一些好处:

  1. 即使未将其用作活动视图,也可以在任何相机上进行操作。
  2. 您可以执行所有需要做的事情,而无需选择并强制重画。
  3. OpenMaya.MGlobal.selectFromScreen将取决于接口,这意味着不可能在Maya批处理作业上执行它。无论哪种情况都可以使用。

话虽这么说,下面是一个示例,该示例将创建一堆随机框,创建一个看着它们的相机,然后选择相机视图内的所有框:

import random

import maya.cmds as cmds
import maya.OpenMaya as OpenMaya
import maya.OpenMayaUI as OpenMayaUI


# Create a new camera.
cam, cam_shape = cmds.camera()
cmds.move(15, 10, 15, cam)
cmds.rotate(-25, 45, 0, cam)
cmds.setAttr("{}.focalLength".format(cam), 70)
cmds.setAttr("{}.displayCameraFrustum".format(cam), True)

# Create a bunch of boxes at random positions.
val = 10
for i in range(50):
    new_cube, _ = cmds.polyCube()
    cmds.move(random.uniform(-val, val), random.uniform(-val, val), random.uniform(-val, val), new_cube)

# Add camera to MDagPath.
mdag_path = OpenMaya.MDagPath()
sel = OpenMaya.MSelectionList()
sel.add(cam)
sel.getDagPath(0, mdag_path)

# Create frustum object with camera.
draw_traversal = OpenMayaUI.MDrawTraversal()
draw_traversal.setFrustum(mdag_path, cmds.getAttr("defaultResolution.width"), cmds.getAttr("defaultResolution.height"))  # Use render's resolution.
draw_traversal.traverse()  # Traverse scene to get all objects in the camera's view.

frustum_objs = []

# Loop through objects within frustum.
for i in range(draw_traversal.numberOfItems()):
    # It will return shapes at first, so we need to fetch its transform.
    shape_dag_path = OpenMaya.MDagPath()
    draw_traversal.itemPath(i, shape_dag_path)
    transform_dag_path = OpenMaya.MDagPath()
    OpenMaya.MDagPath.getAPathTo(shape_dag_path.transform(), transform_dag_path)

    # Get object's long name and make sure it's a valid transform.
    obj = transform_dag_path.fullPathName()
    if cmds.objExists(obj):
        frustum_objs.append(obj)


# At this point we have a list of objects that we can filter by type and do whatever we want.
# In this case just select them.
cmds.select(frustum_objs)

希望能为您提供更好的指导。

答案 1 :(得分:3)

您可以尝试以下脚本

import maya.OpenMaya as om
import maya.OpenMayaUI as omUI
view = omUI.M3dView.active3dView()
om.MGlobal.selectFromScreen( 0, 0, view.portWidth(), view.portHeight(),om.MGlobal.kReplaceList)

我在https://forums.cgsociety.org/t/list-objects-in-viewport/1463426上找到了此代码段,似乎可以解决问题。您可以通读讨论以获取更多信息