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
def expand_string_for_rop(rop_node, string_value): """ Expands a string that contains tokens such as $OS which depend on being evaluated with respect to a specific node Args: rop_node (hou.Node): A Houdini node to evaluate this string with respect to string_value (str): The string to expand Returns: String: The expanded string """ cur_pwd_node = hou.pwd() hou.cd(rop_node.path()) result = hou.expandString(string_value) hou.cd(cur_pwd_node.path()) return result
def sim_cache_delete_playrange(): dopnet, cache_on, cache_name, cache_substeps, cache_start, cache_spacing = sim_dopnet( ) hou.cd(dopnet.path()) # to expandString() correctly list_sf, list_f = sim_cache_framelists() index = 1 + sim_cache_precedent_index(hou.playbar.playbackRange()[0]) candidate_frames = list_sf[index:] # try to delete the files, if they exist for frame in candidate_frames: file_path = cache_name.replace("$SF", str(frame)) file_path = hou.expandString(file_path) file_path = file_path.replace("*", "_") if file_path.endswith(".sim"): try: os.remove(file_path) except: frame_was_not_cached = 1
def create_alembic_single(paths): node = hou.node("/obj") hou.cd("/obj") pos_y = 0 for key, value in paths.items(): # Create Geo node pwd = hou.pwd().createNode("geo", node_name=key) pos_y += 1 pwd.setPosition([2, pos_y]) hou.cd("/obj/" + str(pwd)) pwd.setColor(hou.Color(0, 0, 0)) # Create alembic node alembic = hou.pwd().createNode("alembic") alembic.setName(key) # Set parameters alembic.setParms({"fileName": value, "curveFilter": 0, "NURBSFilter": 0}) # Create Out node transform = alembic.createOutputNode("xform", node_name="ScaleSmaller") transform.parm("scale").set(0.01) out = transform.createOutputNode("null", node_name="OUT") out.setDisplayFlag(True) out.setRenderFlag(True) hou.cd("/obj") hou.ui.displayMessage("Creating a successful", ["Ok"])
def create_alembic_archive(paths): node = hou.node("/obj") hou.cd("/obj") pos_x = 0 pos_y = 5 for key, value in paths.items(): # Create Geo node pwd = hou.pwd().createNode("alembicarchive", node_name=key) pwd.parm("fileName").set(value) pwd.setName(key) # kwargs['node'].hdaModule().BuildHierarchyRoot(kwargs['node']) pwd.parm('buildHierarchy').pressButton() pwd.setColor(hou.Color(0, 0, 0)) pwd.setPosition([pos_x, pos_y]) pos_x += 2.2 parnul = pwd.createInputNode(0, "null", "Scale") parnul.parm("scale").set(0.01) parnul.setColor(hou.Color(0, 0, 0)) _tree(pwd) hou.ui.displayMessage("Creating a successful", ["Ok"])
# *_*coding:utf-8 *_* import hou import json with open("dir.json") as file: dict_all = json.loads(file.read()) obj = hou.node("/obj") #创建摄像机并导入摄像机数据 camera_alembic = obj.createNode("alembicarchive") file_name = camera_alembic.parm("fileName") file_name.set(dict_all["layout"]) buildHierarchy = camera_alembic.parm("buildHierarchy") buildHierarchy.pressButton() hou.cd("/obj/alembicarchive1/camera1/") cameraShape = hou.node("cameraShape1") reslution = cameraShape.parmTuple("res") reslution.set((int(dict_all["camera_resultion_wight"]), int(dict_all["camera_resultion_hight"]))) #创建geo节点 obj.createNode("geo") hou.cd("/obj/geo1") pwd = hou.pwd() file1 = hou.node("./file1") file1.destroy() alembic = pwd.createNode("alembic") file_name = alembic.parm("fileName") file_name.set(dict_all["animation"]) if dict_all["animation"] == []: alembic.bypass(1) else: pass
def houDir(): currentDirectory = hou.hscript("oppwf()")[0][:-1] commandPrompt = str(currentDirectory) + " -> " hou.hscript("prompt '`strcat(oppwf(), \" -> \")`'") hou.cd(currentDirectory)
objectFile = GetAbsoluteFileName("Select Object File", "*.obj", hou.fileType.Geometry) if (objectFile == None): sys.exit() bakeFile = GetAbsoluteFileName("Select Bake File", "*.xml", hou.fileType.Any) if (bakeFile == None): sys.exit() ## @brief baseName is used to store the prefix name used for all created nodes baseName = hou.ui.readInput("Enter Base Node Name") ## @brief we now copy this to a new string baseName = baseName[1] ## @brief scene is used to store a reference to the scene when we change to the scene level scene = hou.cd("/scene") ## @brief create our geo node and then attache the correct file to it. geo = hou.node("/obj").createNode("geo") geo.setName("%sObjectImport" % (baseName)) ## @brief grab our file node so we can set the correct file name file = hou.node('/obj/%sObjectImport/file1' % (baseName)) file.parm("file").set(objectFile) ## @brief now create a chopnet for this geo and attach the channel chopnet = geo.createNode("chopnet") chopnet.setName("%sBakeChannel" % (baseName)) ## @brief now we create our channel in the chop net this will be modified by the parser channel = chopnet.createNode("channel") ## @brief due to the way the data is created we need to have a re-name node to change the format rename = chopnet.createNode("rename") rename.parm("renamefrom").set("?[xyz]") rename.parm("renameto").set("t[xyz]0")
def update_rop_output_paths_for_selected_nodes(self, kwargs={}): print "Update Rop Output Paths for Selected SOP/TOP Nodes. Note: currently not handling @attributes $attributes in element names correctly." self.selected_nodes = kwargs['items'] for node in self.selected_nodes: print 'Name', node.name() if node.type().name() == 'ropfetch': node = node.node(node.parm('roppath').eval()) if node: print 'set path', node.path() #hou.hscriptExpression("cd "+node.path()) hou.cd(node.path()) bake_names = True print "evaluate env vars" if bake_names: node_name = node.name() show_var = hou.hscriptExpression("${SHOW}") seq_var = hou.hscriptExpression("${SEQ}") shot_var = hou.hscriptExpression("${SHOT}") shot_var = show_var + '.' + seq_var + '.' + shot_var shotpath_var = hou.hscriptExpression("${SHOTPATH}") scene_name = hou.hscriptExpression("${SCENENAME}") else: node_name = "${OS}" show_var = "${SHOW}" seq_var = "${SEQ}" shot_var = "${SHOT}" shot_var = "${SHOW}.${SEQ}.${SHOT}" shotpath_var = "${SHOTPATH}" scene_name = "${SCENENAME}" print shot_var scene_name_default = scene_name shot_default = shot_var file_template_default = "`chs('shot_path')`/`chs('output_type')`/`chs('element_name')`/`chs('versionstr')`/`chs('shot')`.`chs('scene_name')`.`chs('element_name')`.`chs('versionstr')`.`chs('wedge_string')`.`chs('frame')`.`chs('file_type')`" # If target matches node typ in dict, then apply versioning print 'node type', node.type().name() if node.type().name() in self.output_types: lookup = self.output_types[node.type().name()] extension = lookup['extension'] print 'extension', extension static_expression = lookup['static_expression'] out_parm_name = lookup['output'] # check if overide for default file_template = file_template_default if 'file_template' in lookup: print "overiding file tempalte" file_template = lookup['file_template'] print "file_template", file_template try: parm_group = node.parmTemplateGroup() parm_folder = hou.FolderParmTemplate( "folder", "Versioning") callback_expr = \ """ # This allows versioning to be inherited by the multi parm db import hou node = hou.pwd() parm = hou.evaluatingParm() print 'parm callback', parm.name() """ parm_folder.setScriptCallbackLanguage( hou.scriptLanguage.Python) parm_folder.setScriptCallback(callback_expr) #parm_folder.addParmTemplate(hou.StringParmTemplate("element_name_template", "Element Name Template", 1, ["${OS}"])) parm_folder.addParmTemplate( hou.StringParmTemplate("element_name_template", "Element Name Template", 1, ["${OS}"])) element_name_parm = hou.StringParmTemplate( "element_name", "Element Name", 1, [node_name]) #elementName.setScriptCallback(callback_expr) #elementName.setScriptCallbackLanguage(hou.scriptLanguage.Python) parm_folder.addParmTemplate(element_name_parm) parm_folder.addParmTemplate( hou.ToggleParmTemplate( "auto_version", "Auto Version Set To Hip Version on Execute", 1)) parm_folder.addParmTemplate( hou.IntParmTemplate("version_int", "Version", 1)) parm_folder.addParmTemplate( hou.StringParmTemplate("versionstr", "Version String", 1, [""])) parm_folder.addParmTemplate( hou.StringParmTemplate("wedge_string", "Wedge String", 1, ["w`@wedgenum`"])) parm_folder.addParmTemplate( hou.StringParmTemplate("output_type", "Output Type", 1, [lookup['type_path']])) parm_folder.addParmTemplate( hou.StringParmTemplate("shot", "Shot", 1, [shot_default])) parm_folder.addParmTemplate( hou.MenuParmTemplate( 'location', 'Location', ("submission_location", "cloud", "onsite"), ("Submission Location", "Cloud", "Onsite"), default_value=0)) # parm_folder.addParmTemplate(hou.MenuParmTemplate("location", "Location", menu_items=(["submission_location","cloud","onsite"]), menu_labels=(["Submission Location","Cloud","Onsite"]), default_value=0, icon_names=([]), item_generator_script="", item_generator_script_language=hou.scriptLanguage.Python, menu_type=hou.menuType.Normal, menu_use_token=False, is_button_strip=False, strip_uses_icons=False) parm_folder.addParmTemplate( hou.StringParmTemplate("shot_path_template", "Shot Path Template", 1, ["${SHOTPATH}"])) parm_folder.addParmTemplate( hou.StringParmTemplate("shot_path", "Shot Path", 1, [shotpath_var])) parm_folder.addParmTemplate( hou.StringParmTemplate("scene_name", "Scene Name", 1, [scene_name_default])) # default_expression=("hou.frame()"), default_expression_language=(hou.scriptLanguage.Python) ) ) parm_folder.addParmTemplate( hou.StringParmTemplate("frame", "Frame", 1, ["$F4"])) parm_folder.addParmTemplate( hou.StringParmTemplate("file_type", "File Type", 1, [extension])) parm_folder.addParmTemplate( hou.StringParmTemplate("file_template", "File Template", 1, [file_template])) #parm_folder.addParmTemplate(hou.FloatParmTemplate("amp", "Amp", 2)) parm_group.append(parm_folder) node.setParmTemplateGroup(parm_group) hou_parm = node.parm("versionstr") hou_parm.lock(False) hou_parm.setAutoscope(False) hou_keyframe = hou.StringKeyframe() hou_keyframe.setTime(0) ver_expr = \ """ # This allows versioning to be inherited by the multi parm db import hou import re node = hou.pwd() parm = hou.evaluatingParm() index_key = node.parm('index_key_template').eval() multiparm_index = node.userData('verdb_'+index_key) version = 0 if multiparm_index is not None: multiparm_index = str(multiparm_index) version_parm = node.parm('version'+multiparm_index) if version_parm is not None: version = version_parm.eval() return version """ hou_keyframe.setExpression(ver_expr, hou.exprLanguage.Python) hou_parm.setKeyframe(hou_keyframe) expr = \ """ import hou node = hou.pwd() lookup = {'submission_location':'$PROD_ROOT', 'cloud':'$PROD_CLOUD_ROOT', 'onsite':'$PROD_ONSITE_ROOT'} location = node.parm('location').evalAsString() root = lookup[location] template = root+'/$SHOW/$SEQ/$SHOT' return template """ hou_parm = node.parm("shot_path_template") hou_parm.lock(False) hou_parm.setAutoscope(False) hou_keyframe = hou.StringKeyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression(expr, hou.exprLanguage.Python) hou_parm.setKeyframe(hou_keyframe) parms_added = True except: parms_added = False if static_expression: hou_parm = node.parm("frame") hou_parm.lock(False) hou_parm.setAutoscope(False) hou_keyframe = hou.StringKeyframe() hou_keyframe.setTime(0) if 'overrides' in lookup and 'frame' in lookup[ 'overrides']: print 'has override for static_expression' hou_keyframe.setExpression( lookup['overrides']['frame'], hou.exprLanguage.Python) else: hou_keyframe.setExpression( "import hou" + '\n' + "node = hou.pwd()" + '\n' + "step = node.parm('f3').eval()" + '\n' + "if node.parm('trange').evalAsString() == 'off':" + '\n' + " value = 'static'" + '\n' + "elif step != 1:" + '\n' + " value = '$FF'" + '\n' + "else:" + '\n' + " value = '$F4'" + '\n' + "return value", hou.exprLanguage.Python) # if node.parm('framegeneration').evalAsString() == '0': hou_parm.setKeyframe(hou_keyframe) # set defaults here if parms already exist and changes are made node.parm("scene_name").set(scene_name_default) node.parm("shot").set(shot_default) element_name_template = node.parm( "element_name_template").evalAsString() try: shot_path_template = hou.expandString( node.parm("shot_path_template").evalAsString()) #element_name_template = node.parm("element_name_template").evalAsString() except: shot_path_template = shotpath_var node.parm('element_name').set(element_name_template) node.parm("shot_path").set(shot_path_template) node.parm('file_template').set(file_template) bake_template = False replace_env_vars_for_tops = True auto_version = node.parm("auto_version").eval() print 'auto_version', auto_version # if autoversion tickbox enabled, then update version to hip version on execute of tool. if node.parm("auto_version").eval(): set_version = int( hou.hscriptExpression('opdigits($VER)')) print 'set version', set_version node.parm("version_int").set(set_version) if bake_template: file_path_split = node.parm( 'file_template').unexpandedString() file_path_split = file_path_split.replace( "`chs('frame')`", "{{ frame }}") file_path_split = file_path_split.replace( "`chs('versionstr')`", "{{ versionstr }}") file_path_split = file_path_split.replace( "`chs('wedge_string')`", "{{ wedge_string }}") file_path_split = file_path_split.replace( "`chs('element_name')`", "{{ element_name }}") # expand any values that we do not wish to be dynamic. file_path = hou.expandString(file_path_split) try: file_path = file_path.replace( "{{ frame }}", node.parm('frame').unexpandedString()) except: file_path = file_path.replace( "{{ frame }}", node.parm('frame').eval()) file_path = file_path.replace("{{ versionstr }}", "`chs('versionstr')`") file_path = file_path.replace("{{ wedge_string }}", "`chs('wedge_string')`") file_path = file_path.replace("{{ element_name }}", "`chs('element_name')`") # overide, and use template else: file_path_split = node.parm( 'file_template').unexpandedString() file_path_split = file_path_split.replace( "`chs('frame')`", "{{ frame }}") file_path_split = file_path_split.replace( "`chs('element_name')`", "{{ element_name }}") file_path = file_path_split try: file_path = file_path.replace( "{{ frame }}", node.parm('frame').unexpandedString()) except: file_path = file_path.replace( "{{ frame }}", node.parm('frame').eval()) element_name = node.parm( 'element_name').unexpandedString() if replace_env_vars_for_tops: print 'replace environment vars in element name with @ lower case version attributes' env_var_matches = re.findall( r'\$\{.*?\}', element_name) print 'element_name', element_name print 'env_var_matches', env_var_matches ignore = ['${OS}'] for match in env_var_matches: if match not in ignore: replacement = match.strip('${}').lower() element_name = element_name.replace( match, '`@' + replacement + '`') else: print 'will preserve environment vars in element name' # we bake the element name into the path so that copy of a node will not break refs in the event of a duplicate node existing in the target network to copy to. # element name cannot be ${OS} because if it changes the reader will not function from the template parms schema. file_path = file_path.replace("{{ element_name }}", element_name) # We bake the full definition of the cached output string into the output file string, except for the frame variable, version and wedge which remains as hscript/chanel refs. # this provides a safe means for copying cache nodes into other scenes without breaking references. # references should be updated on write via a prerender script executing this function to ensure $VER is updated to a current value. print 'out path', file_path node.parm(out_parm_name).set(file_path) print "add defs" def update_index(node, index_int): index_key_parm_name = 'index_key' + str(index_int) #print "update node", node, 'index_int', index_int, 'index_key_parm_name', index_key_parm_name index_key_parm = node.parm(index_key_parm_name) #print 'update index from parm', index_key_parm index_key = index_key_parm.eval() #version = node.parm('version' + str(index_int) ).eval() node.setUserData('verdb_' + index_key, str(index_int)) #print "Changed parm index_key", index_key, "index_int", index_int # ensure parameter callbacks exists def parm_changed(node, event_type, **kwargs): print "parm changed" parm_tuple = kwargs['parm_tuple'] if parm_tuple is None: parm_warn = int( hou.node("/obj").cachedUserData( "parm_warn_disable") != '1') if parm_warn: hou.ui.displayMessage( "Too many parms were changed. callback hasn't been designed to handle this yet, changes may be needed in cloud_submit.py to handle this. see shell output" ) print "Too many parms were changed. callback hasn't been designed to handle this yet, changes may be needed in cloud_submit.py to handle this. see shell output. This warning will be displayed once for the current session." hou.node("/obj").setCachedUserData( 'parm_warn_disable', '1') print "node", node print "event_type", event_type print "parm_tuple", parm_tuple print "kwargs", kwargs else: name = parm_tuple.name() # if a key has changed is_multiparm = parm_tuple.isMultiParmInstance() if is_multiparm and 'index_key' in name: if len(parm_tuple.eval()) > 1: hou.ui.displayMessage( "multiple items in tuple, changes may be needed in cloud_submit.py to handle this" ) index_int = next(re.finditer(r'\d+$', name)).group(0) print 'index_key in name', name, 'update', index_int update_index(node, index_int) # if multiparm instance count has changed, update all and remove any missing. if 'versiondb0' in name: multiparm_count = parm_tuple.eval()[0] print "Total parms changed. validate and clean out old dict. total parms:", multiparm_count index_keys = [] for index_int in range( 1, int(multiparm_count) + 1): index_key_parm_name = 'index_key' + \ str(index_int) index_key_parm = node.parm( index_key_parm_name) print 'update', index_key_parm.name() index_key = index_key_parm.eval() index_keys.append('verdb_' + index_key) print 'update index', index_int, 'node', node update_index(node, index_int) # first all items in dict will be checked for existance on node. if they dont exist they will be destroyed on the dict. user_data_total = 0 keys_to_destroy = [] for index_key, value in node.userDataDict( ).items(): if index_key not in index_keys and 'verdb_' in index_key: print "node missing key", index_key, ":", value, 'will remove' keys_to_destroy.append(index_key) else: user_data_total += 1 if len(keys_to_destroy) > 0: for index_key in keys_to_destroy: node.destroyUserData(index_key) print "destroyed key", index_key # all lookups and validation needs to double check the data is correct. if incorrect, trigger cleanup. # if number of entries dont match, trigger cleanup. this can occur if a wedge is entered in as an index manually, and then altered. we locked parms to avoid this. # new indexes should be automated. # remove callback to replace #removeEventCallback((hou.nodeEventType.ParmTupleChanged, ), parm_changed) print "add callback" node.addEventCallback( (hou.nodeEventType.ParmTupleChanged, ), parm_changed)
import sys import hou hou.hipFile.load('D:/WORK/HOUDINI_16_playground/hython_test.hiplc') # hou.setFrame(101) hou.cd('/out') octaneRops = [] for child in hou.pwd().children(): if child.type().name() == 'Octane_ROP': octaneRops.append(child) print "octaneRops : " for i, rop in enumerate(octaneRops): print "\t",i, " : ",rop,"\n" userInput = raw_input("chose a Octane ROP Driver:") print userInput rop = hou.pwd().children()[int(userInput)] rTarget = hou.node(rop.parm("HO_renderTarget").evalAsString()) rTarget.parm("maxsamples").set(500) # disable mplay rendering rop.parm("HO_renderToMPlay").set(1)
import hou # 返回obj hou.cd('/obj') # 获取节点对象 obj = hou.node('/obj') # 创建节点 obj.createNode('geo') # 操作工作路径 hou.cd('/obj/geo1') # 创建节点 hou.pwd().createNode('box') hou.pwd().createNode('sphere') hou.pwd().createNode('merge') # 获取节点对象 box = hou.node('./box1') sphere = hou.node('./sphere1') merge = hou.node('./merge1') # 连接节点 merge.setFirstInput(box) merge.setNextInput(sphere)
import hou import os import json import toolutils jsonPath = os.path.dirname(__file__) with open("%s/dir.json" % jsonPath) as file: dict_all = json.loads(file.read()) obj = hou.node("/obj") #创建摄像机并导入摄像机数据 camera_alembic = obj.createNode("alembicarchive") file_name = camera_alembic.parm("fileName") file_name.set(dict_all["layout"]) buildHierarchy = camera_alembic.parm("buildHierarchy") buildHierarchy.pressButton() hou.cd("/obj/alembicarchive1/camera1/") cameraShape = hou.node("cameraShape1") reslution = cameraShape.parmTuple("res") reslution.set((int(dict_all["camera_resultion_wight"]), int(dict_all["camera_resultion_hight"]))) #创建资产alembic节点 if dict_all["assets"] != []: # 创建材质节点 hou.cd("/mat") matPwd = hou.node("/mat") bricksNode = matPwd.createNode("bricks") principledshaderNode = matPwd.createNode("principledshader::2.0") hou.cd("/obj") assetNode = hou.node("/obj") geometry = assetNode.createNode("geo") geometry.setName("assetGeometry")
try: print 'disable preview switch', node.path() parm = node.parm('preview_live') if parm: parm.set(0) except: print "didn't disable preview switch", node.path() for node in hou.selectedNodes(): print 'Name', node.name() if node.type().name() == 'ropfetch': node = node.node(node.parm('roppath').eval()) if node: print 'set path', node.path() #hou.hscriptExpression("cd "+node.path()) hou.cd(node.path()) bake_names = True print "evaluate env vars" if bake_names: node_name = node.name() show_var = hou.hscriptExpression("${SHOW}") seq_var = hou.hscriptExpression("${SEQ}") shot_var = hou.hscriptExpression("${SHOT}") shot_var = show_var + '.' + seq_var + '.' + shot_var shotpath_var = hou.hscriptExpression("${SHOTPATH}") scene_name = hou.hscriptExpression("${SCENENAME}") else: node_name = "${OS}"
def defGetRefParmPath(path): if path.startswith("`ch") or path.startswith("ch"): refPath = path.split("'")[0] refPathList = refPath.split('"')[1].split('/') refNode = hou.node("/".join(refPathList[:-1])) path = refNode.parm(refPathList[-1]).path() return path if path.startswith("`ch") or path.startswith("ch"): defGetRefParmPath(path) else: return path for node in hou.selectedNodes(): cd = hou.cd(node.path()) #print cd for p in node.parms(): try: try: oldValue = p.expression() except: oldValue = p.unexpandedString() except: oldValue = p.eval() #oldValue = p.unexpandedString() if type(oldValue) is not int and type(oldValue) is not float: try: if (oldValue.startswith("ch") or oldValue.startswith("`ch")) and "../" in oldValue: absPath = defGetRefParmPath(oldValue)