def initialsetup(cur): currentidx = hou.hotkeys.changeIndex() chindex = getchangeindex(cur) if len(chindex) == 0: chindex = int(currentidx) updatechangeindex(chindex, True) updatedataasync() if hou.isUIAvailable(): try: hou.ui.setStatusMessage( la.MESSAGES['initialsetup1'], severity=hou.severityType.Message) except: print(la.MESSAGES['initialsetup1']) else: print(la.MESSAGES['initialsetup1']) else: chindex = int(chindex[0][0]) if int(currentidx) != chindex: getlastusedhk(cur) updatedataasync() updatechangeindex(int(currentidx)) if hou.isUIAvailable(): hou.ui.setStatusMessage( la.MESSAGES['initialsetup2'], severity=hou.severityType.Message)
def initialsetup(self): currentidx = hou.hotkeys.changeIndex() chindex = self.getchangeindex() if len(chindex) == 0: chindex = int(currentidx) self.updatechangeindex(chindex, True) self.updatecontext(self.isdebug) if hou.isUIAvailable(): hou.ui.setStatusMessage("Searcher database created", severity=hou.severityType.Message) else: print("Searcher database created") else: chindex = int(chindex[0][0]) if int(currentidx) != chindex: self.getlastusedhk() self.updatecontext() self.updatechangeindex(int(currentidx)) if hou.isUIAvailable(): hou.ui.setStatusMessage( "Searcher database created and populated", severity=hou.severityType.Message) # !SECTION # !SECTION
def getlastusedhk(self): try: lastkey = self.settings[util.SETTINGS_KEYS[11]] if str(lastkey) != "": lasthk = str(lastkey).split(' ') hkcheck = hou.hotkeys.assignments(str(lasthk[0])) if len(hkcheck) is 0: self.settings[util.SETTINGS_KEYS[11]] = "" settings_data.savesettings(settingdata) return rmresult = hou.hotkeys.removeAssignment( str(lasthk[0]).strip(), str(lasthk[1]).strip()) if rmresult: hkcheck = hou.hotkeys.assignments(str(lasthk[0])) hou.hotkeys.saveOverrides() if len(hkcheck) is 0: self.settings[util.SETTINGS_KEYS[11]] = "" settings_data.savesettings(settingdata) self.updatechangeindex(int(currentidx)) else: hou.hotkeys.clearAssignments(str(lasthk[0])) hou.hotkeys.saveOverrides() hkcheck = hou.hotkeys.assignments(str(lasthk[0])) if len(hkcheck) is 0: self.settings[util.SETTINGS_KEYS[11]] = "" settings_data.savesettings(settingdata) self.updatechangeindex(int(currentidx)) else: if hou.isUIAvailable(): hou.ui.setStatusMessage(( "Could not clear last assigned temp hotkey on last attempt:" ), severity=hou. severityType.Warning) else: print( "Could not clear last assigned temp hotkey on last attempt:" ) else: if hou.isUIAvailable(): hou.ui.setStatusMessage( ("Could not clear last assigned temp hotkey:"), severity=hou.severityType.Warning) else: print("Could not clear last assigned temp hotkey:") except (AttributeError, TypeError) as e: if hou.isUIAvailable(): hou.ui.setStatusMessage( ("Could not query last assigned temp hotkey:" + str(e)), severity=hou.severityType.Warning) else: print("Could not query last assigned temp hotkey: " + str(e))
def getlastusedhk(cur): settingdata = get_settings() lastkey = settingdata[util.SETTINGS_KEYS[11]] try: if str(lastkey) != "": lasthk = str(lastkey).split(' ') hkcheck = hou.hotkeys.assignments(str(lasthk[0])) if len(hkcheck) is 0: settingdata[util.SETTINGS_KEYS[11]] = "" settings_data.savesettings(settingdata) return rmresult = hou.hotkeys.removeAssignment( str(lasthk[0]).strip(), str(lasthk[1]).strip()) if rmresult: hkcheck = hou.hotkeys.assignments(str(lasthk[0])) hou.hotkeys.saveOverrides() if len(hkcheck) is 0: settingdata[util.SETTINGS_KEYS[11]] = "" settings_data.savesettings(settingdata) currentidx = hou.hotkeys.changeIndex() updatechangeindex(int(currentidx)) else: hou.hotkeys.clearAssignments(str(lasthk[0])) hou.hotkeys.saveOverrides() hkcheck = hou.hotkeys.assignments(str(lasthk[0])) if len(hkcheck) is 0: settingdata[util.SETTINGS_KEYS[11]] = "" settings_data.savesettings(settingdata) currentidx = hou.hotkeys.changeIndex() updatechangeindex(int(currentidx)) else: if hou.isUIAvailable(): hou.ui.setStatusMessage( (la.DBERRORMSG['getlastusedhk3']), severity=hou.severityType.Warning) else: print(la.DBERRORMSG['getlastusedhk3']) else: if hou.isUIAvailable(): hou.ui.setStatusMessage((la.DBERRORMSG['getlastusedhk2']), severity=hou.severityType.Warning) else: print(la.DBERRORMSG['getlastusedhk2']) except (AttributeError, TypeError) as e: if hou.isUIAvailable(): hou.ui.setStatusMessage((la.DBERRORMSG['getlastusedhk1'] + str(e)), severity=hou.severityType.Warning) else: print(la.DBERRORMSG['getlastusedhk1'] + str(e))
def _doCreate(nodeType, name, className, version=None, envVarName=None, parent=None, contextArgs={}): if hou.isUIAvailable() and contextArgs.get("toolname", ""): holder = toolutils.genericTool(contextArgs, nodeType, nodename=name) else: parent = parent if parent else hou.node("/obj").createNode( "geo", node_name=name, run_init_scripts=False) holder = parent.createNode(nodeType, node_name=name) IECoreHoudini.FnParameterisedHolder(holder).setParameterised( className, version, envVarName) if contextArgs.get("shiftclick", False): converter = holder.parent().createNode("ieCortexConverter", node_name=holder.name() + "Converter") outputNode = hou.node(contextArgs.get("outputnodename", "")) toolutils.connectInputsAndOutputs(converter, False, holder, outputNode, 0, 0) x, y = holder.position() converter.setPosition([x, y - 1]) return holder
def _error(message, exception_class): if hou.isUIAvailable(): hou.ui.displayMessage(message, severity=hou.severityType.Error) else: print(message) raise exception_class(message)
def loadsettings(): results = {} try: settingsdata.beginGroup('Searcher') for i in range(len(util.SETTINGS_KEYS)): if util.SETTINGS_TYPES[util.SETTINGS_KEYS[i]] in {"bool", "flag"}: results.update({ util.SETTINGS_KEYS[i]: util.bc(settingsdata.value(util.SETTINGS_KEYS[i])) }) else: results.update({ util.SETTINGS_KEYS[i]: settingsdata.value(util.SETTINGS_KEYS[i]) }) settingsdata.endGroup() return results except (AttributeError, TypeError) as e: if hou.isUIAvailable(): hou.ui.setStatusMessage( (la.SETTINGSMESSAGES['loadsettings'] + str(e)), severity=hou.severityType.Warning) else: print(la.SETTINGSMESSAGES['loadsettings'] + str(e))
def exception(msg): details = traceback.format_exc() if hou.isUIAvailable(): hou.ui.displayMessage(msg, details=details) else: print msg print details
def updatechangeindex(indexval, new=False): try: if new is True: defaultkey = "" for i in range(len(util.HOTKEYLIST)): result = hou.hotkeys.findConflicts("h", util.HOTKEYLIST[i]) if not result: defaultkey = util.HOTKEYLIST[i] Settings.insert( indexvalue=indexval, defaulthotkey=defaultkey, searchdescription=0, searchprefix=0, searchcurrentcontext=0, lastused="", id=1).execute() else: Settings.update(indexvalue=indexval).where( Settings.id == 1).execute() except(AttributeError, TypeError) as e: if hou.isUIAvailable(): hou.ui.setStatusMessage( (la.DBERRORMSG['updatechangeindex'] + str(e)), severity=hou.severityType.Warning) else: print(la.DBERRORMSG['updatechangeindex'] + str(e))
def updatecontext(self, debug): self.isdebug = debug try: time1 = ptime.time() self.cleardatabase() ctxdata, hkeydata = getdata() with db.atomic(): for data_dict in ctxdata: HContext.replace_many(data_dict).execute() with db.atomic(): for idx in hkeydata: Hotkeys.replace_many(idx).execute() HotkeysIndex.replace_many(idx).execute() time2 = ptime.time() if self.isdebug and self.isdebug.level in {"TIMER", "ALL"}: res = ((time2 - time1) * 1000.0) if hou.isUIAvailable(): hou.ui.setStatusMessage(('DB update took %0.4f ms' % res), severity=hou.severityType.Message) else: print('DB update took %0.4f ms' % res) return res except (AttributeError, TypeError) as e: hou.ui.setStatusMessage( ("Could not update Searcher context database: " + str(e)), severity=hou.severityType.Error)
def newAuthorization(cls, auth=None, altparent=None): # type: (dict, "QObject") -> bool # appends or changes auth in file # auth parameter is used as default data when promped user, contents of auth will get replaced if user logins successfully code = 0 data = cls.readAuthorizationsFile() newauth = cls.defaultentry if auth is not None and 'user' in auth and 'token' in auth: # just write to config and get the hell out # or maybe we can test it first... oldones = [ x for x in data['collections'] if x['user'] == auth['user'] ] for old in oldones: data['collections'].remove(old) cls.__sendCallbacks((old, 0, 0)) data['collections'].append(auth) cls.__sendCallbacks((auth, 0, 1)) cls.writeAuthorizationFile(data) return True # make a new auth logindialog = QGithubDeviceAuthDialog( '42e8e8e9d844e45c2d05', auth['user'] if auth is not None else None, parent=altparent) logindialog.exec_() result = logindialog.get_result() if result is None: return False newauth.update(result) username = newauth['user'] # now update passed auth TODO: why am i doing this? just return it if auth is None: auth = {} auth.update(newauth) # send callbacks oldones = [x for x in data['collections'] if x['user'] == username] for old in oldones: data['collections'].remove(old) cls.__sendCallbacks((old, 0, 0)) data['collections'].append(newauth) cls.__sendCallbacks((newauth, 0, 1)) try: cls.writeAuthorizationFile(data) except: if hou.isUIAvailable(): hou.ui.displayMessage("writing token to file failed!") else: QMessageBox.warning(altparent, 'error', "writing token to file failed!") return False return True
def displayMessage(msg): """Pop up a message dialog to display the given message. If the ui is unavailable, then it writes the message to the console. """ if hou.isUIAvailable(): hou.ui.displayMessage(msg, severity=hou.severityType.Message) else: print(msg)
def statmsg(msg, warn=False): """. """ assert type(msg) is str s = hou.severityType.ImportantMessage if warn else hou.severityType.Message if warn: msg = "WARNING: %s" % msg if hou.isUIAvailable(): hou.ui.setStatusMessage(msg, severity=s)
def startup(self, origin): if self.core.uiAvailable: if not hou.isUIAvailable(): return False if hou.ui.mainQtWindow() is None: return False if platform.system() == "Darwin": origin.messageParent = QWidget() origin.messageParent.setParent(hou.ui.mainQtWindow(), Qt.Window) if self.core.useOnTop: origin.messageParent.setWindowFlags( origin.messageParent.windowFlags() ^ Qt.WindowStaysOnTopHint) else: origin.messageParent = hou.ui.mainQtWindow() curShelfSet = hou.ui.curDesktop().shelfDock().shelfSets()[0] curShelves = curShelfSet.shelves() try: prismShelf = hou.shelves.shelves()["prism"] except: msgString = "Could not find the Prism shelf.\n\nDo you want to update the Prism integration in Houdini to fix this?" msg = QMessageBox(QMessageBox.Warning, "Prism Warning", msgString, QMessageBox.Ok | QMessageBox.Cancel) self.core.parentWindow(msg) action = msg.exec_() if action == QMessageBox.Ok: result = self.writeHoudiniFiles( os.environ["HOUDINI_USER_PREF_DIR"]) if result: QMessageBox.information( self.core.messageParent, "Restart", "Successully updated the Prism integration.\n\nAfter the next Houdini restart the Prism shelf will be available." ) else: if prismShelf not in curShelves: hou.ShelfSet.setShelves(curShelfSet, curShelves + (prismShelf, )) origin.startasThread() else: QApplication.addLibraryPath( os.path.join(hou.expandString("$HFS"), "bin", "Qt_plugins")) qApp = QApplication.instance() if qApp is None: qApp = QApplication(sys.argv) origin.messageParent = QWidget() origin.timer.stop()
def register_callbacks(): """Register any dynamic callback functions. :return: """ _register_atexit() if hou.isUIAvailable(): _register_when_ui_available()
def getchangeindex(cur): try: cur.execute("SELECT indexvalue FROM settings") result = cur.fetchall() return result except(AttributeError, TypeError) as e: if hou.isUIAvailable(): hou.ui.setStatusMessage( (la.DBERRORMSG['getchangeindex'] + str(e)), severity=hou.severityType.Warning) else: print(la.DBERRORMSG['getchangeindex'] + str(e))
def main( rop = '', threads = -1, closeDelay = 60): print '=' * 50 if hou.isUIAvailable() and hou.hipFile.hasUnsavedChanges(): print '!!! UNSAVED CHANGES !!!' closeDelay = -1 if rop == '': rop = get_node() if rop != '' and closeDelay != -1: get_parameters( rop, threads, closeDelay)
def register_callbacks(): """Register any dynamic callback functions. :return: """ atexit.register(_atexit_callback) if hou.isUIAvailable(): _register_when_ui_available() hou.hipFile.addEventCallback(_hip_event_callback)
def scene_was_saved(event_type): if event_type == hou.hipFileEventType.BeforeSave: # Display via Hou UI rather than console; preferably. if hou.isUIAvailable(): hou.ui.displayMessage("The user saved to %s" % hou.hipFile.path()) else: print("The user saved to %s" % hou.hipFile.path()) # ----------------------------------------------------------- # SCENE FILE EVENT CALLBACK ))))))))))))))))))))))))))))) END # -----------------------------------------------------------
def displayError(msg, exception=None): """Pop up a message dialog to display the given error message. If the ui is unavailable, then it writes the message to the console. """ if hou.isUIAvailable(): details = (str(exception) if exception is not None else None) hou.ui.displayMessage(msg, severity=hou.severityType.Error, details=details) else: if exception is not None: msg += "\n" + str(exception) raise hou.OperationFailed(msg)
def viewport_selection(kwargs, groupparm="group", grouptypeparm="grouptype"): me = kwargs['node'] # enable active viewport interactive grouping if hou.isUIAvailable(): scene_viewer = toolutils.sceneViewer() selection = scene_viewer.currentGeometrySelection() if selection: me.parm('group').set(selection.mergedSelectionString()) type = selection.geometryType() if type == hou.geometryType.Points: me.parm('grouptype').set(3) if type == hou.geometryType.Primitives: me.parm('grouptype').set(4)
def isbatch(default=False): try: import maya.cmds as cmds return cmds.about(batch=True) except ImportError: pass try: import hou return hou.isUIAvailable() except ImportError: pass return default
def process(self, msg, kwargs): """Override process() function to possibly insert a node path or to display a dialog with the log message before being passed to regular logging output. :param msg: The log message. :type msg: str :param kwargs: kwargs dict. :type kwargs: dict :return: The message and updated kwargs. :rtype: (str, dict) """ if "extra" in kwargs: extra = kwargs["extra"] node = extra.pop("node", self.node) # Prepend the message with the node path. if node is not None: path = node.path() msg = "{} - {}".format(path, msg) dialog = extra.pop("dialog", self.dialog) status_bar = extra.pop("status_bar", self.status_bar) severity = hou.severityType.Message if hou.isUIAvailable(): # Copy of the message for our display. houdini_message = msg # If we have message args we need to format the message with them. if "message_args" in extra: houdini_message = houdini_message % extra["message_args"] severity = extra.pop("severity", severity) # Display the message as a popup. if dialog: title = extra.pop("title", None) hou.ui.displayMessage(houdini_message, severity=severity, title=title) if status_bar: hou.ui.setStatusMessage(houdini_message, severity=severity) return msg, kwargs
def savesettings(settingdict): print("Save Settings?") try: settingsdata.beginGroup('Searcher') keys = list(settingdict.keys()) for i in range(len(keys)): settingsdata.setValue(keys[i], settingdict[keys[i]]) settingsdata.endGroup() settingsdata.sync() except (AttributeError, TypeError) as e: if hou.isUIAvailable(): hou.ui.setStatusMessage( (la.SETTINGSMESSAGES['savesettings'] + str(e)), severity=hou.severityType.Warning) else: print(la.SETTINGSMESSAGES['savesettings'] + str(e))
def doweb(self): if self.ui.title.text() == "": self.parentwindow.parentwindow.setstatusmsg( "Please enter a title for your bug report", "ImportantMessage") if hou.isUIAvailable(): hou.ui.setStatusMessage( "Please enter a title for your bug report.", severity=hou.severityType.Warning) return submittype = submittypeswitch(self.ui.label_cbox.currentIndex()) reporturl = '''https://github.com/instance-id/searcher_addon/issues/new?%s%s''' % ( submittype, self.ui.title.text()) QtGui.QDesktopServices.openUrl(QtCore.QUrl(reporturl)) self.parentwindow.parentwindow.close()
def cleardatabase(): try: delhk = "DELETE FROM hotkeys" delctx = "DELETE FROM hcontext" delhkindex = "DELETE FROM hotkeysindex" db.cursor().execute(delhk) db.cursor().execute(delctx) db.cursor().execute(delhkindex) result = db.cursor().fetchall() return result except(AttributeError, TypeError) as e: if hou.isUIAvailable(): hou.ui.setStatusMessage( (la.DBERRORMSG['cleardatabase'] + str(e)), severity=hou.severityType.Warning) else: print(la.DBERRORMSG['cleardatabase'] + str(e))
def _doCreate( nodeType, name, className, version=None, envVarName=None, parent=None, contextArgs={} ) : if hou.isUIAvailable() and contextArgs.get( "toolname", "" ) : holder = toolutils.genericTool( contextArgs, nodeType, nodename = name ) else : parent = parent if parent else hou.node( "/obj" ).createNode( "geo", node_name=name, run_init_scripts=False ) holder = parent.createNode( nodeType, node_name=name ) IECoreHoudini.FnParameterisedHolder( holder ).setParameterised( className, version, envVarName ) if contextArgs.get( "shiftclick", False ) : converter = holder.parent().createNode( "ieCortexConverter", node_name = holder.name()+"Converter" ) outputNode = hou.node( contextArgs.get( "outputnodename", "" ) ) toolutils.connectInputsAndOutputs( converter, False, holder, outputNode, 0, 0 ) x, y = holder.position() converter.setPosition( [x,y-1] ) return holder
def createdefaults(platform): def_set = util.DEFAULT_SETTINGS def_set[util.SETTINGS_KEYS[1]] = str(defaultdbpath) if platform == "unix": def_set[util.SETTINGS_KEYS[8]] = True settingsdata.beginGroup('Searcher') try: for i in range(len(util.SETTINGS_KEYS)): settingsdata.setValue(util.SETTINGS_KEYS[i], def_set[util.SETTINGS_KEYS[i]]) except (AttributeError, TypeError) as e: if hou.isUIAvailable(): hou.ui.setStatusMessage( (la.SETTINGSMESSAGES['createdefaults'] + str(e)), severity=hou.severityType.Warning) else: print(la.SETTINGSMESSAGES['createdefaults'] + str(e)) settingsdata.endGroup() settingsdata.setIniCodec('UTF-8') settingsdata.sync()
def classic_startup(): # use inspect to get the current file path since attempts to access # __file__ result in a NameError. current_file_path = os.path.abspath( inspect.getsourcefile(lambda: 0) ) # construct the path to the engine's python directory and add it to sys # path. this provides us access to the bootstrap module which contains # helper methods for constructing the proper environment based on the # bootstrap scanario. For this file, the python directory is 3 levels up. tk_houdini_python_path = \ os.path.abspath( os.path.join( current_file_path, "..", "..", "..", "python", ) ) # add to the system path sys.path.insert(0, tk_houdini_python_path) # now that the path is there, we can import the classic bootstrap logic try: from tk_houdini import bootstrap bootstrap.bootstrap_classic() except Exception, e: import traceback stack_trace = traceback.format_exc() message = "Shotgun Toolkit Error: %s" % (e,) details = "Error stack trace:\n\n%s" % (stack_trace) import hou if hou.isUIAvailable(): hou.ui.displayMessage(message, details=details) else: print message print details
def newPublicCollection(cls,username=None, altparent=None): data = GithubAuthorizator.readAuthorizationsFile() if(username is not None): if(isinstance(username,dict)):username=username['user'] newitem={'user':username} data['publiccollections'].append(newitem) cls.writeAuthorizationFile(data) return True if(hou.isUIAvailable()): btn, username = hou.ui.readInput('public collection name', buttons=('Ok','Cancel'), close_choice=1) else: username, btn = QInputDialog.getText(altparent,'enter name', 'public collection name') btn=1-int(btn) if(btn!=0):return False data['publiccollections'] = filter(lambda x: x['user'] != username, data['publiccollections']) data['publiccollections'].append({'user':username}) cls.writeAuthorizationFile(data) return True
def bootstrap_exception(error_msg): """ Shows an error message if there is a problem during bootstrap. """ # this file can be imported before houdini is up and running, but this # method should only be called during a houdini session import hou # get a full stack trace details = traceback.format_exc() if hou.isUIAvailable(): # we have a UI, show the error in a popup dialog hou.ui.displayMessage(error_msg, details=details) else: # no UI, just print to stdout print error_msg print details
def plugin_startup(): # construct the path to the plugin root's folder. # plugins/basic/python2.Xlibs/pythonrc.py # -------------| # this part ^ # use inspect to get the current file path since attempts to access # __file__ result in a NameError. current_file_path = os.path.abspath( inspect.getsourcefile(lambda: 0) ) current_dir_path = os.path.dirname(current_file_path) plugin_root_path = os.path.dirname(current_dir_path) # the plugin python path will be just below the root level. add it to # sys.path plugin_python_path = os.path.join(plugin_root_path, "python") sys.path.insert(0, plugin_python_path) # now that the path is there, we can import the plugin bootstrap logic try: from tk_houdini_basic import plugin_bootstrap plugin_bootstrap.bootstrap(plugin_root_path) except Exception, e: import traceback stack_trace = traceback.format_exc() message = "Shotgun Toolkit Error: %s" % (e,) details = "Error stack trace:\n\n%s" % (stack_trace) import hou if hou.isUIAvailable(): hou.ui.displayMessage(message, details=details) else: print message print details
def get_camera(self): """ Get camera on the scene or from HRST. """ rfxcam = None cam = None #Get camera from current view port. if hou.isUIAvailable(): d = hou.ui.curDesktop() viewport = d.paneTabOfType(hou.paneTabType.SceneViewer).curViewport() cam = viewport.camera() if not cam: #Get the first rfxcam for abcCam in rfxAbcCamera.find_all(): cam = abcCam break if cam and cam.parent() and rfxAbcCamera.is_rfx_abc_camera(cam.parent()): cam = cam.parent() if not cam: #Get any camera from the scene. cam = [c for c in hou.node('/').allSubChildren() if c.type().name() == 'cam'] if cam: cam = cam[0] #If there is no camera in the scene, Create one from current posititon. if not cam: cam = hou.node('/obj').createNode('cam', 'cam1') if isinstance(cam, str): cam = hou.node(cam) return cam
def createParm( p, folders=None, parent=None, top_level=False ): parm = None results = [] if not folders: folders = [] # Compound Parameter if p.isInstanceOf( IECore.TypeId.CompoundParameter ) : if top_level==True: # this is our top-level CompoundParameter sub_folder = ['Parameters'] name = None else: label = parmLabel( p ) sub_folder = folders + [label] name = parmName( p.name, prefix=parent ) # recurse through children for child in p.values(): results += createParm( child, sub_folder, parent=name ) # int if p.typeId()==IECore.TypeId.IntParameter: parm = IECoreHoudini.ParmTemplates.intParm( p, parent=parent ) if p.typeId()==IECore.TypeId.V2iParameter: parm = IECoreHoudini.ParmTemplates.intParm( p, 2, parent=parent ) if p.typeId()==IECore.TypeId.V3iParameter: parm = IECoreHoudini.ParmTemplates.intParm( p, 3, parent=parent ) # float, V2f, V3f if p.typeId()==IECore.TypeId.FloatParameter: parm = IECoreHoudini.ParmTemplates.floatParm( p, parent=parent ) if p.typeId()==IECore.TypeId.V2fParameter: parm = IECoreHoudini.ParmTemplates.floatParm( p, 2, parent=parent ) if p.typeId()==IECore.TypeId.V3fParameter: parm = IECoreHoudini.ParmTemplates.floatParm( p, 3, parent=parent ) # double if p.typeId()==IECore.TypeId.DoubleParameter: parm = IECoreHoudini.ParmTemplates.floatParm( p, parent=parent ) if p.typeId()==IECore.TypeId.V2dParameter: parm = IECoreHoudini.ParmTemplates.floatParm( p, 2, parent=parent ) if p.typeId()==IECore.TypeId.V3dParameter: parm = IECoreHoudini.ParmTemplates.floatParm( p, 3, parent=parent ) # bool if p.typeId()==IECore.TypeId.BoolParameter: parm = IECoreHoudini.ParmTemplates.boolParm( p, parent=parent ) # string if p.typeId()==IECore.TypeId.StringParameter: parm = IECoreHoudini.ParmTemplates.stringParm( p, parent=parent ) # validated string if p.typeId()==IECore.TypeId.ValidatedStringParameter: parm = IECoreHoudini.ParmTemplates.stringParm( p, parent=parent ) # path, dirname, filename, filesequence if p.typeId()==IECore.TypeId.PathParameter: parm = IECoreHoudini.ParmTemplates.pathParm( p, parent=parent ) if p.typeId()==IECore.TypeId.DirNameParameter: parm = IECoreHoudini.ParmTemplates.pathParm( p, parent=parent ) if p.typeId()==IECore.TypeId.FileNameParameter: parm = IECoreHoudini.ParmTemplates.pathParm( p, parent=parent ) if p.typeId()==IECore.TypeId.FileSequenceParameter: parm = IECoreHoudini.ParmTemplates.pathParm( p, parent=parent ) # frame list if p.typeId()==IECore.TypeId.FrameListParameter: parm = IECoreHoudini.ParmTemplates.stringParm( p, parent=parent ) # color3f if p.typeId()==IECore.TypeId.Color3fParameter: parm = IECoreHoudini.ParmTemplates.colParm( p, 3, parent=parent ) # color4f if p.typeId()==IECore.TypeId.Color4fParameter: parm = IECoreHoudini.ParmTemplates.colParm( p, 4, parent=parent ) # M44f, M44d if p.typeId()==IECore.TypeId.M44fParameter: parm = IECoreHoudini.ParmTemplates.matrixParm( p, parent=parent ) if p.typeId()==IECore.TypeId.M44dParameter: parm = IECoreHoudini.ParmTemplates.matrixParm( p, parent=parent ) # Box2i, Box2f, Box2d if p.typeId()==IECore.TypeId.Box2iParameter: parm = IECoreHoudini.ParmTemplates.boxParmInt( p, 2, parent=parent ) if p.typeId()==IECore.TypeId.Box2fParameter: parm = IECoreHoudini.ParmTemplates.boxParmFloat( p, 2, parent=parent ) if p.typeId()==IECore.TypeId.Box2dParameter: parm = IECoreHoudini.ParmTemplates.boxParmFloat( p, 2, parent=parent ) # Box3i, Box3f, Box3d if p.typeId()==IECore.TypeId.Box3iParameter: parm = IECoreHoudini.ParmTemplates.boxParmInt( p, 3, parent=parent ) if p.typeId()==IECore.TypeId.Box3fParameter: parm = IECoreHoudini.ParmTemplates.boxParmFloat( p, 3, parent=parent ) if p.typeId()==IECore.TypeId.Box3dParameter: parm = IECoreHoudini.ParmTemplates.boxParmFloat( p, 3, parent=parent ) if p.isInstanceOf( IECore.TypeId.ObjectParameter ) : # input connection parameter, may need to add conversion parameters if set(p.validTypes()).intersection( set(IECoreHoudini.FromHoudiniGeometryConverter.supportedTypes()) ) : converter = IECoreHoudini.FromHoudiniGeometryConverter.createDummy( p.validTypes() ) sub_folder = folders + [ parmLabel( p ) ] name = parmName( p.name, prefix=parent ) ## \todo: set joinWithNext with userData if hou.ParmTemplate.setJoinWithNext() starts working useNameFilterParm = IECore.BoolParameter( "useNameFilter", "Enables the nameFilter", True ) results += createParm( useNameFilterParm, sub_folder, parent=name ) useNameTuple = results[-1]["tuple"] nameFilterParm = IECore.StringParameter( "nameFilter", "A list of named shapes to convert. Uses Houdini matching syntax.", "*", userData = { "houdini" : { "disableWhen" : IECore.StringData( "{ %s == 0 }" % useNameTuple.name() ) } } ) results += createParm( nameFilterParm, sub_folder, parent=name ) for child in converter.parameters().values() : results += createParm( child, sub_folder, parent=name ) if parm: with IECore.IgnoredExceptions( KeyError ) : parm['tuple'].hide( not bool(p.userData()["UI"]['visible'].value) ) with IECore.IgnoredExceptions( KeyError ) : parm['tuple'].setDisableWhen( p.userData()["houdini"]['disableWhen'].value ) # add our list of parent folders parm['folder'] = folders parm['cortex_name'] = p.name # add to our list of results results.append(parm) # certain parameter types are ok to ignore ignoredParameterTypes = ( IECore.CompoundParameter, IECore.ObjectParameter, IECoreScene.PrimitiveParameter, IECoreScene.GroupParameter, ) if not parm and not isinstance( p, ignoredParameterTypes ) : msg = "IECoreHoudini does not currently support parameters of type " + p.typeName() # hbatch/hython don't support ui.setStatusMessage() ## \todo: remove this if the Houdini load errors stop masking the IECore warnings if hou.isUIAvailable() : hou.ui.setStatusMessage( msg, hou.severityType.Warning ) IECore.warning( msg ) # our parent folder list return results
import sys import hou def start_clippy_thread(): clippy_dir = '/path/to/clippy' if clippy_dir not in sys.path: sys.path.append(clippy_dir) try: import clippy_hou clippy_hou.ClippyForHoudini.start_clippy_timer() except Exception: pass if hou.isUIAvailable(): start_clippy_thread()
def error(msg): if hou.isUIAvailable(): hou.ui.displayMessage(msg) else: print msg
def do_crash_recovery(calledFromUI=False): tmpdir = str( hou.getenv("TEMP") or hou.getenv("HOUDINI_TEMP_DIR") ) files = glob.glob( os.path.join(tmpdir, '*.hip') ) uicall = calledFromUI if hou.isUIAvailable() and len(files)>0: td = os.path.join(tmpdir, '') # dir with '/' files = [ (f, os.path.getmtime(f), ) for f in files ] files = sorted(files, key=lambda f: f[1], reverse=True) files = [ str(re.sub('^%s' % td, '', f[0])) for f in files ] sel = hou.ui.selectFromList(files, exclusive=True, title="Crash Recovery", message="Select .hip File to Recover") recovered = False if len(sel)>0: f = files[sel[0]] fn = os.path.join(tmpdir, f) # extract HIPNAME f = re.sub('^crash.', '', f) f = re.sub('\..+_[0-9]+\.hip', '.hip', f) # do recovery try: hou.hipFile.clear(True) hou.hipFile.load(fn, True) hou.setUpdateMode(hou.updateMode.Manual) recovered = True except: hou.ui.setStatusMessage("error while recovering file %s" % fn, hou.severityType.Error) print "ERROR: %s" % traceback.format_exc() hou.hipFile.setName(f) # delete crash file(s) msg = 'Cleanup: Delete all crash recovery hip files?' if recovered: msg = \ 'File recovered. Make sure to save it to a safe location.\n' \ 'NOTE: Update mode is set to "Manual" to avoid potential re-crashes.\n' \ '\n%s' % msg d = hou.ui.displayMessage(msg, buttons=("DELETE", "Skip", )) if d==0: files = \ glob.glob( os.path.join(tmpdir, 'crash.*') ) + \ glob.glob( os.path.join(tmpdir, '*.hip') ) for f in files: try: os.remove(f) except: pass hou.ui.setStatusMessage("crash recovery cleanup: deleted %d files" % len(files)) else: pass # user cancelled else: # no crash files found # if uicall: hou.ui.setStatusMessage(" Crash Recovery: No emergency-saved .hip file(s) found -- nothing to recover. (%s)" % tmpdir, hou.severityType.ImportantMessage) pass
def createParm( p, folders=None, parent=None, top_level=False ): parm = None results = [] if not folders: folders = [] # Compound Parameter if p.isInstanceOf( IECore.TypeId.CompoundParameter ) : if top_level==True: # this is our top-level CompoundParameter sub_folder = ['Parameters'] name = None else: label = parmLabel( p ) sub_folder = folders + [label] name = parmName( p.name, prefix=parent ) # recurse through children for child in p.values(): results += createParm( child, sub_folder, parent=name ) # int if p.typeId()==IECore.TypeId.IntParameter: parm = IECoreHoudini.ParmTemplates.intParm( p, parent=parent ) if p.typeId()==IECore.TypeId.V2iParameter: parm = IECoreHoudini.ParmTemplates.intParm( p, 2, parent=parent ) if p.typeId()==IECore.TypeId.V3iParameter: parm = IECoreHoudini.ParmTemplates.intParm( p, 3, parent=parent ) # float, V2f, V3f if p.typeId()==IECore.TypeId.FloatParameter: parm = IECoreHoudini.ParmTemplates.floatParm( p, parent=parent ) if p.typeId()==IECore.TypeId.V2fParameter: parm = IECoreHoudini.ParmTemplates.floatParm( p, 2, parent=parent ) if p.typeId()==IECore.TypeId.V3fParameter: parm = IECoreHoudini.ParmTemplates.floatParm( p, 3, parent=parent ) # double if p.typeId()==IECore.TypeId.DoubleParameter: parm = IECoreHoudini.ParmTemplates.floatParm( p, parent=parent ) if p.typeId()==IECore.TypeId.V2dParameter: parm = IECoreHoudini.ParmTemplates.floatParm( p, 2, parent=parent ) if p.typeId()==IECore.TypeId.V3dParameter: parm = IECoreHoudini.ParmTemplates.floatParm( p, 3, parent=parent ) # bool if p.typeId()==IECore.TypeId.BoolParameter: parm = IECoreHoudini.ParmTemplates.boolParm( p, parent=parent ) # string if p.typeId()==IECore.TypeId.StringParameter: parm = IECoreHoudini.ParmTemplates.stringParm( p, parent=parent ) # validated string if p.typeId()==IECore.TypeId.ValidatedStringParameter: parm = IECoreHoudini.ParmTemplates.stringParm( p, parent=parent ) # path, dirname, filename, filesequence if p.typeId()==IECore.TypeId.PathParameter: parm = IECoreHoudini.ParmTemplates.pathParm( p, parent=parent ) if p.typeId()==IECore.TypeId.DirNameParameter: parm = IECoreHoudini.ParmTemplates.pathParm( p, parent=parent ) if p.typeId()==IECore.TypeId.FileNameParameter: parm = IECoreHoudini.ParmTemplates.pathParm( p, parent=parent ) if p.typeId()==IECore.TypeId.FileSequenceParameter: parm = IECoreHoudini.ParmTemplates.pathParm( p, parent=parent ) # frame list if p.typeId()==IECore.TypeId.FrameListParameter: parm = IECoreHoudini.ParmTemplates.stringParm( p, parent=parent ) # color3f if p.typeId()==IECore.TypeId.Color3fParameter: parm = IECoreHoudini.ParmTemplates.colParm( p, 3, parent=parent ) # color4f if p.typeId()==IECore.TypeId.Color4fParameter: parm = IECoreHoudini.ParmTemplates.colParm( p, 4, parent=parent ) # M44f, M44d if p.typeId()==IECore.TypeId.M44fParameter: parm = IECoreHoudini.ParmTemplates.matrixParm( p, parent=parent ) if p.typeId()==IECore.TypeId.M44dParameter: parm = IECoreHoudini.ParmTemplates.matrixParm( p, parent=parent ) # Box2i, Box2f, Box2d if p.typeId()==IECore.TypeId.Box2iParameter: parm = IECoreHoudini.ParmTemplates.boxParmInt( p, 2, parent=parent ) if p.typeId()==IECore.TypeId.Box2fParameter: parm = IECoreHoudini.ParmTemplates.boxParmFloat( p, 2, parent=parent ) if p.typeId()==IECore.TypeId.Box2dParameter: parm = IECoreHoudini.ParmTemplates.boxParmFloat( p, 2, parent=parent ) # Box3i, Box3f, Box3d if p.typeId()==IECore.TypeId.Box3iParameter: parm = IECoreHoudini.ParmTemplates.boxParmInt( p, 3, parent=parent ) if p.typeId()==IECore.TypeId.Box3fParameter: parm = IECoreHoudini.ParmTemplates.boxParmFloat( p, 3, parent=parent ) if p.typeId()==IECore.TypeId.Box3dParameter: parm = IECoreHoudini.ParmTemplates.boxParmFloat( p, 3, parent=parent ) if p.isInstanceOf( IECore.TypeId.ObjectParameter ) : # input connection parameter, may need to add conversion parameters if set(p.validTypes()).intersection( set(IECoreHoudini.FromHoudiniGeometryConverter.supportedTypes()) ) : converter = IECoreHoudini.FromHoudiniGeometryConverter.createDummy( p.validTypes() ) sub_folder = folders + [ parmLabel( p ) ] name = parmName( p.name, prefix=parent ) for child in converter.parameters().values() : results += createParm( child, sub_folder, parent=name ) if parm: # is this parameter hidden? do_hide = False if 'UI' in p.userData() and 'visible' in p.userData()['UI']: do_hide = not bool(p.userData()['UI']['visible'].value) parm['tuple'].hide( do_hide ) # add our list of parent folders parm['folder'] = folders parm['cortex_name'] = p.name # add to our list of results results.append(parm) # certain parameter types are ok to ignore ignoredParameterTypes = ( IECore.CompoundParameter, IECore.ObjectParameter, IECore.PrimitiveParameter, IECore.GroupParameter, ) if not parm and not isinstance( p, ignoredParameterTypes ) : msg = "IECoreHoudini does not currently support parameters of type " + p.typeName() # hbatch/hython don't support ui.setStatusMessage() ## \todo: remove this if the Houdini load errors stop masking the IECore warnings if hou.isUIAvailable() : hou.ui.setStatusMessage( msg, hou.severityType.Warning ) IECore.warning( msg ) # our parent folder list return results
def classic_startup(): # use inspect to get the current file path since attempts to access # __file__ result in a NameError. current_file_path = os.path.abspath( inspect.getsourcefile(lambda: 0) ) # construct the path to the engine's python directory and add it to sys # path. this provides us access to the bootstrap module which contains # helper methods for constructing the proper environment based on the # bootstrap scanario. For this file, the python directory is 3 levels up. tk_houdini_python_path = \ os.path.abspath( os.path.join( current_file_path, "..", "..", "..", "python", ) ) # add to the system path sys.path.insert(0, tk_houdini_python_path) # We need to check to make sure we don't have an incompatibility # between httplib and Houdini's bundled ssl.py. This is a problem # on some Linux distros (CentOS 7.x) with H16. We also then had to # package the urllib2 library that is compatible with our bundled # httplib. if sys.platform.startswith("linux") and sys.version.startswith("2.7.5"): # We can check to see if ssl has the function we know that # system httplib is likely to require. If it doesn't have it, # then we need to force the use of our bundled httplib before # we let the bootstrap happen. import ssl if not hasattr(ssl, "_create_default_https_context"): # Clear httplib if it's already been imported. if "httplib" in sys.modules: del sys.modules["httplib"] if "urllib2" in sys.modules: del sys.modules["urllib2"] # Add the submodule containing httplib to sys.path so that # the next time it's imported it'll come from there instead # of the system Python install. packages_path = os.path.join(tk_houdini_python_path, "packages") sys.path.insert(0, packages_path) # now that the path is there, we can import the classic bootstrap logic try: from tk_houdini import bootstrap bootstrap.bootstrap_classic() except Exception, e: import traceback stack_trace = traceback.format_exc() message = "Shotgun Toolkit Error: %s" % (e,) details = "Error stack trace:\n\n%s" % (stack_trace) import hou if hou.isUIAvailable(): hou.ui.displayMessage(message, details=details) else: print message print details
def statmsg(msg, warn=False): '''.''' s = hou.severityType.Warning if warn else hou.severityType.Message if hou.isUIAvailable(): hou.ui.setStatusMessage(msg, severity=s)