Exemple #1
0
def move_selection_to_mouse(uievent, include_ancestors=False):

    items = set(hou.selectedItems())
    if not items: return
    if include_ancestors:
        ancestors = set()
        for node in items:
            ancestors = ancestors.union(set(node.inputAncestors()))
        items = items.union(ancestors)

    last = hou.selectedItems()[-1]
    delta = uievent.editor.cursorPosition() - last.position()
    with hou.undos.group("Move nodes"):
        for item in items:
            item.setPosition(item.position() + delta)
Exemple #2
0
def run(alt_mode=False):
    rv_list = []
    nodes = hou.selectedNodes()
    for node in nodes:
        #print node.name(), node.type().name(),  node.color()
        rv = []
        if alt_mode:
            rv = alt.customProcessNode(node)
        else:
            rv = std.customProcessNode(node)        
        if rv:
            rv_list.append(rv)
        colors.customProcessNode(node)        

    # netboxes
    items = [x for x in hou.selectedItems() if x not in nodes]
    for item in items:
        c = hou.ui.selectColor(item.color())
        if c:
            item.setColor(c)
        
    # rv
    if len(rv_list)>0 and alt_mode:
        cmd = 'rv -tile '+' '.join(rv_list)   
        print cmd
        subprocess.Popen( cmd.split(), stdout=subprocess.PIPE)
Exemple #3
0
def add_to_selection(nodes, kwargs, selectMode=None, statMsg=None):
    """Extends the current node selection with 'nodes', according to
    the modifier keys in kwargs.

    no modifier:    replace selection
    shift, alt:     add to selection
    ctrl:           remove from selection
    ctrl+shift:     intersect with selection
    """
    assert selectMode is None or type(selectMode) is str

    haz_shift = kwargs["shiftclick"] or kwargs['altclick']
    haz_ctrl = kwargs["ctrlclick"]

    if selectMode is None:
        # determine select mode based on kwargs
        if haz_shift or haz_ctrl:
            # we got some modifier pressed
            if haz_shift:
                # shift: add (union), shift+ctrl: intersect
                selectMode = "intersect" if haz_ctrl else "add"
            else:
                # ctrl: remove from selection
                selectMode = "remove"
    else:
        selectMode = selectMode.lower()

    current = set(hou.selectedItems())
    sel = set(nodes)
    sel_length_old = len(sel)

    if selectMode == "intersect":
        sel = sel.intersection(current)
    elif selectMode == "add":
        sel = sel.union(current)
    elif selectMode == "remove":
        sel = current.difference(sel)
    else:
        selectMode = "replace"

    if sel is not None:
        hou.clearAllSelected()
        for n in sel:
            n.setSelected(True)

    # report back

    msg0 = "Select (%s) %d matches: Now %d selected (was %d)" \
        % ( selectMode.lower(), sel_length_old, len(sel), len(current), )

    if statMsg:
        msg0 = msg0 + " " + str(statMsg)

    if "editor" in kwargs:
        kwargs["editor"].flashMessage("BUTTONS_reselect", msg0, FLASH_SECONDS)

    statmsg("%s    (ALT: add to selection"
            ", CTRL:remove from selecton"
            ", CTRL+ALT:intersect with selection)" % msg0)
Exemple #4
0
def hcopyweb():
    qapp = QApplication.instance()
    try:
        nodes = hou.selectedItems()
    except:
        nodes = hou.selectedNodes()

    enctype = hpasteoptions.getOption('hpasteweb.encryption_type', 'None')
    key = None
    encparms = {}
    if enctype == 'AES-CBC':
        key = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for x in xrange(AES.block_size)
        ])
        encparms = {'mode': AES.MODE_CBC}
        enctype = 'AES'
    elif enctype.lower() == 'none' or enctype == '':
        enctype = None

    if enctype is not None and key is None:
        print('Warning: unknown encryption method, disabling encryption')
        enctype = None

    try:
        s = nodesToString(nodes, encryption_type=enctype, key=key, **encparms)
    except RuntimeError as e:
        hou.ui.displayMessage("Error: %s" % str(e.message),
                              severity=hou.severityType.Error)
        return
    except RuntimeWarning as e:  # da heck?
        hou.ui.displayMessage("Warning: %s" % str(e.message),
                              severity=hou.severityType.Warning)
    #except Exception as e:
    #    hou.ui.displayMessage("Internal Error: %s %s" % (str(type(e)), str(e.message)), severity=hou.severityType.Error)
    #    return

    if isinstance(qapp, QApplication):
        qapp.setOverrideCursor(qtc.Qt.WaitCursor)
    try:
        s = webPack(s)
    except Exception as e:
        hou.ui.displayMessage(e.message,
                              severity=hou.severityType.Error,
                              title='error')
        return
    finally:
        if isinstance(qapp, QApplication):
            qapp.restoreOverrideCursor()

    # append key to snippet
    if enctype is not None:
        s = key + '!' + s
    if hou.applicationVersion()[0] > 15:
        hou.ui.copyTextToClipboard(s)
    else:
        qapp.clipboard().setText(s)
    hou.ui.setStatusMessage("Success: Cloud link copied to clipboard!")
Exemple #5
0
def _ls():
    """
    Return the first selected.

    Author: Sean
    """
    sels = hou.selectedItems()
    if sels:
        return sels[0]
Exemple #6
0
    def commit_conversions(self):

        # Find all boxes that have nodes that were made by the conversion script
        boxes = []
        for item in hou.selectedItems():
            if not isinstance(item, hou.NetworkBox):
                continue

            # If the box doesn't have two nodes in it, it's definitely not ours
            nodes = item.nodes()
            if len(nodes) != 2:
                continue

            # If neither is named _new and/or neither is named _old, it's not one of ours
            if not "_new" in nodes[0].name() and not "_new" in nodes[1].name():
                continue
            if not "_old" in nodes[0].name() and not "_old" in nodes[1].name():
                continue

            # If the assets are not named the same, it's not one of ours
            print nodes[0].name()[:-4]
            print nodes[1].name()[:-4]

            if nodes[0].name()[:-4] != nodes[1].name()[:-4]:
                continue

            # If it passed the tests, add it to the list of network boxes we can work with
            boxes.append(item)

        print boxes

        # Don't go on unless there's a valid network box
        if len(boxes) < 1:
            qd.error(
                "There aren't any network boxes created by the conversion script."
            )
            return

        for box in boxes:
            old_node = next(
                (node for node in box.nodes() if "_old" in node.name()), None)
            new_node = next(
                (node for node in box.nodes() if "_new" in node.name()), None)

            old_hda = old_node.type().definition()
            old_hda.setIcon(Environment().get_project_dir() +
                            '/pipe/tools/_resources/1.png')

            publish.non_gui_publish_go(old_node, "Converted to V2")
            for child in new_node.allSubChildren():
                if "_material" in child.type().name(
                ) or "_modify" in child.type().name():
                    publish.non_gui_publish_go(child, "Converted from V1")
Exemple #7
0
def drag(include_ancestors=False, dx=0, dy=0):
    items = set(hou.selectedItems())
    if include_ancestors:
        ancestors = set()
        for node in items:
            ancestors = ancestors.union(set(node.inputAncestors()))
        items = items.union(ancestors)

    with hou.undos.group("Move nodes"):
        for selected in items:
            position = selected.position()
            position += hou.Vector2(dx, dy)
            selected.setPosition(position)
Exemple #8
0
 def load_asset_in_houdini(self, file_path):
     try:
         hou.clearAllSelected()
         self.pwd_for_load_nodes.loadItemsFromFile(file_path, True)
         with hou.undos.disabler():
             self.move_nodes_to_clicked_position(hou.selectedItems(),
                                                 self.pos_for_load_nodes)
     except hou.PermissionError as e:
         HaocUtils.show_message_box(self, e.instanceMessage())
     except hou.OperationFailed as e:
         HaocUtils.show_message_box(self, e.description())
         # If load failed it can be the asset damaged, so make it size 0 for nex time download
         open(file_path, 'w').close()
     except hou.LoadWarning as e:
         print e.description()
		def _replaceContent(self, index):
			try:
				nodes = hou.selectedItems()
			except:
				nodes = hou.selectedNodes()
			if (len(nodes)==0):
				QMessageBox.warning(self,'cannot replace','selection is empty')
				return
			item=index.internalPointer()
			good = QMessageBox.warning(self,'sure?','confirm that you want to replace the content of selected item "%s". This operation can not be undone.'%item.name() ,QMessageBox.Ok|QMessageBox.Cancel) == QMessageBox.Ok
			if(not good):return
			try:
				item.setContent(hpaste.nodesToString(nodes))
			except CollectionSyncError as e:
				QMessageBox.critical(self,'something went wrong!','Server error occured: %s'%e.message)
Exemple #10
0
def add_to_selection(nodes, kwargs, selectMode=None):
    """Extends the current node selection with 'nodes', according to
    the modifier keys in kwargs.

    no modifier:    replace selection
    shift, alt:     add to selection
    ctrl:           remove from selection
    ctrl+shift:     intersect with selection
    """
    assert selectMode is None or type(selectMode) is str

    haz_shift = kwargs["shiftclick"] or kwargs['altclick']
    haz_ctrl = kwargs["ctrlclick"]

    if selectMode is None:
        # determine select mode based on kwargs
        if haz_shift or haz_ctrl:
            # we got some modifier pressed
            if haz_shift:
                # shift: add (union), shift+ctrl: intersect
                selectMode = "intersect" if haz_ctrl else "add"
            else:
                # ctrl: remove from selection
                selectMode = "remove"
    else:
        selectMode = selectMode.lower()

    current = set(hou.selectedItems())
    sel = set(nodes)
    sel_length_old = len(sel)

    if selectMode == "intersect":
        sel = sel.intersection(current)
    elif selectMode == "add":
        sel = sel.union(current)
    elif selectMode == "remove":
        sel = current.difference(sel)
    else:
        selectMode = "replace"

    if sel is not None:
        hou.clearAllSelected()
        for n in sel:
            n.setSelected(True)

    # report back
    statmsg("Select (%s) %d nodes: Now %d selected (was %d)" % \
        (selectMode.capitalize(), sel_length_old, len(sel), len(current), ) )
Exemple #11
0
    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.MouseButtonPress:
            if event.button() != QtCore.Qt.MouseButton.MidButton:
                return False
            if HaocEventF.pop is not None:
                if HaocEventF.pop.isVisible():
                    return False
            if HaocEventF.is_control_hold and HaocEventF.is_shift_hold:
                pane_tab = hou.ui.curDesktop().paneTabUnderCursor()
                if pane_tab is not None:
                    if pane_tab.type() == hou.paneTabType.NetworkEditor:
                        if HaocEventF.pop is None:
                            HaocEventF.pop = Popup.PopWidget()
                            HaocEventF.pop.setStyleSheet(hou.qt.styleSheet())

                        main_window_rec = hou.ui.mainQtWindow().geometry()
                        des_pos = QtCore.QPoint()
                        delta_x = main_window_rec.width() - event.pos().x()
                        delta_y = main_window_rec.height() - event.pos().y()
                        if delta_x < HaocEventF.pop.size().width():
                            des_pos.setX(event.pos().x() -
                                         HaocEventF.pop.size().width())
                        else:
                            des_pos.setX(event.pos().x())
                        if delta_y < HaocEventF.pop.size().height():
                            des_pos.setY(main_window_rec.height() -
                                         HaocEventF.pop.size().height())
                        else:
                            des_pos.setY(event.pos().y())

                        HaocEventF.pop.move(
                            hou.ui.mainQtWindow().mapToGlobal(des_pos))
                        HaocEventF.pop.show_pop(pane_tab,
                                                len(hou.selectedItems()) > 0)
        if event.type() == QtCore.QEvent.KeyPress:
            if event.key() == QtCore.Qt.Key_Control:
                HaocEventF.is_control_hold = True
            if event.key() == QtCore.Qt.Key_Shift:
                HaocEventF.is_shift_hold = True
        if event.type() == QtCore.QEvent.KeyRelease:
            if event.key() == QtCore.Qt.Key_Control:
                HaocEventF.is_control_hold = False
            if event.key() == QtCore.Qt.Key_Shift:
                HaocEventF.is_shift_hold = False
        return QtCore.QObject.eventFilter(self, obj, event)
        def _addItem(self, collection):
            # Please, dont throw from here!
            try:
                nodes = hou.selectedItems()
            except:
                nodes = hou.selectedNodes()
            if len(nodes) == 0:
                QMessageBox.warning(self, 'not created',
                                    'selection is empty, nothing to add')
                return

            while True:
                # btn,(name,desc) = (0,('1','2'))#hou.ui.readMultiInput('enter some information about new item',('name','description'),buttons=('Ok','Cancel'))
                name, desc, public, good = QDoubleInputDialog.getDoubleTextCheckbox(
                    self, 'adding a new item to %s' % collection.name(),
                    'enter new item details', 'name', 'description', 'public',
                    '', 'a snippet', False)
                if not good:
                    return

                if len(name) > 0:
                    break
                    # validity check

            try:
                # print(name)
                # print(desc)
                # print(hpaste.nodesToString(nodes))
                self.model().addItemToCollection(
                    collection,
                    name,
                    desc,
                    hpaste.nodesToString(nodes),
                    public,
                    metadata={'nettype': self.__netType})
            except CollectionSyncError as e:
                QMessageBox.critical(self, 'something went wrong!',
                                     'Server error occured: %s' % str(e))
Exemple #13
0
def createDepsys(context):
    """
    This Fincton is Auto Setup DependencyROP

    Samples**
    createDepsys('obj'):
    -context-
    >>obj
    >>shop
    """

    global roothierarchy

    rootdephierarchy = roothierarchy + str(context)

    if context == 'out':
        depRop = hou.node(rootdephierarchy)

    if context == 'obj':
        depRop = hou.node(rootdephierarchy)

        if depRop.recursiveGlob('Dep_ROP') == ():

            objRop = depRop.createNode('ropnet', 'Dep_ROP')
            objRop.setColor(hou.Color((0.8, 0.4, 0.3)))
            objRop.moveToGoodPosition()

    if context == 'shop':
        depRop = hou.node(rootdephierarchy)

        if depRop.recursiveGlob('Dep_ROP') == ():

            ShopRop = depRop.createNode('ropnet', 'Dep_ROP')
            ShopRop.moveToGoodPosition()
            ShopRop.setColor(hou.Color((0.3, 0.4, 0.8)))

    #=== Send currentNode Dep_Rop
    currentDep = hou.node(roothierarchy).recursiveGlob('Dep_ROP')[0].path()

    try:  #version 15 is not hou.selectedItems
        getcurrentnode = hou.selectedItems()

    except TypeError:
        getcurrentnode = hou.selectedNodes()

    except AttributeError:
        getcurrentnode = hou.selectedNodes()

    ropDepNode = hou.node(currentDep)

    timevariables = dict(pstart=hou.getenv("PSTART"), pend=hou.getenv("PEND"))
    dependency_Name = "_Dependency_Cache"

    for current in getcurrentnode:

        current_dict = dict(name=str(current.name()),
                            path=(str(current.path())))

        if ropDepNode.recursiveGlob(current_dict["name"] +
                                    dependency_Name) == ():
            depJobNode = ropDepNode.createNode('geometry')
            depJobNode.moveToGoodPosition()
            depJobNode.setColor(hou.Color((0.3, 0.7, 0.2)))

            depJobNode.setName(current_dict["name"] + dependency_Name)
            #=== PPI Setting ===#

            try:
                submitNode = depJobNode.createOutputNode(
                    "submitDeadlineHoudini")
                submitNode.move([0, -0.8])

                submitNode.setParms({'framesPerTask': 100000})
                ##submit for Auto
                submitNode.parm('submit').pressButton()

            except:
                pass

            #reratuvePath_for_nullSop
            rerativePath = hou.node(current_dict["path"])
            AnkerName = "_Cache_Dep_Marker"
            if rerativePath.recursiveGlob(current_dict["name"]) == ():
                rerativeNode = rerativePath.createOutputNode(
                    'null', current_dict["name"] + AnkerName)
                rerativeNode.setColor(hou.Color((0.3, 0.1, 0.2)))
                rerativeNode.move([0.5, -0.3])

                cacheNode = rerativeNode.createOutputNode(
                    'filecache', depJobNode.name())
                cacheNode.setParms({'loadfromdisk': 1})
                cacheNode.move([0, -0.3])

                depEndNode = cacheNode.createOutputNode(
                    'null', "out_Dependenciy_tree")
                depEndNode.setColor(hou.Color((0.3, 0.1, 0.2)))
                depEndNode.move([0, -0.5])
                depEndNode.setDisplayFlag(1)
                depEndNode.setRenderFlag(1)

                ##Map for Dep reraative Node
                depJobNode.setParms({'soppath': rerativeNode.path()})
 def _getSelection(self):
     return hou.selectedItems()
def getSelectedItems():
    for sel in hou.selectedItems():
        return sel
    def createPreview(self, *args, **kwargs):
        """Creates a Playblast preview from currently open scene"""
        logger.debug("Func: createPreview")



        #
        pbSettings = self.loadPBSettings()
        # validFormats = cmds.playblast(format=True, q=True)
        # validCodecs = cmds.playblast(c=True, q=True)
        #
        # if not pbSettings["Format"] in validFormats:
        #     msg = ("Format specified in project settings is not supported. Install {0}".format(pbSettings["Format"]))
        #     cmds.warning(msg)
        #     return -1, msg
        #
        # if not pbSettings["Codec"] in validCodecs:
        #     msg = ("Codec specified in project settings is not supported. Install {0}".format(pbSettings["Codec"]))
        #     cmds.warning(msg)
        #     return -1, msg
        #
        extension = "jpg"

        openSceneInfo = self.getOpenSceneInfo()
        if not openSceneInfo:
            msg = "This is not a base scene. Scene must be saved as a base scene before playblasting."
            self._exception(360, msg)
            return

        selection = hou.selectedItems()
        hou.clearAllSelected()
        jsonInfo = self._loadJson(openSceneInfo["jsonFile"])
        #

        scene_view = toolutils.sceneViewer()
        viewport = scene_view.curViewport()
        cam = viewport.camera()
        if cam:
            currentCam = cam.name()
        else:
            currentCam = 'persp'

        flip_options = scene_view.flipbookSettings().stash()

        # flip_options.output("E:\\test\\{0}_$F4.{1}".format(camName, "tga"))
        # flip_options.useResolution(True)
        # flip_options.resolution((221, 124))
        # scene_view.flipbook(viewport, flip_options)


        versionName = self.getSceneFile()
        relVersionName = os.path.relpath(versionName, start=openSceneInfo["projectPath"])
        playBlastDir = os.path.join(openSceneInfo["previewPath"], openSceneInfo["version"])
        self._folderCheck(playBlastDir)
        playBlastFile = os.path.join(playBlastDir, "{0}_{1}_PB_$F4.{2}".format(self.niceName(versionName), currentCam, extension))
        relPlayBlastFile = os.path.relpath(playBlastFile, start=openSceneInfo["projectPath"])
        #
        if os.path.isfile(playBlastFile):
            try:
                os.remove(playBlastFile)
            except WindowsError:
                msg = "The file is open somewhere else"
                self._exception(202, msg)
                return

        flip_options.output(playBlastFile)
        #
        # ## CREATE A CUSTOM PANEL WITH DESIRED SETTINGS
        #
        # tempWindow = cmds.window(title="SM_Playblast",
        #                        widthHeight=(pbSettings["Resolution"][0] * 1.1, pbSettings["Resolution"][1] * 1.1),
        #                        tlc=(0, 0))
        # # panel = pm.getPanel(wf=True)
        #
        # cmds.paneLayout()
        #
        # pbPanel = cmds.modelPanel(camera=currentCam)
        # cmds.showWindow(tempWindow)
        # cmds.setFocus(pbPanel)
        #
        # cmds.modelEditor(pbPanel, e=1,
        #                allObjects=not pbSettings["PolygonOnly"],
        #                da="smoothShaded",
        #                displayTextures=pbSettings["DisplayTextures"],
        #                wireframeOnShaded=pbSettings["WireOnShaded"],
        #                grid=pbSettings["ShowGrid"],
        #                useDefaultMaterial=pbSettings["UseDefaultMaterial"],
        #                polymeshes=True,
        #                imagePlane=True,
        #                hud=True
        #                )
        #
        # cmds.camera(currentCam, e=True, overscan=True, displayFilmGate=False, displayResolution=False)
        #
        # ## get previous HUD States and turn them all off
        # hudPreStates = {}
        # HUDS = cmds.headsUpDisplay(lh=True)
        # for hud in HUDS:
        #     hudPreStates[hud] = cmds.headsUpDisplay(hud, q=True, vis=True)
        #     cmds.headsUpDisplay(hud, e=True, vis=False)
        #
        # ## clear the custom HUDS
        # customHuds = ['SMFrame', 'SMScene', 'SMCategory', 'SMFPS', 'SMCameraName', 'SMFrange']
        # for hud in customHuds:
        #     if cmds.headsUpDisplay(hud, ex=True):
        #         cmds.headsUpDisplay(hud, rem=True)
        #
        # if pbSettings["ShowFrameNumber"]:
        #     freeBl = cmds.headsUpDisplay(nfb=5)  ## this is the next free block on section 5
        #     cmds.headsUpDisplay('SMFrame', s=5, b=freeBl, label="Frame", preset="currentFrame", dfs="large",
        #                       lfs="large")
        # if pbSettings["ShowSceneName"]:
        #     freeBl = cmds.headsUpDisplay(nfb=5)  ## this is the next free block on section 5
        #     cmds.headsUpDisplay('SMScene', s=5, b=freeBl, label="Scene: %s" % (self.niceName(versionName)),
        #                       lfs="large")
        # if pbSettings["ShowCategory"]:
        #     freeBl = cmds.headsUpDisplay(nfb=5)  ## this is the next free block on section 5
        #     cmds.headsUpDisplay('SMCategory', s=5, b=freeBl, label="Category: %s" % (jsonInfo["Category"]),
        #                       lfs="large")
        # if pbSettings["ShowFPS"]:
        #     freeBl = cmds.headsUpDisplay(nfb=5)  ## this is the next free block on section 5
        #     cmds.headsUpDisplay('SMFPS', s=5, b=freeBl, label="Time Unit: %s" % (cmds.currentUnit(q=True, time=True)),
        #                       lfs="large")
        #
        # # v1.1 SPECIFIC
        # try:
        #     if pbSettings["ShowFrameRange"]:
        #         freeBl = cmds.headsUpDisplay(nfb=5)  ## this is the next free block on section 5
        #         cmds.headsUpDisplay('SMFrange', s=5, b=freeBl,
        #                           label="Frame Range: {} - {}".format(int(cmds.playbackOptions(q=True, minTime=True)),
        #                                                               int(cmds.playbackOptions(q=True,
        #                                                                                      maxTime=True))),
        #                           lfs="large")
        # except KeyError:
        #     pass
        #
        # freeBl = cmds.headsUpDisplay(nfb=2)
        # cmds.headsUpDisplay('SMCameraName', s=2, b=freeBl, ba='center', dw=50, pre='cameraNames')
        #
        # ## Get the active sound
        #
        # aPlayBackSliderPython = mel.eval('$tmpVar=$gPlayBackSlider')
        # activeSound = cmds.timeControl(aPlayBackSliderPython, q=True, sound=True)
        #
        # ## Check here: http://download.autodesk.com/us/maya/2011help/pymel/generated/functions/pymel.core.windows/pymel.core.windows.headsUpDisplay.html
        # # print "playBlastFile", playBlastFile
        # normPB = os.path.normpath(playBlastFile)
        # # print "normPath", normPB
        ranges = self._getTimelineRanges()
        flip_options.frameRange((ranges[1], ranges[2]))
        flip_options.outputToMPlay(True)
        flip_options.useResolution(True)
        flip_options.resolution((pbSettings["Resolution"][0], pbSettings["Resolution"][1]))
        scene_view.flipbook(viewport, flip_options)


        # cmds.playblast(format=pbSettings["Format"],
        #              filename=playBlastFile,
        #              widthHeight=pbSettings["Resolution"],
        #              percent=pbSettings["Percent"],
        #              quality=pbSettings["Quality"],
        #              compression=pbSettings["Codec"],
        #              sound=activeSound,
        #              uts=True)
        # ## remove window when pb is donw
        # cmds.deleteUI(tempWindow)
        #
        # # Get back to the original frame range if the codec is Quick Time
        # if pbSettings["Format"] == 'qt':
        #     cmds.playbackOptions(maxTime=maxTime)
        #     cmds.playbackOptions(animationEndTime=endTime)
        #
        # ## remove the custom HUdS
        # if pbSettings["ShowFrameNumber"]:
        #     cmds.headsUpDisplay('SMFrame', rem=True)
        # if pbSettings["ShowSceneName"]:
        #     cmds.headsUpDisplay('SMScene', rem=True)
        # if pbSettings["ShowCategory"]:
        #     cmds.headsUpDisplay('SMCategory', rem=True)
        # if pbSettings["ShowFPS"]:
        #     cmds.headsUpDisplay('SMFPS', rem=True)
        # try:
        #     if pbSettings["ShowFrameRange"]:
        #         cmds.headsUpDisplay('SMFrange', rem=True)
        # except KeyError:
        #     pass
        #
        #     cmds.headsUpDisplay('SMCameraName', rem=True)
        #
        # ## get back the previous state of HUDS
        # for hud in hudPreStates.keys():
        #     cmds.headsUpDisplay(hud, e=True, vis=hudPreStates[hud])
        # pm.select(selection)

        ## find this version in the json data
        for version in jsonInfo["Versions"]:
            if relVersionName == version["RelativePath"]:
                # replace the houdini variable with first frame
                nonVarPBfile = relPlayBlastFile.replace("_$F4", "_0001")
                # version["Preview"][currentCam] = nonVarPBfile
                version["Preview"][currentCam] = relPlayBlastFile

        self._dumpJson(jsonInfo, openSceneInfo["jsonFile"])
def MotionTrail():
    """
    This func isThis func is SOPLevel Script
    Create Motion Trail Base System

    Samples***
    selcted Current Nodetree
    MotionTrail()
    """
    import hou

    #Create Path
    select = hou.selectedItems()
    node_Path = str(select[0].path())

    root = hou.node(node_Path)

    #============ Motion Trail Bigin ==============#
    #Bigin_Sop Tree
    bigin_null = root.createOutputNode("null", "MotionTrail")

    bigin_null.move([0, -1])
    bigin_null.setColor(hou.Color((0.5, 0.4, 0.0)))

    #TimeShiftSop
    timeShiftSop = bigin_null.createOutputNode("timeshift")
    timeShiftSop.move([-2, -0.3])
    timeShiftSop.setParmExpressions({"frame": '101'})

    #ScatterSop
    ScatterSop = timeShiftSop.createOutputNode("scatter")
    ScatterSop.move([0, -0.2])
    ScatterSop.setParmExpressions({
        "npts": "500",
        "relaxpoints": '0',
        "useprimnumattrib": "1",
        "useprimuvwattrib": "1"
    })

    #InterPolateSop
    InterPolateSop = ScatterSop.createOutputNode("attribinterpolate")
    InterPolateSop.move([1.8, -0.3])
    InterPolateSop.setInput(1, bigin_null)

    #WrangleSop
    WrangleSop = InterPolateSop.createOutputNode("attribwrangle", "Set_id")
    WrangleSop.move([0.3, -0.4])
    WrangleSop.setParms({'snippet': 'i@id = @ptnum;'})

    #trailvelSop
    TrailvelSop = WrangleSop.createOutputNode("trail", "set_velocity")
    TrailvelSop.move([0, -0.3])
    TrailvelSop.setParmExpressions({'result': '3', 'computeangular': '1'})

    #trailSop
    TrailSop = TrailvelSop.createOutputNode("trail", "set_Trail")
    TrailSop.move([0, -0.3])
    TrailSop.setParmExpressions({'result': '0', 'length': '10'})
    TrailSop.setColor(hou.Color((0.7, 0, 0.4)))

    #addSop
    AddSop = TrailSop.createOutputNode("add", 'Conect_Pts')
    AddSop.move([0, -0.3])
    Parm = AddSop.parm('add').set(4)

    AddSop.setParms({'attrname': 'id'})
    ParmRadio = AddSop.setParms({'stdswitcher1': '1', 'switcher1': '1'})
    #temp = AddSop.asCode()

    #resampleSop
    ResampleSop = AddSop.createOutputNode("resample")
    ResampleSop.move([0, -0.3])
    ResampleSop.setParms({'length': '0.05'})

    #Endnull
    EndnullSop = ResampleSop.createOutputNode("null", "Motion_Trail_OUT")
    EndnullSop.move([0, -0.3])
    EndnullSop.setColor(hou.Color((0.5, 0.4, 0.0)))

    #FileCacheSop
    FileCache = EndnullSop.createOutputNode("filecache",
                                            "Source_MotionTrail_Cache")
    FileCache.move([1.5, -0.4])
    FileCache.setParms({'loadfromdisk': '1'})
    FileCache.setParmExpressions({'f1': '$PSTART-15', 'f2': '$PEND+2'})
    #===Flag===#
    FileCache.setRenderFlag(1)
    FileCache.setDisplayFlag(1)
    FileCache.setCurrent(1, 1)
    #===event===#
    #Post_Select = hou.selectedItems()
    #Post_Path  = str(Post_Select[0].path())

    #EventNode = hou.node(Post_Path)
    #EventNode.parm("execute").pressButton()

    del hou
def Assenble_bgeo():
    """
    This fuc is
    Selected Alembic objects Convert_HoudiniGeometry& write_bgeoFile

    Samples***
    selcted obj alembicNode...
    Assenble_bgeo()
    """

    import hou
    import dep_system

    select = hou.selectedItems()
    root = hou.node("/obj")

    for shapenode in select:

        Nodepath = str(shapenode.path())

        alembicNode = hou.node(Nodepath)

        Child = alembicNode.children()
        Child_Path = str(Child[0].path())

        #====== Create CahceAssembles======#
        Cache_AssembleNode = root.createNode("geo", None, 0)
        Cache_AssembleNode.setName(str(Child[0]) + '_bgeo')
        Cache_AssembleNode.setColor(hou.Color((0.3, 0.4, 0.3)))
        Cache_AssembleNode.moveToGoodPosition()

        Assemble_root = hou.node(Cache_AssembleNode.path())

        #objectMergeSop
        objmergeSop = Assemble_root.createNode('object_merge')
        objmergeSop.setName('Import_' + str(Child[0]) + '_ABC')
        objmergeSop.setParms({'objpath1': Child_Path, 'xformtype': 1})
        objmergeSop.setColor(hou.Color((0.7, 0, 0.4)))

        #PythonSOP
        PythonSop = objmergeSop.createOutputNode('python', 'Unpacking_process')
        PythonSop.move([0.3, -0.3])
        PythonSop.parm('python').set(
            "node = hou.pwd()\ngeo = node.geometry()\nresultgeo = hou.Geometry()\
                                      \n\nsops = hou.sopNodeTypeCategory()\n#unpack\n\nunpack_py = sops.nodeVerb('unpack')\
                                      \nunpack_py.setParms({'transfer_attributes': 'path'})\nunpack_py.execute(geo,[geo])\
                                      \n\n#reconvert_ShapeName\nfor prim in geo.iterPrims():\n    path = prim.attribValue('path')\
                                      \n    shape = path.split('/')[-1]\n\n    prim.setAttribValue('path',shape)\n\n#normal\
                                      \nnormal_py = sops.nodeVerb('normal')\nnormal_py.execute(resultgeo,[geo])\n\n\
                                      \nnode.geometry().clear()\nnode.geometry().merge(resultgeo)"
        )
        #nullSop
        EndnullSop = PythonSop.createOutputNode('null')
        EndnullSop.setName("unpacking_" + str(Child[0]) + "_OUT")
        EndnullSop.move([0, -0.3])
        EndnullSop.setColor(hou.Color((0.5, 0.4, 0.0)))
        EndnullSop.setCurrent(1, 1)
        EndnullSop.setDisplayFlag(1)
        EndnullSop.setRenderFlag(1)

        dep_system.createDepsys("obj")
def CvtFillVolume():
    """
    This func is SOPLevel Script
    Create Convert Line VolumeTool

    Samples***
    selcted Current Nodetree
    CvtFillVolume()
    """
    import hou

    #Create Path
    select = hou.selectedItems()
    node_Path = str(select[0].path())

    root = hou.node(node_Path)

    #============ Motion Trail Bigin ==============#
    #Bigin_Sop Tree
    bigin_null = root.createOutputNode("null", "ConvertFillCurve")

    bigin_null.move([0, -1])
    bigin_null.setColor(hou.Color((0.5, 0.4, 0.0)))

    #=== for loop Start ===#

    #forLoop_Sop_bigin Tree
    loop_beginSop = bigin_null.createOutputNode("block_begin", "foreach_bigin")
    loop_beginSop.move([-1, -0.5])
    loop_beginSop.setParms({'method': 1, 'blockpath': '../block_end'})
    Meta = loop_beginSop.parm('createmetablock').pressButton()

    #CarveSop_Tree
    CarveSop = loop_beginSop.createOutputNode("carve", "carve")
    CarveSop.move([0, -0.2])
    CarveSop.setParms({"firstu": 0, "secondu": 1})

    #resampleSop_tree
    ResampleSop = CarveSop.createOutputNode("resample", "resample")
    ResampleSop.setParms({'dolength': 0, 'dosegs': 1, 'segs': '1000'})
    ResampleSop.move([0, -0.2])
    #ResampleSop.setParms({"docurveuattr":0})

    #forLoop_Sop_end Tree
    loopendSop = ResampleSop.createOutputNode("block_end", "block_end")
    loopendSop.move([0, -0.2])
    loopendSop.setParms({
        'itermethod': 1,
        'method': 1,
        'class': 0,
        'useattrib': 0
    })
    loopendSop.setParms({
        'blockpath': "../foreach_bigin",
        'templatepath': "../foreach_bigin"
    })

    #WrangleSop tree
    WrangleSop = loopendSop.createOutputNode("attribwrangle", "rastaring")
    WrangleSop.move([0.3, -0.7])

    WranglePram = WrangleSop.parm("snippet")
    WranglePram.set(
        'float curve = chramp("curve",@curveu);\n\n@pscale = curve*0.035;\n\
                    \n@density = fit(rand(@primnum),0,1,0.5,1);')

    #VDBSOP
    VDBSop = WrangleSop.createOutputNode("vdb", "VDB")
    VDBSop.move([-2.5, 0.5])
    VDBSop.setInput(0, None)  #DisConenct

    VDBSop.setParms({'name1': 'density', 'voxelsize': '0.01'})

    #rastaraiseSop tree
    rasterizeSop = WrangleSop.createOutputNode('volumerasterizeparticles',
                                               'Rerasterize_point')
    rasterizeSop.move([-1.5, -0.5])
    rasterizeSop.setInput(0, VDBSop)
    rasterizeSop.setInput(1, WrangleSop)

    #End NullSop tree

    EndNullSop = rasterizeSop.createOutputNode("null", "ConvertFillCurve_End")
    EndNullSop.move([0, -0.5])
    EndNullSop.setColor(hou.Color((0.5, 0.4, 0.0)))

    #FileCacheSop
    FileCache = EndNullSop.createOutputNode("filecache", "FillVolume_Cache")
    FileCache.move([0, -0.4])
    FileCache.setParms({'loadfromdisk': '1'})
    FileCache.setParmExpressions({'f1': '$PSTART-15', 'f2': '$PEND+2'})
    #===Flag===#
    FileCache.setRenderFlag(1)
    FileCache.setDisplayFlag(1)
    FileCache.setCurrent(1, 1)

    del hou
 def get_sel(self):
     '''
     :return: string:: the path of selected node in houdini eg: '/obj/Ship1/Portuguese_ship_001'
     '''
     return hou.selectedItems()[0].path()
Exemple #21
0
 def __get_selected_node(self):
     nds = hou.selectedItems()
     if nds:
         return nds[0].path()
     return ""
Exemple #22
0
    hou.parm(light_blocker.path()+'/geometry_matrix1').setExpression('ch("../../../sx")*(cos(ch("../../../ry"))*cos(ch("../../../rz")))')
    hou.parm(light_blocker.path()+'/geometry_matrix2').setExpression('ch("../../../sx")*(cos(ch("../../../ry"))*sin(ch("../../../rz")))')
    hou.parm(light_blocker.path()+'/geometry_matrix3').setExpression('-ch("../../../sx")*(sin(ch("../../../ry")))')
    hou.parm(light_blocker.path()+'/geometry_matrix5').setExpression('(-ch("../../../sy")*(cos(ch("../../../rx"))*sin(ch("../../../rz"))))+(ch("../../../sy")*(sin(ch("../../../rx"))*sin(ch("../../../ry"))*cos(ch("../../../rz"))))')
    hou.parm(light_blocker.path()+'/geometry_matrix6').setExpression('(ch("../../../sy")*(cos(ch("../../../rx"))*cos(ch("../../../rz"))))+(ch("../../../sy")*(sin(ch("../../../rx"))*sin(ch("../../../ry"))*sin(ch("../../../rz"))))')
    hou.parm(light_blocker.path()+'/geometry_matrix7').setExpression('ch("../../../sy")*(sin(ch("../../../rx"))*cos(ch("../../../ry")))')
    hou.parm(light_blocker.path()+'/geometry_matrix9').setExpression('(ch("../../../sz")*(sin(ch("../../../rx"))*sin(ch("../../../rz"))))+(ch("../../../sz")*(cos(ch("../../../rx"))*sin(ch("../../../ry"))*cos(ch("../../../rz"))))')
    hou.parm(light_blocker.path()+'/geometry_matrix10').setExpression('(-ch("../../../sz")*(sin(ch("../../../rx"))*cos(ch("../../../rz"))))+(ch("../../../sz")*(cos(ch("../../../rx"))*sin(ch("../../../ry"))*sin(ch("../../../rz"))))')
    hou.parm(light_blocker.path()+'/geometry_matrix11').setExpression('ch("../../../sz")*(cos(ch("../../../rx"))*cos(ch("../../../ry")))')
    hou.parm(light_blocker.path()+'/geometry_matrix13').setExpression('ch("../../../tx")')
    hou.parm(light_blocker.path()+'/geometry_matrix14').setExpression('ch("../../../ty")')
    hou.parm(light_blocker.path()+'/geometry_matrix15').setExpression('ch("../../../tz")')
        
obj = hou.node('/obj')

selection = hou.selectedItems()

arnold_lights = []

for light in selection:
    if light.type().name() == "arnold_light":
        arnold_lights.append(light)
        
light_blocker_transform_nodes = []

hou.Node.setSelected(obj, False, clear_all_selected=True)

if len(arnold_lights) == 0:
    light_blocker_transform("light_blocker_transform1")
    hou.Node.setSelected(light_blocker_transform.subnet, True)
else:
Exemple #23
0
    def save_nodes(self):
        input_name = self.asset_name.text().strip()
        if len(input_name) < 3:
            QtWidgets.QMessageBox.warning(
                hou.qt.mainWindow(), "Input Error",
                "The number of letters of Asset name must at least have 3")
            return
        input_error = HaocUtils.check_name_ok(input_name)
        if input_error != '':
            QtWidgets.QMessageBox.warning(
                hou.qt.mainWindow(), "Input Error",
                "File name is not up to standard,please remove the stuff below from your input:\n%s"
                % input_error)
            return

        selected_path = ""
        index = self.tree_view.currentIndex()
        index = self.sort_filter.mapToSource(index)
        selected_item = self.sort_filter.sourceModel().itemFromIndex(index)
        if selected_item:
            selected_path = PopWidget.get_selected_folder(selected_item)
        asset_upload_path = selected_path + input_name
        parent = hou.selectedItems()[0].parent()
        cat_name = parent.childTypeCategory().name()
        local_path = '%s/data/%s/nodes/%s/%s' % (HaocUtils.get_root_path(),
                                                 HaocUtils.Config.get_ak(),
                                                 cat_name, asset_upload_path)
        cloud_path = '%s/%s' % (cat_name, asset_upload_path)

        if input_name[-1] == "/":
            if not os.path.exists(local_path):
                os.makedirs(local_path)
        else:
            if os.path.exists("%s.nod" % local_path):
                button_code = HaocUtils.show_question_box(
                    self,
                    "This asset is already exist,do you want to replace it?")
                if button_code != QtWidgets.QMessageBox.Yes:
                    return

            # Check for SopNode HardLocked status
            if len(hou.selectedNodes()) > 1:
                locked_nodes = []
                if self.network_editor.pwd().childTypeCategory(
                ) == hou.sopNodeTypeCategory():
                    for node in hou.selectedNodes():
                        if isinstance(node,
                                      hou.SopNode) and node.isHardLocked():
                            locked_nodes.append(node)
                if len(locked_nodes) > 0:
                    text = "Detected these selected nodes have had HardLocked,thus will cause asset become large, " \
                        "do you want to unlock those nodes?\n%s" % "\n".join([x.name() for x in locked_nodes])
                    button_code = HaocUtils.show_question_box(self, text)
                    if button_code == QtWidgets.QMessageBox.Cancel:
                        return
                    if button_code == QtWidgets.QMessageBox.Yes:
                        for node in locked_nodes:
                            node.setHardLocked(False)

            if not os.path.exists(os.path.dirname(local_path)):
                os.makedirs(os.path.dirname(local_path))
            parent.saveItemsToFile(hou.selectedItems(), "%s.nod" % local_path,
                                   self.hda_fall_backs.isChecked())
            if self.comments.toPlainText().strip() != '':
                with codecs.open("%s.hlp" % local_path, 'w',
                                 'utf-8') as comments_file:
                    comments_file.write(self.comments.toPlainText())

        # Put folder or file on cloud
        command = HaocObjects.CommandItem(1, path=cloud_path)
        commands_t = SCloudUtils.TDoCommands([command])
        commands_t.start()