コード例 #1
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        ui_file_path = "{0}/scripts/widgets/projectBrowser.ui".format(
            hou.expandString('$ALS'))
        loader = QUiLoader()
        self.widget = loader.load(ui_file_path)

        self.widget.jobField.setText(hou.expandString('$JOB'))
        self.widget.mjobField.setText(hou.expandString('$MJOB'))
        self.widget.hdataField.setText(hou.expandString('$HDATA'))
        self.widget.mcacheField.setText(hou.expandString('$MCACHE'))
        self.widget.mdataField.setText(hou.expandString('$MDATA'))
        self.widget.mscenesField.setText(hou.expandString('$MSCENES'))
        self.widget.flipField.setText(hou.expandString('$PLAY'))
        self.widget.rcField.setText(hou.expandString('$RCPATH'))
        self.widget.refField.setText(hou.expandString('$REFPATH'))

        self.widget.jobButton.clicked.connect(self._projDir)
        self.widget.mjobButton.clicked.connect(self._mprojDir)
        self.widget.hdataButton.clicked.connect(self._dataDir)
        self.widget.mdataButton.clicked.connect(self._mDataDir)
        self.widget.mcacheButton.clicked.connect(self._mCacheDir)
        self.widget.mscenesButton.clicked.connect(self._mScenesDir)
        self.widget.flipButton.clicked.connect(self._flipDir)
        self.widget.rcButton.clicked.connect(self._rcpathDir)
        self.widget.refButton.clicked.connect(self._referenceDir)
        self.widget.localDataButton.clicked.connect(self._dataLocalDir)
        self.widget.storageButton.clicked.connect(self._dataStorageDir)
        self.widget.sceneButton.clicked.connect(self._openScene)

        h = QHBoxLayout(self)
        h.setContentsMargins(0, 0, 0, 0)
        h.addWidget(self.widget)
        self.widget.setStyleSheet(hqt.get_h14_style())
コード例 #2
0
ファイル: PandoraSubmitter.py プロジェクト: luisfos/Pandora
	def houGetExternalFiles(self):
		hou.setFrame(hou.playbar.playbackRange()[0])
		whitelist = ['$HIP/$OS-bounce.rat', '$HIP/$OS-fill.rat', '$HIP/$OS-key.rat', '$HIP/$OS-rim.rat']
		houdeps = hou.fileReferences()
		extFiles = []
		extFilesSource = []
		for x in houdeps:
			if "/Redshift/Plugins/Houdini/" in x[1]:
				continue

			if x[0] is None:
				continue

			if x[1] in whitelist:
				continue

			if not os.path.isabs(hou.expandString(x[1])):
				continue

			if os.path.splitext(hou.expandString(x[1]))[1] == "":
				continue

			if x[0] is not None and x[0].name() in ["RS_outputFileNamePrefix", "vm_picture"]:
				continue

			if x[0] is not None and x[0].name() in ["filename", "dopoutput", "copoutput", "sopoutput"] and x[0].node().type().name() in ["rop_alembic", "rop_dop", "rop_comp", "rop_geometry"]:
				continue

			extFiles.append(hou.expandString(x[1]).replace("\\", "/"))
			extFilesSource.append(x[0])

		#return [extFiles, extFilesSource]
		return extFiles
コード例 #3
0
 def read_source_text(self):
     if self.file:
         if os.path.exists(hou.expandString(self.file)):
             text = open(hou.expandString(self.file)).read()
         else:
             hou.ui.displayMessage('File not found', buttons=(('OK',)),
                               severity=hou.severityType.Error,
                               default_choice=0,
                               title='Save VEX Code')
             self.set_empty()
             return
         self.set_text(text)
     elif self.parm:
         try:
             text = self.parm.unexpandedString()
         except:
             try:
                 text = self.parm.expression()
             except:
                 print "CANNOT READ PARAMETER"
                 return
         self.set_text(text)
     elif self.section:
         text = self.section.contents()
         self.set_text(text)
     else:
         pass
     self.save_current_declared_parms()
コード例 #4
0
 def read_source_text(self):
     if self.file:
         if os.path.exists(hou.expandString(self.file)):
             text = open(hou.expandString(self.file)).read()
         else:
             hou.ui.displayMessage('File not found', buttons=(('OK',)),
                               severity=hou.severityType.Error,
                               default_choice=0,
                               title='Save VEX Code')
             self.set_empty()
             return
         self.set_text(text)
     elif self.parm:
         try:
             text = self.parm.unexpandedString()
         except:
             try:
                 text = self.parm.expression()
             except:
                 print "CANNOT READ PARAMETER"
                 return
         self.set_text(text)
     elif self.section:
         text = self.section.contents()
         self.set_text(text)
     else:
         pass
     self.save_current_declared_parms()
コード例 #5
0
def execute(node):
    data = eval_node_parms(node)
    filepath = hou.hipFile.path()

    filename = hou.hipFile.basename()

    dir_path = os.path.splitext(data["cachedir"])[0].rsplit("/", 1)[0]

    if os.path.exists(hou.expandString(data["path"])) is False:
        os.makedirs(hou.expandString(data["path"]))
    dirs = os.listdir(hou.expandString(data["path"]))

    node.parm("description").set(data["description"])
    node.setUserData(data["fullpath"], data["description"])

    if dir_path not in data["tempdir"]:
        if len(dirs) != 0:
            hou.ui.displayMessage(
                "Detected the existence of files, replace them ?",
                buttons=("yes", "no"),
                severity=hou.severityType.Message)
            hou.hipFile.saveAsBackup()

            node.node("rop_geometry1").parm("execute").pressButton()
        else:
            hou.hipFile.saveAsBackup()

            node.node("rop_geometry1").parm("execute").pressButton()

    else:
        raise (hou.Error("This is tempfile, please set correct path"))
コード例 #6
0
def getOutputDir(choices=None):
    """
    Open a Houdini Dialog and return a path to the export directory.  Allows for
    either a list of choices to be displayed or a file select dialog.
    """

    if choices:
        c = hou.ui.selectFromList(choices,\
                                  exclusive = True,\
                                  title = 'Choose Directory',\
                                  num_visible_rows = 10)
        if not c:
            raise Exception("No Output Folder Selected. Exiting...")
        return hou.expandString(_interpretChoice(choices[c[0]]))
    else:
        outDir = ""
        while(not os.path.isdir(hou.expandString(outDir))):
            outDir = hou.ui.selectFile(start_directory = None,\
                                       title = "Select Output Folder",\
                                       collapse_sequences = False,\
                                       pattern = ('*'),\
                                       multiple_select = False,\
                                       chooser_mode = hou.fileChooserMode.Read)
            if outDir == '':
                return outDir
        return hou.expandString(outDir)
コード例 #7
0
    def run(self):
        print ''.join(['=' for i in range(100)])
        print '\nMove all losted files back to data filder:\n'
        for d in self.dirs:
            cd = d.replace('\\', '/')
            store = hou.expandString('$DATA_STORE')
            data = hou.expandString('$HDATA_GLOB')
            dataPath = cd.replace(store, data)
            print dataPath
            createPath(dataPath)
            for f in os.listdir(cd):
                self.update.emit()
                print 'repare: %s/%s' % (dataPath, f)
                shutil.move('%s/%s' % (cd, f), '%s/%s' % (dataPath, f))
            os.rmdir(cd)

        wdirs = []
        for w in self.wedges:
            self.update.emit()
            d = '/'.join(w.split('/')[:-1])
            name = w.split('/')[-1]
            dataPath = d.replace('data_store', 'data')
            if not d in wdirs:
                createPath(d)
            print 'repare: %s/%s' % (dataPath, name)
            shutil.move('%s/%s' % (d, name), '%s/%s' % (dataPath, name))
        for d in wdirs:
            if len(os.listdir(d)) == 0:
                print 'clean: %d' % d
                os.rmdir(d)
コード例 #8
0
 def _getJob(self, listNode):
     basename = hou.hipFile.path().split('/')[-1].replace('.hip', '')
     seq = hou.expandString('$SEQ')
     sh = hou.expandString('$SH')
     seq_sh = '{}_{}'.format(seq, sh) if seq != '' else ''
     base = '{}.{}'.format(seq_sh, basename) if seq_sh != '' else basename
     return '{}.{}'.format(base, listNode)
コード例 #9
0
ファイル: maya_import.py プロジェクト: all-in-one-of/ALS_lib
    def __init__(self, fromnode = True, parent = None) :
        super(maya_scene, self).__init__(parent)
        self.process_maya = None
        self.fromnode = fromnode

        self.node = None
        self.maya_env()

        self.scene = hou.expandString( "$PERFORCE" )
        try :
            self.scene = hou.pwd().parm("scene").eval()
        except:
            pass
            
        self.exportPath = hou.expandString( "$MDATA" )
        self.abc = "0"
        self.light = "1"
        self.cam = "1"
        self.start =  hou.expandString( "$RFSTART" )
        self.end   =  hou.expandString( "$RFEND" )

        self.mode    = "empty"
        self.abcFile = "empty"
        self.selstr  = "empty"
        self.smooth  = "empty"
        self.smoothIter = "empty"
        self.checkMblur = "empty"
        self.step = "empty"
        if fromnode :
            self.initNode()
コード例 #10
0
    def __init__(self, node):
        self.node = node
        self.rop = hou.node(node.parm("ropnode").eval())
        self.job = hou.expandString('$JOB')
        self.rcpath = hou.expandString('$RCPATH')
        self.seq = hou.expandString('$SEQ')
        self.sh = hou.expandString('$SH')
        self.hdata = hou.expandString('$HDATA').replace(
            LOCAL, HOUDINI_GLOB_PATH)

        self.simmode = node.parm('simmode').eval()
        self.distribute = node.parm('distribute').eval()
        self.distributemode = node.parm('distribmode').eval()
        self.distributeparts = node.parm('distribparts').eval()

        self.save = node.parm('save_scene').eval()
        self.new_ver = node.parm('increment').eval()
        self.submit = node.parm('submit').eval()
        self.wedge = node.parm('wedge').eval()
        self.cmd = node.parm('cmd').eval()
        self.comment = node.parm('comment').eval()
        self.tilescript = node.parm('tilescript').eval()
        self.seq_sh = "%s_%s" % (self.seq, self.sh) if self.seq != '' else ''
        self.hstart = '%s/scripts' % self.job

        self.hipName = hou.hipFile.name()
        self.hipBasename = hou.hipFile.basename().split(".hip")[0]
        self.taskName = "%s.%s" % ( self.seq_sh, self.hipBasename ) if self.seq_sh != ''\
                        else self.hipBasename

        self.prerender = self.node.parm('dopreren').eval()
コード例 #11
0
def processMesh(nodes, nodePieces, numPieces):
    PARMS = ["tx", "ty", "tz", "rx", "ry", "rz", "px", "py", "pz"]
    RFSTART = int(hou.expandString('$RFSTART'))
    RFEND = int(hou.expandString('$RFEND'))

    initialParmData = []

    #GET INITIAL TRANSFORMS
    hou.setFrame(frame)
    for objectToProcess in range(0, len(numPieces)):
        initialParmData.append(objectToProcess)

        for index in range(0, numPieces[objectToProcess]):
            initialParmData[objectToProcess].append(index)

            for index_parm in range(0, 3):
                #Get original tx,ty,tz
                initialParmData[objectToProcess][index].append(
                    nodes[objectToProcess].points()[index].attribValue(
                        'P')[index_parm])

            for index_parm in range(0, 3):
                #Get original rx,ry,rz
                initialParmData[objectToProcess][index].append(
                    nodes[objectToProcess].points()[index].attribValue(
                        'R')[index_parm])
コード例 #12
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        ui_file_path = "{0}/scripts/widgets/flipbook.ui".format(
            hou.expandString('$ALS'))
        loader = QUiLoader()
        self.widget = loader.load(ui_file_path)

        self.job = hou.expandString('$JOB')
        self.play = hou.expandString('$PLAY')
        self.seq = hou.expandString('$SEQ')
        self.sh = hou.expandString('$SH')
        self.width = 2048
        self.height = 858
        self.replace = 0

        h = QHBoxLayout(self)
        h.setContentsMargins(0, 0, 0, 0)
        h.addWidget(self.widget)
        self.widget.setStyleSheet(hqt.get_h14_style())

        # icon = QIcon()
        # icon.addPixmap(QPixmap("file.png"))
        # self.widget.getDirBtn.setIcon(icon)
        self.widget.getDirBtn.clicked.connect(self._getFlipPath)
        self.widget.flipbookButton.clicked.connect(self._flipWrite)
コード例 #13
0
 def variablesReload(self):
     self.projectLine.setText(hou.expandString("$PROJECT_NAME"))
     self.stepLine.setText(hou.expandString("$STEP"))        
     self.shotNameLine.setText(hou.expandString("$SHOT_NAME"))
     self.startNameLine.setText(hou.expandString("$START_FRAME"))
     self.endNameLine.setText(hou.expandString("$END_FRAME"))
     print"reload !"
コード例 #14
0
def openFile(node):
    parms_path = node.parm("sopoutput").eval()

    path = os.path.split(parms_path)[0]
    if os.path.exists(hou.expandString(path)) is True:
        os.startfile(hou.expandString(path))
    else:
        raise (hou.Error("can't find file path"))
コード例 #15
0
ファイル: PyTake2.py プロジェクト: GJpy/Houpy_PyTake2
    def __init__(self, name="pytake", parent="", set_to_current=False,
                 include_node=None, include_parm=None, _add_to_scene=True):
        
        if not hasattr(include_parm, "__iter__"):
            if include_parm is None:
                include_parm = []
            else:
                include_parm = [include_parm]

        if not hasattr(include_node, "__iter__"):
            if include_node is None:
                include_node = []
            else:
                include_node = [include_node]
            
        self.set_to_current = set_to_current
        self.take_members = {}
        
        # Construc take's name
        if _add_to_scene:
            self.name = _incName(_checkName(name))
        else:
            self.name = _checkName(name)
            
        # Construct parent string
        if not parent:
            if hou.expandString('$ACTIVETAKE') != "Main":
                parent = hou.expandString('$ACTIVETAKE')
        else:
            if isinstance(parent, Take):
                parent = parent.getName()

        if parent:
            self._parent = "-p " + parent
            self.parent = parent
        else:
            self._parent = ""
            self.parent = parent

            
        # Create Take and add it to the list of takes
        if _add_to_scene:
            self._createTake()

        # if node or parms included add it
        if include_parm:
            self.includeParms(include_parm)

        if include_node:
            for n in include_node:
                self.includeParmsFromNode(n)
            
        # set current
        if _add_to_scene:
            if self.set_to_current:
                hou.hscript("takeset " + self.name)
            else:
                hou.hscript("takeset Main")
コード例 #16
0
def createCollectionDir():
    collectDir = '$HIP'+'/collect'
    counter = 1
    while os.path.exists(hou.expandString(collectDir)) :
        collectDir = '$HIP'+'/collect' + str(counter)
        counter = counter + 1
    collectDir = hou.expandString(collectDir)
    os.makedirs(collectDir)
    return collectDir
コード例 #17
0
ファイル: assettools.py プロジェクト: astron10/SideFXLabs
    def buildDefaultPathFromPreset(self, preset):
        if preset == default_install_options[1]:
            _path = hou.expandString("$HOUDINI_USER_PREF_DIR/otls")
        elif preset == default_install_options[2]:
            _path = hou.expandString("$HIP")
        else:
            _path = getDefaultVHDAPath()

        return os.path.join(_path, self.defaults[1].replace("::", ".") +
                            ".hda").replace("\\", "/")
コード例 #18
0
    def setupUi(self):


        self.roots = "/prod/project/"
        #variable widget
        self.projectLine=QtWidgets.QLineEdit()
        self.stepLine=QtWidgets.QLineEdit()
        self.shotNameLine=QtWidgets.QLineEdit()
        self.startNameLine=QtWidgets.QLineEdit()
        self.endNameLine=QtWidgets.QLineEdit()
        #variable
        self.projectLine.setText(hou.expandString("$PROJECT_NAME"))
        self.projectName=self.projectLine.text() 
        self.stepLine.setText(hou.expandString("$STEP"))
        self.step=self.stepLine.text() 
        self.shotNameLine.setText(hou.expandString("$SHOT_NAME"))
        self.startNameLine.setText(hou.expandString("$START_FRAME"))
        self.endNameLine.setText(hou.expandString("$END_FRAME"))
        #setup path
        self.sequencesRoots= self.roots+self.projectName+"/sequences/"

        #les widgets
        self.label = QtWidgets.QLabel(self.sequencesRoots)
        #filter list
        self.filtrer=QtWidgets.QLineEdit()
        self.filtrer.setPlaceholderText('project filter')
        #list
        self.listWidget = QtWidgets.QListWidget()
        # refresh 
        self.refreshBouton=QtWidgets.QPushButton("filter and reload stg variable !")
        self.fixImportBouton=QtWidgets.QPushButton("createFixImportandBuildScene")
        self.versionUp=QtWidgets.QPushButton("versionUp")
        self.openAndScript=QtWidgets.QPushButton("openSceneAndApplyScript")
        self.textScript=QtWidgets.QPlainTextEdit()
        self.textScript.setPlaceholderText('pasteScriptHere')

        #layout
        mainLayout=QtWidgets.QVBoxLayout()
        #add widget to layout
        mainLayout.addWidget(self.label)
        mainLayout.addWidget(self.projectLine)
        mainLayout.addWidget(self.stepLine)
        mainLayout.addWidget(self.shotNameLine)
        mainLayout.addWidget(self.startNameLine)
        mainLayout.addWidget(self.endNameLine)
        #widget util
        mainLayout.addWidget(self.filtrer)
        mainLayout.addWidget(self.refreshBouton)
        mainLayout.addWidget(self.fixImportBouton)
        mainLayout.addWidget(self.versionUp)
        mainLayout.addWidget(self.openAndScript)
        mainLayout.addWidget(self.textScript,0,0)
        mainLayout.addWidget(self.listWidget,5,0)
        #set layout
        self.setLayout(mainLayout)
コード例 #19
0
def unpackage():
    """
        Unpacking of a scene file created by the copyPastePackage.package function. this needs to be looked at.
        I don't have windows so I have no idea if it works there.
            
    """

    zipfileLoc = hou.ui.selectFile(
        title="please select a zipFile created by the package function",
        pattern="*.zip")
    if not zipfileLoc:

        return

    file_ = zipfile.ZipFile(hou.expandString(zipfileLoc), "r")

    isOke = False

    for name in file_.namelist():

        if name.endswith(".hip") or name.endswith(".hipnc"):

            isOke = True
            break

    if not isOke:

        return

    unpackLoc = hou.expandString(
        hou.ui.selectFile(
            title=
            "please select a directory you wish to use to unpack the files to."
        ))

    if not unpackLoc or not os.path.isdir(unpackLoc):

        return

    unzip(file_, unpackLoc)
    unpackageDir = os.path.dirname(file_.namelist()[0])
    otlsfiles = glob.glob(os.path.join(unpackLoc, unpackageDir, "otls", "*"))
    hipfile = glob.glob(os.path.join(unpackLoc, unpackageDir, "*.hip*"))

    if len(hipfile) != 1:

        return

    hou.hipFile.load(hipfile[0])

    for otl in otlsfiles:

        hou.hda.installFile(otl)
コード例 #20
0
def get_environ_filename(path_env,
                         name_env,
                         path_default_list,
                         name_default_list,
                         parent_dir_must_exist=True,
                         file_must_exist=True):
    """
    Returns a filename from the current environment based on two supplied environment variable names; one for the path,
    one for the filename. In case the environment variables are not present or valid, you can specify a list of default
    paths and default filenames to check. The first valid filename will be returned. You can request that the path
    must exist, or that the full filename must exist.

    Args:
        path_env (str): Name of the environment variable containing the path
        name_env (str): Name of the environment variable containing the filename
        path_default_list (list): List of strings for default path
        name_default_list (list): List of strings for default filename
        parent_dir_must_exist (bool): If True, then the function will only return a filename if the path exists
        file_must_exist (bool): If True, then the function will only return a filename if the file exists too

    Returns:
        String: Returns a string containing the filename if the conditions are met, otherwise None
    """
    path_list = []
    name_list = []

    if path_env in os.environ:
        path_list.append(os.environ[path_env])

    if name_env in os.environ:
        name_list.append(os.environ[name_env])

    path_list.extend(path_default_list)
    name_list.extend(name_default_list)

    for path in path_list:
        for name in name_list:
            # Use hou.expandString() on each part of the path individually. Otherwise it will remove \\ at start
            path = os.path.normpath("\\".join(
                [hou.expandString(item) for item in path.split("\\")]))
            name = hou.expandString(name)
            filename = os.path.join(path, name)

            if file_must_exist and not (os.path.exists(filename)
                                        and os.path.isfile(filename)):
                continue

            if parent_dir_must_exist and not (os.path.exists(path)
                                              and os.path.isdir(path)):
                continue

            return filename
    return None
コード例 #21
0
def writeList(hou, file_path='', node_list=None):
    ''' This function creates the JSON content out of the provided list of nodes'''
    # grabs a collection of selected nodes
    if node_list == None:
        node_list = hou.selectedNodes()
    if node_list == ():
        return
    # creates various dictionaries to populate JSON
    data = {}
    nodes = {}
    connections = {}
    # run through nodes collectiong info
    for node in node_list:
        # dictionary to contain changed parms and values
        parms = {}
        # run through nodes' parms checkign for changed defaults
        for parm in node.parms():
            if parm.isAtDefault() == False:
                parms[parm.name()] = parm.eval()
        # populate nodes part of JSON dictionary
        nodes[node.name()] = dict(
            zip(['type', 'parms'], [node.type().name(), parms]))
        # populate connections part of dictionary
        connections[node.name()] = []
        for connection in node.inputConnections():
            connections[node.name()].append(
                dict({
                    connection.inputNode().name():
                    (connection.inputIndex(), connection.outputIndex())
                }))
    data['nodes'] = nodes
    data['connections'] = connections
    data['host'] = {'host': keyGen()}
    # write JSON file to disk
    if file_path == '':
        file_path = hou.expandString(
            hou.ui.selectFile(pattern='*.json',
                              chooser_mode=hou.fileChooserMode.Write))
    else:
        file_path = hou.expandString(
            hou.ui.selectFile(start_directory=file_path,
                              pattern='*.json',
                              chooser_mode=hou.fileChooserMode.Write))
    try:
        with open(file_path, 'w') as json_write:
            json_write.write(json.dumps(data, indent=4,
                                        separators=(',', ': ')))
    except IOError:
        hou.ui.setStatusMessage("Could not write snippet...")
        return -1
    hou.ui.setStatusMessage("Successfully wrote snippet as: " + file_path)
    return 0
コード例 #22
0
def getInputFile():
    inputFile = ''
    while (not _isValidTextFile(inputFile)):
        inputFile = hou.ui.selectFile(start_directory = hou.expandString(DAILIES_DIR),\
                                      title = "Select Definition (.txt) File",\
                                      collapse_sequences = False,\
                                      pattern = ('*.txt'),\
                                      multiple_select = False,\
                                      chooser_mode = hou.fileChooserMode.Read)
        if inputFile == '':
            raise Exception("No input file chosen. Exiting...")

    return hou.expandString(inputFile)
コード例 #23
0
ファイル: APSmisc.py プロジェクト: symek/haps
def getLocalStoragePath(TmpLocalStorage=HOUDINI_TEMP_DIR):
    TmpLocalStorage = hou.expandString(TmpLocalStorage)
    if not os.path.isdir(TmpLocalStorage):
        umask = os.umask(0)
        try:
            os.makedirs(TmpLocalStorage)
        except:
            TmpLocalStorage = hou.expandString(
                '$HOUDINI_TEMP_DIR/ifds/storage')
            if not os.path.isdir(TmpLocalStorage):
                os.makedirs(TmpLocalStorage)
        os.umask(umask)
    return TmpLocalStorage
コード例 #24
0
def getInputFile():
    inputFile = ''
    while(not _isValidTextFile(inputFile)):
        inputFile = hou.ui.selectFile(start_directory = hou.expandString(DAILIES_DIR),\
                                      title = "Select Definition (.txt) File",\
                                      collapse_sequences = False,\
                                      pattern = ('*.txt'),\
                                      multiple_select = False,\
                                      chooser_mode = hou.fileChooserMode.Read)
        if inputFile == '':
            raise Exception("No input file chosen. Exiting...")
    
    return hou.expandString(inputFile)
コード例 #25
0
ファイル: sceneSetup.py プロジェクト: all-in-one-of/kaTools-1
def setProject():
    file = "/promethium/init/projectDir.txt"
    f = open(file, "r")
    fl = f.readlines()

    projpaths = []

    for line in fl:
        projpath = line.split("=")[1].rstrip().replace("\"", "")
        print projpath
        exist = os.path.exists(projpath)

        if exist != True:
            print "This project Directory doesnt exist."
            pass
        else:
            projpaths.append(projpath)

    projpath = selectProjectDir(projpaths)

    if projpath is None:
        pass
    else:
        dirs = os.listdir(projpath)
        shotDirs = []
        for dir in dirs:
            if os.path.isfile(os.path.join(projpath, dir)):
                #print dir, "is a file"
                continue
            if re.search("^c\d", dir) != None or re.search("assets",
                                                           dir) != None:
                shotDirs.append(dir)

        shot = selectShot(shotDirs)
        if shot is None:
            pass
        else:
            # create template directories
            needTemplates = hou.ui.displayConfirmation(
                "Create Template directories?")
            if needTemplates is True:
                createTemplateDirs(os.path.join(projpath, shot))

            # set up frame range
            needFrameRange = hou.ui.displayConfirmation("Set Frame Range?")
            if needFrameRange is True:
                plateDir = os.path.join(hou.expandString("$PROJECTDIR"),
                                        hou.expandString("$SHOT"))
                plateDir = os.path.join(plateDir, "plate")
                setFrameRangeFromPlate(plateDir)
コード例 #26
0
def getFrameRange():
    rfstart = hou.expandString("$RFSTART")
    rfend = hou.expandString("$RFEND")
    ui = hou.ui.readMultiInput("Input Frame Range.",\
                               ["Start Frame","End Frame","Step"],\
                               buttons=["OK","Cancel"],\
                               default_choice=0,\
                               close_choice=1,\
                               help="Enter the Frame Range for which you want to generate the geometry sequences.  K Pumpkin??  ;P",\
                               title="Input Frame Range.",\
                               initial_contents=[str(rfstart),str(rfend),str("1")])
    if ui[0]:
        raise Exception("Cancelling...")
    return [ui[1][0], ui[1][1], ui[1][2]]
コード例 #27
0
def screenShot():
    """take a screen shot of the current viewport at the current frame"""
    help(screenShot)
    import hou
    import toolutils
    import os
    #selected node
    nodeSelect = hou.selectedNodes()
    path = hou.expandString("$HIP")
    frame = hou.expandString("$F")
    frame = int(frame)
    black = hou.Color((0, 0, 0))
    #name check there is a node selected
    if len(nodeSelect) < 1:
        print("!!!    error: select a node    !!!")
    else:
        for node in nodeSelect:
            name = node.name()
            node.setColor(black)
        #Get the current Desktop
        desktop = hou.ui.curDesktop()
        # Get the scene viewer
        scene = toolutils.sceneViewer()
        flipbook_options = scene.flipbookSettings().stash()
        # set frame range
        flipbook_options.frameRange((frame, frame))
        #set output path
        root = "{1}/{2}/{0}/".format(name, path, "screenShot")
        if os.path.exists(root):
            listPath = os.listdir(root)
            inc = len(listPath)
            inc = int(inc)
            outputPath = "{}{}.{:04d}.jpg".format(root, name, inc)
        else:
            os.makedirs(root)
            inc = 0
            outputPath = "{}{}.{:04d}.jpg".format(root, name, inc)
        #set flipbook current path
        flipbook_options.output(outputPath)
        #run flipbook
        scene.flipbook(scene.curViewport(), flipbook_options)
        # reload image
        print(outputPath)
        editor = hou.ui.paneTabOfType(hou.paneTabType.NetworkEditor)
        image = hou.NetworkImage()
        image.setPath(outputPath)
        image.setRect(hou.BoundingRect(0, 0, 5, 5))
        image.setRelativeToPath(node.path())
        editor.setBackgroundImages([image])
コード例 #28
0
def keyframeReducer(nodes,
                    parms=[],
                    startFrame=int(hou.expandString('$RFSTART')),
                    endFrame=int(hou.expandString('$RFEND')),
                    tolerance=0.0001):
    '''keyframeReducer
    For each node, look for the specified parameters during the frame range. If the difference between the current and next frame is less than the tolerance, remove the keyframe.

    If the parm list is empty, it will search though ALL parameters for the specified node. This will take a long time if you have a lot of nodes.
    '''

    originalKeyframes = 0
    deletedKeyframes = 0
    modified = False
    initialTime = time.clock()

    print 'Processing Keyframes'

    for node in nodes:
        for frame in range(startFrame, endFrame + 1):
            if not parms:
                temp = node.parms()
                for parm in temp:
                    parms.append(parm.name())
            for parm in parms:
                if node.parm(parm).keyframesInRange(frame, frame):
                    originalKeyframes += 1
                    if abs(
                            node.parm(parm).evalAsFloatAtFrame(frame + 1) -
                            node.parm(parm).evalAsFloatAtFrame(frame)
                    ) < tolerance:
                        if not modified:
                            modified = True
                        deletedKeyframes += 1
                        tempValue = node.parm(parm).eval()
                        node.parm(parm).deleteKeyframeAtFrame(frame)
                        node.parm(parm).set(tempValue)

    if modified:
        print 'Initial Frames: {}\nDeleted Frames: {}\nPercent Removed: {}%'.format(
            originalKeyframes, deletedKeyframes,
            deletedKeyframes / float(originalKeyframes) * 100)
    else:
        print 'No Keyframes Removed'
    seconds = time.clock() - initialTime
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    print 'Time taken to complete: {}h:{}m:{}s'.format(h, m, s)
    print 'Processing Complete'
コード例 #29
0
ファイル: weekly_render.py プロジェクト: seashby10/papa-tools
def getInputFile():
    inputFile = ""
    while not _isValidTextFile(inputFile):
        inputFile = hou.ui.selectFile(
            start_directory=hou.expandString(DAILIES_DIR),
            title="Select Definition (.txt) File",
            collapse_sequences=False,
            pattern=("*.txt"),
            multiple_select=False,
            chooser_mode=hou.fileChooserMode.Read,
        )
        if inputFile == "":
            raise Exception("No input file chosen. Exiting...")

    return hou.expandString(inputFile)
コード例 #30
0
def abc2bjson(infile, outdir = '$TEMP/'):
    
    # Create a temporary Geometry Node
    temp_geo = hou.node("/obj").createNode('geo')
    
    # Generate .bjson.gz sequences in folders that correspond to the keys of the
    # geo_dict.
    for key in _geo_dict.keys():
        # Skip key if no object paths listed.
        if not _geo_dict[key]:
            continue
        
        # Tell us what key we're working on
        print key + ": " + " ".join(_geo_dict[key])
        
        # Clean out temp_geo Node
        for n in temp_geo.children():
        	n.destroy()
    	
    	# Create a merge node to merge all abcSOPs
    	temp_merge = temp_geo.createNode("merge")
    	
    	# Create an Alembic for each object path and connect to temp_merge
    	for p in _geo_dict[key]:
    	    abcSOP = temp_geo.createNode("alembic")
            abcSOP.setParms({'fileName': infile, 'objectPath': p})
            temp_merge.setNextInput(abcSOP)
        
        # Generate Output to a separate directory for this geometry sequence.
        seqDir = os.path.join(outdir,key) + os.sep
        _generateOutput(temp_merge, hou.expandString(seqDir), key)
    
    # Clean Up
    temp_geo.destroy()
コード例 #31
0
ファイル: PyTake2.py プロジェクト: GJpy/Houpy_PyTake2
 def isCurrent(self):
     ''' 
         Returns True if the take is the current take, False otherwise.
     '''
     if self.name == hou.expandString("$ACTIVETAKE"):
         return True
     return False
コード例 #32
0
ファイル: bp_submit.py プロジェクト: Quazo/breakingpoint
def get_node_info():

    info = []
    # rop_list = hou.node('/out').allSubChildren()
    rop_list = hou.selectedNodes()
    if len(rop_list) == 0:
        return None

    arnold_rop_list = []

    for rop in rop_list:
        if rop.type().name() == "arnold":
            arnold_rop_list.append(rop)

    """
	for arnold_rop in arnold_rop_list:
		#arnold_rop.parm('execute').pressButton()
		ASS_FILE = hou.expandString(arnold_rop.evalParm('ar_ass_file'))
		print "ASSFILE:" + arnold_rop.evalParm('ar_ass_file')

	"""

    arnold_rop = arnold_rop_list[0]
    # arnold_rop.parm('execute').pressButton()
    info.append(hou.expandString(arnold_rop.parm("ar_ass_file").unexpandedString().replace("$F4", "####")))
    info.append(arnold_rop.path())

    return info
コード例 #33
0
def expandPathParm(parm):
    """
    Returns processed and expanded path from input parameter

    parm should be hou.Parm object
    """
    in_path = hou.pwd().path()
    hou.cd(parm.node().path())

    if len(parm.keyframes()) == 0:
        expr = parm.unexpandedString()
    else:
        expr = parm.eval()

    expr = expr.replace("$ACTIVETAKE", "<Channel>")
    expr = expr.replace("${ACTIVETAKE}", "<Channel>")

    expr = expr.replace("$WEDGE", "<Wedge>")
    expr = expr.replace("${WEDGE}", "<Wedge>")
    expr = expr.replace("${AOV}.", "<ValueVar @AOV.>")
    expr = expr.replace("${AOV}/", "<ValueVar @AOV/>")
    expr = expr.replace("${AOV}_", "<ValueVar @AOV_>")
    expr = expr.replace("$AOV.", "<ValueVar @AOV.>")
    expr = expr.replace("$AOV/", "<ValueVar @AOV/>")
    expr = expr.replace("$AOV_", "<ValueVar @AOV_>")

    path = hou.expandString(expr)

    expr = expr.replace(
        "@AOV", "@$AOV"
    )  #@$AOV is required for the output setting at render time, but expandString would remove it.

    hou.cd(in_path)
    return path
コード例 #34
0
def openCurFolder():
	buttons = ("HIP", "geo", "3d-out","out","Materials","cancel")
	choice = hou.ui.displayMessage("OPEN FOLDER:", buttons, hou.severityType.Message, 0, len(buttons)-1)
	if(choice!=len(buttons)-1):
		st = hou.expandString("$HIP")
		pattern = re.compile("/3d/hip")
		dirname = ''
		if pattern.search(st):
			if(choice==1):
				st = pattern.split(st)[0] + "/3d/hip/geo"
				dirname = 'geo'
			if(choice==2): 
				st = pattern.split(st)[0] + "/3d-out"
				dirname = '3d-out'
			if(choice==3): 
				st = pattern.split(st)[0] + "/out"
				dirname = 'out'
			if(choice==4): 
				st = pattern.split(st)[0] + "/Materials"
				dirname = 'Materials'
			nSt = os.path.normpath(st)
			if os.path.isdir(nSt):
				if _platform == "linux" or _platform == "linux2":
					os.chdir(nSt)
					webbrowser.open(nSt)
				else:
					os.system("start "+ nSt)
			else:
				hou.ui.displayMessage('"' + dirname + '"' + " directory does not exist")
		else: hou.ui.displayMessage(" Scene is not saved")
コード例 #35
0
def reloadGeo():

    import hou
    import os
    geoImport = hou.node("/obj/geoImport")

    children = geoImport.children()
    for n in children:
        n.destroy()

    #set path
    hipPath = hou.expandString('$HIP')
    path = hipPath + "/geo/"
    print(path)

    listPath = os.listdir(path)

    obj = hou.node("/obj")
    geoImport = hou.node("/obj/geoImport")

    for n in listPath:
        print(n)
        currentFile = geoImport.createNode("file", n)
        #set fileName
        currentFile.setParms({"file": "$" + "HIP/geo/" + n})
コード例 #36
0
ファイル: bp_open.py プロジェクト: satishgoda/breakingpoint
def crash_recovery():

    TEMP_PATH = hou.expandString("$TEMP")
    newest_hip = max(glob.iglob(TEMP_PATH + "/*.hip*"), key=os.path.getctime)
    newest_hip = newest_hip.replace("/", "\\")

    old_path = ""
    with open(newest_hip, mode="rb") as f:
        for line in f.readlines():
            if(line.startswith("set -g HIPFILE = ")):
                old_path = line.replace("set -g HIPFILE = ", "")
                old_path = old_path.replace("\'", "")
                old_path = old_path.replace("\n", "")
                break

    version_s = re.search("(?<=_v)", old_path)
    old_version = old_path[version_s.start():version_s.start()+3]
    new_version = "%03d" % (int(old_version)+1)

    new_path = old_path.replace("v{0}".format(old_version), "v{0}".format(new_version))
    new_path = new_path.replace(".hip", "_CRASH.hip")

    shutil.copy2(old_path, new_path)
    hou.hipFile.load(new_path)

    hou.ui.setStatusMessage("[BP] Recovered crashed file {0} to {1} successfully".format(old_path, new_path))
コード例 #37
0
def updateJobNameFromHipLocation():
    import os
    hip = hou.expandString("$HIP")
    JOB = os.path.dirname(hip)
    jobname = JOB.split("/").pop()
    hou.hscript('setenv JOBNAME =' + jobname)
    print("Updated JOBNAME to: " + jobname)
コード例 #38
0
    def handleBinary(self, node):
        if node.type().name() not in BinaryHandler._binaryNodes:
            return False

        self.node = node
        if node.path().startswith('/obj/bookkeeper'):
            return False

        outputs = node.outputConnections()
        outputData = list()
        if len(outputs) == 0:
            outputData.append('None')
        else:
            for output in outputs:
                childNode = output.outputNode()
                outIndex = output.outputIndex()
                inIndex = output.inputIndex()
                outputData.append(str((childNode.userData('uuid'),
                                       outIndex, inIndex)))
        hou.copyNodesToClipboard((node,))
        path = os.path.join(hou.expandString('$HOUDINI_TEMP_DIR'),
                            'SOP_copy.cpio')
        f = open(path, 'rb')
        data = f.read()
        f.close()
        zData = binascii.b2a_base64(zlib.compress(data, 9))
        nodeId = node.userData('uuid')
        parentId = node.parent().userData('uuid')
        return (nodeId, parentId, zData, str(outputData))
コード例 #39
0
ファイル: alembic_functionality.py プロジェクト: jonntd/helga
    def replace_global_variable(self, string_value, global_variable_name):
        """
        Expand global_variable_name, check if this string is in string value and replace if so.
        """

        #check if variable exists
        try:

            hou.hscriptExpression('{0}'.format(global_variable_name))

        except:

            #log
            self.logger.debug('Global variable {0} does not exist. Not altering string value'.format(global_variable_name))
            return string_value


        #global_variable_value
        global_variable_value = hou.expandString('{0}'.format(global_variable_name))

        #replace
        string_value = string_value.replace(global_variable_value, global_variable_name)

        #return
        return string_value
コード例 #40
0
def reloadAlembic():

    import hou
    import os
    alembicImport = hou.node("/obj/alembicImport")

    children = alembicImport.children()
    for n in children:
        n.destroy()

    #set path
    hipPath = hou.expandString('$HIP')
    path = hipPath + "/abc/"
    print(path)

    listPath = os.listdir(path)

    obj = hou.node("/obj")
    alembicImport = hou.node("/obj/alembicImport")

    for n in listPath:
        print(n)
        currentFile = alembicImport.createNode("alembic", n)
        #set fileName
        currentFile.setParms({"fileName": "$" + "HIP/abc/" + n})
コード例 #41
0
def unpackage():
    """
        Unpacking of a scene file created by the copyPastePackage.package function. this needs to be looked at.
        I don't have windows so I have no idea if it works there.
            
    """

    zipfileLoc = hou.ui.selectFile(title="please select a zipFile created by the package function", pattern="*.zip")
    if not zipfileLoc: 
        
        return
    
    file_ = zipfile.ZipFile(hou.expandString(zipfileLoc), "r")

    isOke = False
    
    for name in file_.namelist():
        
        if name.endswith(".hip") or name.endswith(".hipnc"):
            
            isOke = True
            break
    
    if not isOke: 
        
        return
        
    unpackLoc = hou.expandString(hou.ui.selectFile(title="please select a directory you wish to use to unpack the files to."))
    
    if not unpackLoc or not os.path.isdir(unpackLoc): 
        
        return
      
    unzip(file_, unpackLoc)
    unpackageDir = os.path.dirname(file_.namelist()[0])
    otlsfiles = glob.glob(os.path.join(unpackLoc, unpackageDir, "otls", "*"))
    hipfile = glob.glob(os.path.join(unpackLoc, unpackageDir, "*.hip*"))
        
    if len(hipfile) != 1: 
        
        return
    
    hou.hipFile.load(hipfile[0])
        
    for otl in otlsfiles:

        hou.hda.installFile(otl)
コード例 #42
0
def getOutputDir(output = None):
    if not output:
        hou.ui.displayMessage("Please Select a Render Output Directory.")
        outputDir= ''
        outputDir = hou.ui.selectFile(start_directory = None,\
                                          title = "Select Output Directory for Renders",\
                                          collapse_sequences = False,\
                                          file_type = hou.fileType.Directory,\
                                          multiple_select = False,\
                                          chooser_mode = hou.fileChooserMode.Read)
        if not outputDir:
            return hou.expandString(output)

        return hou.expandString(outputDir)

    else:
        return hou.expandString(output)
コード例 #43
0
ファイル: takes.py プロジェクト: hibernationTheory/sQuery
def curTake():
	
	'''returns the current Take object'''
	
	current_take_name = hou.expandString("$ACTIVETAKE")
	current_take = TakeWrapper(current_take_name)
	result = current_take
	return result
コード例 #44
0
    def pasteBinary(self, rawData):
        data = zlib.decompress(binascii.a2b_base64(rawData))

        path = os.path.join(hou.expandString('$HOUDINI_TEMP_DIR'),
                            'SOP_copy.cpio')
        f = open(path, 'wb')
        f.write(data)
        f.close()
コード例 #45
0
ファイル: c3d_ui.py プロジェクト: mikedatsik/C3DtoHoudini
def C3D_MainCallBackFunction():

    explist = hou.expandString(dialog.value("file_c3d.val")).split(" ; ")

    file_chan = [dialog.value("savechan.val"), dialog.value("file_chan.val")]
    hou_cord = dialog.value("hou_cord.val")
    framerate = [dialog.value("framerate_enabler.val"), dialog.value("framerate.val")]
    start_end = [dialog.value("startend_enabler.val"), dialog.value("startend0.val"), dialog.value("startend1.val")]
    mymenu = dialog.value("mymenu.val")
    
    if str(dialog.value("save.val")) == "1.0":
        if explist[0] == "":
            hou.ui.displayMessage("You must choose file!")
        else:
            check_done = 0
            for expstr in explist:
                if os.path.exists(expstr) and  os.path.splitext(expstr)[1].lower() == ".c3d":
                    cmd = []

                    cmd.append(expstr)

                    cmd.append(mymenu)

                    cmd.append(framerate[0])

                    cmd.append(int(framerate[1]))

                    ### ADD Convert to Houdini coordinates

                    cmd.append(start_end[0])

                    cmd.append(start_end[1])

                    cmd.append(start_end[2])
                    
                    if file_chan[0]:
                        if file_chan[1] != "":
                            cmd.append(file_chan[1])
                        else:
                            hou.ui.displayMessage("You must choose directory to write clip!\n or unselect checkbox to save by Default")
                            return
                    else:
                        cmd.append("")

                    c3d.CreateMarkerSet(*cmd)
                    print cmd
                    check_done=+1
            if check_done != 0:
                pass
                dialog.setValue("open.val", 0)
                dialog.destroy()
                hou.ui.displayMessage("All done!")
            else:
                hou.ui.displayMessage("You must choose .c3d file!")

    else:
        dialog.setValue("open.val", 0)
        dialog.destroy()
コード例 #46
0
ファイル: PyTake2.py プロジェクト: GJpy/Houpy_PyTake2
def currentTake():
    '''
        Return the current take.
    '''
    currentName = hou.expandString('$ACTIVETAKE')
    if currentName == "Main":
        print("Current take is Main take")
        return None
    else:
        return _readScript(currentName)
コード例 #47
0
ファイル: AutoCompFusion.py プロジェクト: Aeoll/Aelib
def run():
    floc = os.path.dirname(os.path.abspath(__file__))
    scriptLoc = floc
    templateLoc = floc
    template = templateLoc + "/template.comp"
    # FUSION = "C:\Program Files\Blackmagic Design\Fusion 9\Fusion.exe"
    FUSION = "/opt/BlackmagicDesign/Fusion9/Fusion"


    newcomp = hou.expandString("$HIP") + "/comp/" + hou.expandString("$HIPNAME") + "_autocomp.comp"
    if not os.path.exists(os.path.dirname(newcomp)):
        os.makedirs(os.path.dirname(newcomp))
    shutil.copy2(template, newcomp)

    # set the save path for the autocomp and part of the path for its write nodes
    compwritepath = hou.expandString("$HIP") + "/comp/render/" + hou.expandString("$HIPNAME") + "_"
 
 
 
    subprocess.Popen([FUSION, newcomp])
コード例 #48
0
def getInputFile():
    inputFile = ''
    while(not _isValidAlembic(inputFile)):
        inputFile = hou.ui.selectFile(start_directory = None,\
                                      title = "Select Alembic (.abc) File",\
                                      collapse_sequences = False,\
                                      pattern = ('*.abc'),\
                                      multiple_select = False,\
                                      chooser_mode = hou.fileChooserMode.Read)
        if inputFile == '':
            raise Exception("No input file chosen. Exiting...")
    return hou.expandString(inputFile)
コード例 #49
0
def getOutputDir(choices = None):
    if choices:
        c = hou.ui.selectFromList(choices,\
                                       exclusive = True,\
                                       title = 'Choose Directory',\
                                       num_visible_rows = len(choices))
        if not c:
            raise Exception("No Output Folder Selected. Exiting...")
        return hou.expandString(_interpretChoice(choices[c[0]]))
    else:
        outDir = ""
        while(not os.path.isdir(hou.expandString(outDir))):
            outDir = hou.ui.selectFile(start_directory = None,\
                                       title = "Select Output Folder",\
                                       collapse_sequences = False,\
                                       pattern = ('*'),\
                                       multiple_select = False,\
                                       chooser_mode = hou.fileChooserMode.Read)
            if outDir == '':
                return outDir
        return hou.expandString(outDir)
コード例 #50
0
def getFrameRange():
    """
    Use a Houdini Dialog to get from the user and return a 3-tuple in the form:
    
        (Start Frame, End Frame, Step)

    Raise an Exception if no selection is made.
    """

    rfstart = hou.expandString("$RFSTART")
    rfend = hou.expandString("$RFEND")
    ui = hou.ui.readMultiInput("Input Frame Range.",\
                               ["Start Frame","End Frame","Step"],\
                               buttons=["OK","Cancel"],\
                               default_choice=0,\
                               close_choice=1,\
                               help="Enter the Frame Range that you exported.\n\
                                     (Ex: If you exported frames 92 to 305 from Maya, input 92 and 305).",\
                               title="Input Frame Range.",\
                               initial_contents=[str(rfstart),str(rfend),str("1")])
    if ui[0]:
        raise Exception("Cancelling...")
    return (ui[1][0], ui[1][1], ui[1][2])
コード例 #51
0
ファイル: bp_save.py プロジェクト: Quazo/breakingpoint
def save_increment():

    # Save only if there are unsaved changes
    if(not hou.hipFile.hasUnsavedChanges()):
        return

    hipname = hou.expandString("$HIPNAME")
    hipfile = hou.expandString("$HIPFILE")
    hip = hou.expandString("$HIP")
    hipformat = hipfile.split(".")[-1]

    # Remove Comment
    comment = hipname.split(".")[0].split("_")[-1]
    if(len(comment) > 2):
        hipname = hipname.replace("_{0}".format(comment), "")

    # Increment Version
    version_s = re.search("(?<=_v)", hipname)
    old_version = hipname[version_s.start():version_s.start()+3]
    new_version = "%03d" % (int(old_version)+1)

    old_version = "v{0}".format(old_version)
    new_version = "v{0}".format(new_version)
    hipname = hipname.replace(old_version, new_version)

    try:

        hou.hipFile.save(file_name="{0}/{1}.{2}".format(hip, hipname, hipformat))
        # hou.hipFile.saveAndIncrementFileName()
        HIPFILE = hou.expandString("$HIPFILE")
        msg = "[BP] Successfully saved under : {0}".format(HIPFILE)
        msgSeverityType = hou.severityType.ImportantMessage
        hou.ui.setStatusMessage(msg, msgSeverityType)

    except:

        hou.ui.setStatusMessage("Save aborted!", hou.severityType.Error)
コード例 #52
0
def getInputFile():
    """
    Open a Houdini File Select Dialog and return the path to the Alembic file to
    be read. Raises an Exception if no file is chosen.
    """
    
    inputFile = ''
    while(not _isValidAlembic(inputFile)):
        inputFile = hou.ui.selectFile(start_directory=None,\
                                      title="Select Alembic (.abc) File",\
                                      collapse_sequences=False,\
                                      pattern=('*.abc'),\
                                      multiple_select=False,\
                                      chooser_mode=hou.fileChooserMode.Read)
        if inputFile == '':
            raise Exception("No input file chosen. Exiting...")
    return hou.expandString(inputFile)
コード例 #53
0
ファイル: HComHoudiniClient.py プロジェクト: GJpy/HCom
def sendBgeo(target_clientID, sender, tabTarget, isObj=False, tabClientType=None):
    
    n = hou.selectedNodes()
    if not n:
        hou.ui.displayMessage("Nothing is selected")
        return False
    sel = n[0]
    
    if sel.__class__ != hou.SopNode:
        hou.ui.displayMessage("Node selected is not a sop node")
        return False
    
    geo = sel.geometry()
    
    if isObj:
        if not geo.points():
            hou.ui.displayMessage("No points found on geometry")
            return False
    
    fileType = ".bgeo"
    if isObj:
        fileType = ".obj"
    
    # Dump geo on disk in a tmp file if data() not supported by houdini's version
    # If it is an obj file it must pass by saveToFile() methode
    if hasattr(geo, "data") and not isObj:
        binaryData = geo.data()
    else:
        tmpFile = hou.expandString("$HOME") + "/" + "tmphcom__" + fileType
        geo.saveToFile(tmpFile)
        binaryData = ""
        with open(tmpFile, 'rb') as f:
            binaryData = f.read()
        os.remove(tmpFile)
    
    meshData = {}
    meshData["MESH_TYPE"] = fileType
    meshData["MESH_NAME"] = sel.name()
    meshData["MESH_DATA"] = binaryData
    
    result = _sendData(target_clientID, sender, meshData, "mesh", tabTarget)
    if result:
        return True
    else:
        return False
コード例 #54
0
ファイル: HComHoudiniUtils.py プロジェクト: GJpy/HCom
def getAllLib(node):
    '''
        Fetch all library path of sub otls and selected otl.
        returns a dict {lib_file:binary_data}
    '''
    
    libFound = False
    libData = []
    libNameList = []
                
    # All sub children nodes
    allChildrens = list(node.allSubChildren())
    allChildrens.append(node)
    
    for childrenNode in allChildrens:
        
        nodeDefinition = childrenNode.type().definition()
        if not nodeDefinition:
            continue
        
        libPath = nodeDefinition.libraryFilePath()
        libName = os.path.basename(libPath)
        
        if libName in libNameList:
            continue
        
        # Skip built-in otl
        if libPath.startswith(hou.expandString("$HH")):
            continue
        
        if not os.path.exists(libPath):
            continue
        
        binaryData = ""
        with open(libPath, 'rb') as f:
            binaryData = f.read()
        
        libData.append([libName, binaryData])
        libNameList.append(libName)
        libFound = True
    
    if libFound:
        return libData
    return False
コード例 #55
0
ファイル: ybox.py プロジェクト: kybin/houdini
def gotoCategory(goto_category):
	pane = currentPanetab()
	goto_path = hou.expandString("$LAST{0}".format(goto_category.upper()))
	current_path = currentNode().path()
	current_category = current_path.split('/')[1]

	if goto_category == current_category:
		return False

	# save our lastnode in this context
	hou.hscript('set -g LAST{0} = {1}'.format(current_category.upper(), current_path))
	# then goto destination context
	goto_root =  (not goto_path) or (goto_path.count('/')==1)
	if goto_root:
		pane.cd("/{0}".format(goto_category))
	elif goto_path:
		pane.setCurrentNode(hou.node(goto_path))

	print("\nset $LAST{0} ({1})".format(current_category.upper(), current_path))
	print("goto $LAST{0} ({1})".format(goto_category.upper(), goto_path))
	return True
コード例 #56
0
ファイル: IFDuserhooks.py プロジェクト: horitin/pipeline
def processInclude(filename):

    if filename:
        if filename.find(' ') >= 0:
            ray_comment('Inline include (value has spaces)')
            #soho.indent()
            print filename
            ray_comment('End of Inline include')
        else:
            try:
                fp = open(filename, 'r')
                ray_comment('Include file: %s' % filename)
                for line in fp.readlines():
                    #soho.indent()
                    sys.stdout.write(hou.expandString(line))
                ray_comment('End of include file: %s' % filename)
            except:
                ray_comment('Error processing include file: %s' % filename)
        return True
        
    return False
コード例 #57
0
    def pasteUser(self):
        """
            Request a users home directory's and try to load the cmd file.
        
        """
        
        response = hou.ui.readInput("Please provide the username of the user who's file you'd like to load")[1]
        
        if response:
            
            # Returns the filepath of the users we want to look for. we will check and see if this file is really there.
            pathToFile = os.path.join(os.path.dirname(hou.expandString("~")), response, os.path.split(self._copyFile)[1])

            if os.path.isfile(pathToFile):
                
                self._copyFile = pathToFile
                self.paste()
            
            else:
            
                hou.ui.displayMessage("The given username has no written out commands to load in")
コード例 #58
0
ファイル: urho_xml.py プロジェクト: ghidra/htou
def collect_nodes():
	#we should only have one node selected
	for n in hou.selectedNodes():
		#first we should check that we have selected a node that is a urho NODE
		if n.type().nameComponents()[2] in ('null','merge'):
			if(n.name().split("_")[0]=='NODE'):
				#now lets find out where we want to save this bitch
				path = hou.ui.selectFile(title="pick save location")
				path = hou.expandString(path)

				data = gen_node(node_data(n))
				seek_component(n,data)

				print(path+strip_string( strip_digits(n.name()), 'NODE_')+".xml")
				WriteXml(data,path+strip_string( strip_digits(n.name()), 'NODE_')+".xml")
				#print tostring(data)
				#print xml.dump(node_data)
			else:
				print "ERROR: We expect the selected node to be labeled as NODE"
		else:
			print "ERROR: The selected nodes should be a null or merge. As well we expect the selected node to be labeled as NODE"
		'''node = gen_node(node_data(n))