Example #1
0
def combine_separate():
    """
    Depending on selection will combine or separate objects.

    Script will try to retain the transforms and outline position of the
    first object selected.

    """
    def clean_up_object(new):
        """
        Cleans up after `polyUnite` / `polySeparate`
        """
        if not new.get_parent() == parent:
            new.set_parent(parent)

        cmds.reorder(str(new), f=True)
        cmds.reorder(str(new), r=outliner_index)
        new.transform.set_pivot(pivot)

        new.attr['rotate'] = list(transforms.rotate)
        new.attr['scale'] = list(transforms.scale)
        return cmds.rename(str(new), name.split('|')[-1])

    selected = mampy.daglist(os=True, tr=True, l=True)
    if not selected:
        raise InvalidSelection()

    dag = selected.pop()
    name, parent = dag.short_name, dag.get_parent()
    transforms = dag.transform.get_transforms()
    pivot = dag.transform.get_rotate_pivot()

    if selected:
        logger.debug('Combining Objects.')
        for each in selected:
            if dag.is_child_of(each):
                raise InvalidSelection('Cannot parent an object to one of its '
                                       'children')
            elif dag.is_parent_of(each):
                continue
            each.set_parent(each)

    outliner_index = get_outliner_index(dag)
    dag.transform.attr['rotate'] = (0, 0, 0)
    dag.transform.attr['scale'] = (1, 1, 1)

    if selected:
        new_dag = Node(cmds.polyUnite(name, selected.cmdslist(), ch=False)[0])
        cmds.select(clean_up_object(new_dag), r=True)
    else:
        logger.debug('Separate Objects.')
        new_dags = mampy.daglist(cmds.polySeparate(name, ch=False))
        for new in new_dags:
            cmds.rename(clean_up_object(new), name.split('|')[-1])
        cmds.delete(name)
        cmds.select(new_dags.cmdslist(), r=True)
Example #2
0
def set_mask(*masks):
    """Set selection masks in maya.

    if the current mask is the given mask toggle object component mode. This is the
    default mode maya uses when switching selection masks. You will be able to continue
    selecting components but also select other objects as maya objects.

    Usage:

        set_mask('vertex', 'controlVertex', 'latticePoint')
        set_mask('meshComponents')

    """
    component_masks = {mask: True for mask in masks}
    if (cmds.selectMode(q=True, component=True) and
            any(cmds.selectType(q=True, **{mask: True}) for mask in component_masks.iterkeys())):
        cmds.selectMode(object=True)
        cmds.selectType(ocm=True, alc=False)
        cmds.selectType(ocm=True, **component_masks)
        cmds.selectType(**component_masks)
        cmds.hilite(mampy.daglist().cmdslist())
    else:
        cmds.selectMode(component=True)
        cmds.selectType(allComponents=False)
        cmds.selectType(**component_masks)
Example #3
0
def unhide_all(unhide_types=None):
    """
    unhide all groups and mesh objects in the scene.
    """
    for trans in mampy.daglist(transforms=True):
        if trans.shape is None or trans.shape.type == MFn.kMesh:
            trans.attr["visibility"] = True
Example #4
0
def exit_tool_and_mask():
    """Exit current tool or toggle selection mode.

    When working with other contexts in maya use this function to exit the current
    context and return to selection context; if you are using base tools ('select',
    move, rotate, scale) toggle selection mode instead.

    Usage:

        tool_select()

    """
    # base_tools = ['{}SuperContext'.format(i) for i in ('select', 'move', 'rotate', 'scale')]
    if not cmds.currentCtx() == 'selectSuperContext':
        cmds.setToolTo('selectSuperContext')
    else:
        if cmds.selectMode(q=True, object=True):
            hilited = mampy.daglist(hl=True)
            if hilited:
                cmds.hilite(hilited.cmdslist(), toggle=True)
                cmds.select(hilited.cmdslist())
            else:
                cmds.selectMode(component=True)
        else:
            cmds.selectMode(object=True)
Example #5
0
def set_isolate_set(selected):
    set_name = get_isolate_set_name()
    # Trying to hide visible children in hierarchy to get wanted isolate
    # behavior.
    for sel in selected:
        for child in sel.iterchildren():
            if child in selected or not child.type == MFn.kTransform:
                continue
            # Only work on visible children
            if child.attr['visibility']:
                child.attr['visibility'] = False
                HIDDEN_CHILDREN.add(child)

    hilited = DagpathList(
        [dag for dag in mampy.daglist(hl=True) if dag not in selected]
    )
    if hilited:
        cmds.hilite(hilited.cmdslist(), toggle=True)
        # In case the dag object was a child of unhilited object rehilite it.
        for dag in selected:
            cmds.hilite(str(dag))

    if not set_name:
        for dag in selected:
            cmds.isolateSelect(get_active_panel(), addDagObject=str(dag))
        return

    cmds.sets(clear=set_name)
    cmds.sets(selected.cmdslist(), include=set_name)
Example #6
0
def poly_invert(shell=False):
    """
    Invert selection.

    If shell is active but there are no selections, script assumes we
    want a full invert.

    .. note:: If current selection mask is *object* and there are no
        selections there is no way that I know of to find out the active
        component type.
    """
    # To find out how we want to operate on the objects we walk through
    # the possible outcomes leaving the object list at last.
    modes = [mampy.complist(), mampy.daglist(hl=True), mampy.daglist()]
    for mode, selected in enumerate(modes):
        if not selected:
            continue
        break

    if mode == 2:
        if not selected:
            cmds.select(mampy.daglist(visible=True, assemblies=True).cmdslist())
        else:
            cmds.select(selected.cmdslist(), toggle=True)
    if mode == 1:
        for mask in get_active_flags_in_mask(object=False):
            try:
                active_mask = {
                    'facet': MFn.kMeshPolygonComponent,
                    'edge': MFn.kMeshEdgeComponent,
                    'vertex': MFn.kMeshVertComponent,
                    'polymeshUV': MFn.kMeshMapComponent,
                }[mask]; break
            except KeyError:
                continue
        for dag in selected:
            component = SingleIndexComponent.create(dag.dagpath, active_mask)
            cmds.select(component.get_complete().cmdslist(), toggle=True)
    if mode == 0:
        selection_list = ComponentList()
        for comp in selected:
            if shell:
                for mesh in comp.mesh_shells.itervalues():
                    selection_list.append(mesh)
            else:
                selection_list.append(comp.get_complete())
        cmds.select(selection_list.cmdslist(), toggle=True)
Example #7
0
def nonquads(ngons=True, query=False):
    """
    Select all nonquads from an object.
    """
    type_ = 3 if ngons else 1

    if query:
        selected = mampy.daglist()

    cmds.selectMode(component=True)
    cmds.selectType(facet=True)

    cmds.polySelectConstraint(mode=3, t=0x0008, size=type_)
    cmds.polySelectConstraint(disable=True)
    ngons = mampy.daglist()

    if query:
        cmds.select(selected.cmdslist())
        return ngons
    sys.stdout.write(str(len(ngons)) + ' N-Gon(s) Selected.\n')
Example #8
0
def display_xray():
    """
    Toggles xray on selected objects.
    """
    selected = mampy.daglist()
    if not selected:
        return logger.warn("Nothing selected.")

    for dag in selected:
        if dag.shape and dag.shape.type == MFn.kMesh:
            state = cmds.displaySurface(str(dag.shape), q=True, xRay=True).pop()
            cmds.displaySurface(str(dag.shape), xRay=not (state))
def detach(extract=False):
    """
    Dispatches function call depening on selection type or type of panel
    under cursor.
    """
    selected = mampy.complist() or mampy.daglist()
    if not selected:
        raise NothingSelected()

    object_type = selected.pop().type
    if object_type == MFn.kMeshPolygonComponent:
        mamtools.mesh.detach(extract)
    elif object_type in [api.MFn.kTransform]:
        cmds.duplicate(rr=True)
Example #10
0
def find_matching_in_hilited(objects):
    hilited = mampy.daglist(hl=True, dag=True, type='mesh')
    if not hilited:
        return objects

    for obj in objects:
        parent = str(obj).lstrip('|').split('|')[0]
        for child in hilited:
            if child == obj:
                continue
            child_name = str(child).lstrip('|').split('|')[0]
            if parent == child_name:
                objects.append(child)
    return objects
Example #11
0
def get_face_weighted_sets():
    sets = cmds.ls('{}*'.format(_face_weighted_name))
    selected, to_weight = mampy.daglist(), ComponentList()
    if selected:
        for each in selected:
            set_name = get_face_weighted_set_name(each.transform.short_name)
            if set_name in sets:
                to_weight.extend(mampy.complist(cmds.sets(set_name, q=True)))
    else:
        for set_name in sets:
            try:
                to_weight.extend(mampy.complist(cmds.sets(set_name, q=True)))
            except ValueError:
                continue
    return to_weight
Example #12
0
def toggle_mesh_under_cursor():
    """Toggle mesh object under cursor."""
    preselect = mampy.complist(preSelectHilite=True)
    if not preselect:
        under_cursor_mesh = get_object_under_cursor()
        if under_cursor_mesh is None:
            return
        node = Node(under_cursor_mesh)
        if cmds.selectMode(q=True, component=True):
            cmds.hilite(str(node.transform))
        else:
            cmds.select(str(node), toggle=True)
    else:
        node = preselect.pop().mdag
        if node.transform in mampy.daglist(hl=True):
            cmds.hilite(str(node.transform), unHilite=True)
Example #13
0
def set_isolate_selected_off_or_update():
    global SELECT_CHANGE_EVENT
    isoset = mampy.daglist(cmds.sets(get_isolate_set_name(), q=True))
    selset = get_selected_objects()

    if isoset:
        if isoset == selset or not selset:
            try:
                MEventMessage.removeCallback(SELECT_CHANGE_EVENT)
                SELECT_CHANGE_EVENT = None
            except RuntimeError:
                pass
            cmds.isolateSelect(get_active_panel(), state=False)
            # Show hidden children again and clear HIDDEN_CHILDREN list to
            # avoid uncertain clashes.
            for child in HIDDEN_CHILDREN:
                child.attr['visibility'] = True
            HIDDEN_CHILDREN.clear()
        else:
            set_isolate_set(selset)
Example #14
0
def delete(cv=False):
    """Custom delete using 'right' delete function depending on selection."""
    selected = mampy.complist() or mampy.daglist()
    if not selected:
        return logger.warn("Nothing to delete.")

    for each in selected:
        if isinstance(each, SingleIndexComponent):
            # Try to delete supported types if that fails uss default delete in
            # maya
            try:
                {
                    MFn.kMeshEdgeComponent: partial(cmds.polyDelEdge, each.cmdslist(), cv=cv),
                    MFn.kMeshVertComponent: partial(cmds.polyDelVertex, each.cmdslist()),
                    MFn.kMeshPolygonComponent: partial(cmds.polyDelFacet, each.cmdslist()),
                }[each.type]()
            except KeyError:
                cmds.delete(each.cmdslist())
        else:
            cmds.delete(str(each))
    cmds.select(cl=True)
def merge():
    """
    Dispatches function call depending on selection type
    """
    selected = mampy.complist() or mampy.daglist()
    if not selected:
        raise NothingSelected()

    control_object = selected.pop()
    if control_object.type in [MFn.kTransform]:
        object_type = control_object.shape.type
    else:
        object_type = control_object.type

    try:
        {
            MFn.kMeshVertComponent: functools.partial(mamtools.delete.merge_verts,
                                                      False),
            MFn.kMeshPolygonComponent: mamtools.delete.merge_faces,
            MFn.kMeshEdgeComponent: mamtools.delete.collapse,
            MFn.kMesh: mamtools.mesh.combine_separate,
        }[object_type]()
    except KeyError:
        logger.warn('{} is not a valid type'.format(object_type))
Example #16
0
def get_mesh_objects(mode):
    objects = {
        All: partial(mampy.daglist, type='mesh'),
        Hierarchy: partial(mampy.daglist, sl=True, dag=True, type='mesh'),
        Selected: partial(mampy.daglist, sl=True),
    }[mode]()
    if mode == All:
        return objects
    elif mode == Hierarchy and not objects:
        objects = mampy.daglist()

    # Make subd toggle work when in component mode.
    if mode == Hierarchy:
        objects = find_matching_in_hilited(objects)
    # Add hilited objects to existing list and sort out meshes.
    # objects.extend(other)
    mesh_objects = DagpathList()
    for dag in objects:
        if dag.type == MFn.kMesh:
            mesh_objects.append(dag)
        else:
            if dag.shape.type == MFn.kMesh:
                mesh_objects.append(dag.shape)
    return mesh_objects
def test_daglist_empty_with_dependency_node_selected():
    with mesh_cube('test_cube') as cube:
        mesh, plug = cube
        cmds.select(plug)
        assert not mampy.daglist()
Example #18
0
def get_selected_objects():
    return mampy.daglist([dag.transform for dag in mampy.daglist()])
Example #19
0
def visibility_toggle():
    """
    Toggle visibility of selected objects.
    """
    for dag in mampy.daglist():
        dag.attr["visibility"] = not (dag.attr["visibility"])
Example #20
0
def transforms(translate=False, rotate=False, scale=False):
    """Small function to control transform freezes."""
    transforms = [str(dp.transform) for dp in mampy.daglist()]
    cmds.makeIdentity(transforms, t=translate, r=rotate, s=scale, apply=True)
Example #21
0
def history():
    """Delete history on selected objects, works on hilited objects."""
    with undoable():
        for each in mampy.daglist():
            cmds.delete(str(each.transform), ch=True)