yashpolke

pythonScripts

Nov 21st, 2016
748
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 36.61 KB | None | 0 0
  1. Switch viz for subnet folders:
  2. node = hou.pwd()
  3. parent = node.parent()
  4.  
  5. return parent.evalParmTuple('folder0')[0]
  6.  
  7. ****************************************************************************************************************************
  8. Mantra prep for farm:
  9. import hou, houdini_nodes
  10.  
  11. def main():
  12.  
  13.     ### Query mantra nodes ###
  14.     #mantra_path = hou.ui.selectNode(relative_to_node=None, initial_node=None, node_type_filter=hou.nodeTypeFilter.Rop)
  15.  
  16.     list_rops = []
  17.     nodeType = houdini_nodes.get_best_node_type(hou.ropNodeTypeCategory(), 'mantra').name()
  18.  
  19.     for mantra_node in hou.node('/').allSubChildren():
  20.         if mantra_node.type().name() == nodeType:
  21.             list_rops.append(mantra_node)
  22.  
  23.     tree_nodes = {}
  24.     for i in list_rops:
  25.         tree_nodes[i.path()] = i.path()
  26.     choices = hou.ui.selectFromTree(tree_nodes.keys(), 'Select mantra nodes')
  27.  
  28.  
  29.     if len(choices) > 0:
  30.         ropDict = {}
  31.         for choice in choices:
  32.             ropDict[choice] = choice
  33.             mantra_path = ropDict.keys()[0]
  34.             mNode = hou.node(mantra_path)
  35.  
  36.         for item in ropDict.keys():
  37.             mNode = hou.node(item)
  38.  
  39.             ### Create dictionary of parms whcih need to be set to default ###
  40.             parms_dict = {'trange':0, 'f1':mNode.parm('f1').revertToDefaults(), 'f2':mNode.parm('f2').revertToDefaults(), 'f3':mNode.parm('f3').revertToDefaults(), 'camera':'/obj/cam_main_STEREO_CAMERA'}
  41.  
  42.             ### Set values on the mantra nodes ###
  43.             for key, value in parms_dict.items():
  44.                 mNode.setParms(parms_dict)
  45.     [mantra_rop.setColor(hou.Color([1, 0, 0])) for mantra_rop in list_rops
  46.      if mantra_rop.parm('forcelights').evalAsString() == '']
  47. **************************************************************************************************************************
  48. Match string and align nodes:
  49.  
  50.  
  51. node = hou.pwd()
  52. geo = node.geometry()
  53.  
  54. incr = hou.frame() * 0.0001
  55.  
  56. # Add code to modify contents of geo.
  57. # Use drop down menu to select examples.
  58.  
  59. #get position of points in viewport
  60. total_points = geo.points()
  61. pos = []
  62. for pt in total_points:
  63.     pos.append(pt.position())
  64.    
  65. #get list of all nodes to align
  66. nulls = []
  67. for i in hou.node('/obj/geo1').children():
  68.     if i.name().startswith('null'):
  69.         nulls.append(i)
  70.  
  71. #get current position of nodes in network view
  72. null_pos = []
  73. for null_node in hou.node('/obj/geo1').children():
  74.     if null_node.name().startswith('null'):
  75.         null_pos.append(null_node.position())
  76.  
  77. values = zip(nulls, pos, null_pos)
  78. for a in values:
  79.     node = a[0]
  80.     posx = a[1][0]
  81.     posy = a[1][1]
  82.     posbx = a[2][0]
  83.     posby = a[2][1]
  84.    
  85.     blendpx = hou.hscriptExpression('fit(@Frame, $RFSTART, $RFEND, {}, {})'.format(posbx, posx))
  86.     blendpy = hou.hscriptExpression('fit(@Frame, $RFSTART, $RFEND, {}, {})'.format(posby, posy))
  87.    
  88.     node.setPosition(hou.Vector2(blendpx, blendpy))
  89. ****************************************************************************************************************************
  90. Rotate nodes:
  91.  
  92. import math
  93.  
  94. #values
  95. theta1  = `chs('theta')`
  96. theta2  = `chs('s_theta')`
  97. r1     = `chs('radius')`
  98. r2     = `chs('s_radius')`
  99.  
  100. node = hou.pwd()
  101. geo = node.geometry()
  102.  
  103. # Add code to modify contents of geo.
  104. # Use drop down menu to select examples.
  105.  
  106. snode_pos = node.position()
  107. nnode = node.inputs()[0]
  108. nnode_pos = nnode.position()
  109.  
  110. center = snode_pos
  111. target = nnode_pos
  112.  
  113. frame = hou.frame()
  114. incr = frame * 0.001
  115.  
  116. mean_pos = (abs(snode_pos[0]-nnode_pos[0]), abs(snode_pos[1]-nnode_pos[1]))
  117.  
  118. #co-ordinates
  119. x1_pos = r1 * math.sin(theta1)
  120. y1_pos = r1 * math.cos(theta1)
  121.  
  122. x2_pos = r2 * math.sin(theta2)
  123. y2_pos = r2 * math.cos(theta2)
  124.  
  125. op1 = `ch('rotate_input')`
  126. op2 = `ch('rotate_self')`
  127. op3 = `ch('rotate_both')`
  128.  
  129. #set position
  130. if(op1 is 1):
  131.     nnode.setPosition(hou.Vector2(snode_pos[0] + x1_pos, snode_pos[1] + y1_pos))
  132.    
  133. if(op2 is 1):
  134.     node.setPosition(hou.Vector2(nnode_pos[0] + x1_pos, nnode_pos[1] + y1_pos))
  135.    
  136. if(op3 is 1):
  137.     nnode.setPosition(hou.Vector2(mean_pos[0] + x1_pos, mean_pos[1] + y1_pos))
  138.     node.setPosition(hou.Vector2(mean_pos[0] - x2_pos, mean_pos[1] - y2_pos))
  139.  
  140.  
  141. ****************************************************************************************************************************
  142. Pop-up parameters:
  143.  
  144. node = hou.node(hou.selectedNodes()[0].path())
  145. desktop = hou.ui.curDesktop();
  146. pane = desktop.createFloatingPane(hou.paneTabType.Parm);
  147. pane.setCurrentNode(node);
  148. pane.setPin(True);
  149. ****************************************************************************************************************************
  150. Create objectmerge node:
  151. import hou
  152. def main():
  153.     nodeType1   = 'object_merge'
  154.     nodeType2   = 'geo'
  155.     nodeTypeOut = 'dd::mantra::1'
  156.  
  157.     choose = hou.ui.displayMessage('Location', buttons=('SOP', 'OBJ'))
  158.    
  159. for node in hou.selectedNodes():
  160.         tmpName = node.name()
  161.         new_name = re.sub('OUT_', '', tmpName)
  162.         nodeName = new_name
  163.         geoName  = new_name
  164.         nodePath = node.path()
  165.         nodePos = node.position()
  166.         directory = node.path().split(node.name())[0]
  167.  
  168.         parentNode1 = hou.node(directory)
  169.         parentNode2 = hou.node('/obj')
  170.         parentNodePath = parentNode1.path()
  171.         parentNodePos = parentNode1.position()
  172.         parentOut     = hou.node('/out')
  173.  
  174.         if(choose == 0):
  175.             object_merge_node = createObjMergeNode(nodeType1, nodeName, parentNode1)
  176.             object_merge_node.setPosition(hou.Vector2(nodePos[0], nodePos[1]-1))
  177.             object_merge_node.setColor(hou.Color([0.188, 0.529, 0.459]))
  178.             object_merge_node.setParms({'objpath1':'{}'.format(nodePath)})
  179.             object_merge_node.setParms({'xformtype':1})
  180.         else:
  181.             render_node = createObjRenderNode(nodeType2, nodeName, parentNode2, parentNode1)
  182.             render_node.setPosition(hou.Vector2(parentNodePos[0], parentNodePos[1]-1))
  183.             render_node.setColor(hou.Color([0.322, 0.259, 0.58]))
  184.             #render_node.setName('RENDER_{}'.format(parentNode1.name()), unique_name=True)
  185.             parentNode3 = hou.node(render_node.path())
  186.             object_merge_node2 = createObjMergeNode2(nodeType1, nodeName, parentNode3)
  187.             object_merge_node2.setColor(hou.Color([0.188, 0.529, 0.459]))
  188.             object_merge_node2.setParms({'objpath1':'{}'.format(nodePath)})
  189.             object_merge_node2.setParms({'xformtype':1})
  190.  
  191.             ### create mantra node ###
  192.             mantra_node = createMantraNode(nodeTypeOut, new_name, parentOut)
  193.             mantra_node.parm('forceobject').set(render_node.name())
  194.             mantra_node.parm('vobject').set('')
  195.             mantra_node.parm('alights').set('')
  196.  
  197. def createObjMergeNode(nodeType1, nodeName, parentNode1):
  198.     object_merge_node = parentNode1.createNode(nodeType1)
  199.     object_merge_node.setName('IN_{}'.format(nodeName), unique_name=True)
  200.  
  201.     return object_merge_node
  202.  
  203.  
  204. def createObjRenderNode(nodeType2, nodeName, parentNode2, parentNode1):
  205.     render_node = parentNode2.createNode(nodeType2)
  206.     for child in render_node.allSubChildren():
  207.         child.destroy()
  208.     render_node.setName('RENDER_{}'.format(nodeName), unique_name=True)
  209.  
  210.     return render_node
  211.  
  212.  
  213. def createObjMergeNode2(nodeType1, nodeName, parentNode3):
  214.     object_merge_node2 = parentNode3.createNode(nodeType1)
  215.     object_merge_node2.setName('IN_{}'.format(nodeName), unique_name=True)
  216.  
  217.     return object_merge_node2
  218.  
  219. def createMantraNode(nodeTypeOut, new_name, parentOut):
  220.     mantra_node = parentOut.createNode(nodeTypeOut)
  221.     mantra_node.setName('{}'.format(new_name), unique_name=True)
  222.  
  223.  
  224. ***************************************************************************************************************************
  225.  
  226. Source scripts form disk:
  227.  
  228. import sys
  229. import traceback
  230.  
  231. try:
  232.     pythonScriptPath = '/home/yashp/Desktop/Scripts'
  233.     if not pythonScriptPath in sys.path:
  234.         sys.path.append(pythonScriptPath)
  235.     import create_merge_switch_yashp
  236.     create_merge_switch_yashp.main()
  237. except ImportError, e:
  238.     print "cannot import script"
  239. except Exception, e:
  240.     exc_type, exc_value, exc_traceback = sys.exc_info()
  241.     print "*** print_exception:"
  242.     traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stdout)
  243.  
  244. ****************************************************************************************************************************
  245. Connect Nodes:
  246.  
  247. import hou
  248. import math
  249. def main():
  250.    
  251.     limit = len(hou.selectedNodes())
  252.     yPos = []
  253.     for aNode in hou.selectedNodes():
  254.         yPos.append([aNode.position()[1], aNode])
  255.     yPos = sorted(yPos)
  256.     for i in xrange(len(yPos) - 1):
  257.         yPos[i][1].setInput(0,yPos[i+1][1])
  258.     xPos = []
  259.     for xNode in hou.selectedNodes():
  260.         xPos.append([xNode.position()[1], xNode])
  261.     xPos = sorted(xPos)
  262.  
  263. ****************************************************************************************************************************
  264.  
  265. Create Smoke Dops:
  266.  
  267. import hou
  268. import re
  269.  
  270. def main():
  271.     for node in hou.selectedNodes():
  272.         if hou.nodeTypeCategories().keys():
  273. ### Above function lets you call this function on any context ###
  274.             dir        = node.path().split(node.name())[0]
  275.             nodeName   = node.path().split('/')[-1]
  276.             parentNode = hou.node(dir)
  277.             nodeType1  = 'dopnet'
  278.             nodeType2  = 'dopio'
  279.             nodeType3  = 'bound'
  280.  
  281.             geo        = node.geometry()
  282.             condition0 = geo.prims()
  283.             condition1 = geo.containsPrimType('VDB')
  284.             condition2 = geo.containsPrimType('Volume')
  285.  
  286. #nodeName
  287.             dopnetName = hou.ui.readInput('Name the node', buttons=('OK', 'CANCEL'), initial_contents='')[1]
  288. #remove white spaces
  289. #            otherName  = 'DOPs_'+re.sub(r'\s+', '_', dopnetName)
  290. #remove special characters
  291. #otherName = re.sub('^[A-Za-z0-9]+]', '', rawOtherName)
  292.             if dopnetName != '':
  293.                 nodeName  = 'DOPs_{}'.format(dopnetName)
  294.                 nodeName2 = 'doi_{}'.format(dopnetName)
  295.                 nodeName3 = 'bounds_{}'.format(dopnetName)
  296.             else:
  297.                 nodeName  = 'DOPs_smoke'
  298.                 nodeName2 = 'doi_smoke'
  299.                 nodeName3 = 'bounds_smoke'
  300. #create dopnet regarless
  301.             dopnet     = createNode(nodeType1, nodeName, parentNode)
  302.             dop_io     = createNode(nodeType2, nodeName2, parentNode)
  303.             bounds     = createNode(nodeType3, nodeName3, parentNode)
  304.  
  305.             dopnetPath  = dopnet.path()
  306.             dop_io_path = dop_io.path()
  307.  
  308.             hou.hscript('oppresetload {} div_size'.format(dopnetPath))
  309.             for aNode in dopnet.children():
  310.                 aNode.destroy()
  311.             dopnet.setColor(hou.Color([0.576,0.208,0.475]))
  312.             dop_io.setColor(hou.Color([1, 0.725, 0]))
  313.  
  314.             dop_io.setParms({'doppath' : '{}'.format(dop_io.relativePathTo(dopnet))})
  315.             dop_io.setParms({'defobj' : 'smoke'})
  316.             dop_io.setParms({'presets' : '0'})
  317. ### Setting node position ###
  318.             selNodePos = node.position()
  319.  
  320.             dopnet.setPosition(hou.Vector2(selNodePos[0],selNodePos[1]-2))
  321.             dop_io.setPosition(hou.Vector2(selNodePos[0], selNodePos[1]-2.8))
  322.             bounds.setPosition(hou.Vector2(selNodePos[0]+1, selNodePos[1]-1))
  323.  
  324.             dopnet.setInput(0,node)
  325.             dopnet.setInput(1, bounds)
  326.             node.setSelected(False)
  327.  
  328.             bounds.setInput(0, node)
  329. #load preset based on type of entity
  330.             if(len(condition0) == 0):
  331. #                hou.hscript('oppresetload{}'.format(dopnet_particles_basic))
  332.                 smoke_object = hou.node('{}'.format(dopnetPath)).createNode('smokeobject', 'smoke')
  333.                 gas_resize   = hou.node('{}'.format(dopnetPath)).createNode('gasresizefluiddynamic', 'gasresizefluiddynamic')
  334.                 source_gpfd  = hou.node('{}'.format(dopnetPath)).createNode('gasparticletofield', 'density')
  335.                 source_gpft  = hou.node('{}'.format(dopnetPath)).createNode('gasparticletofield', 'temperature')
  336.                 source_gpfv  = hou.node('{}'.format(dopnetPath)).createNode('gasparticletofield', 'vel')
  337.                 merge        = hou.node('{}'.format(dopnetPath)).createNode('merge', 'merge')
  338.                 smoke_solver = hou.node('{}'.format(dopnetPath)).createNode('smokesolver::2.0', 'smokesolver')
  339.                 output       = hou.node('{}'.format(dopnetPath)).createNode('output', 'OUTPUT')
  340.  
  341.                 merge.setInput(0, source_gpfd)
  342.                 merge.setInput(1, source_gpft)
  343.                 merge.setInput(2, source_gpfv)
  344.  
  345.                 smoke_solver.setInput(0, smoke_object)
  346.                 smoke_solver.setInput(1, gas_resize)
  347.                 smoke_solver.setInput(4, merge)
  348.                 output.setInput(0, smoke_solver)
  349.  
  350.                 output.setDisplayFlag(True)
  351.  
  352.             else:
  353. #                hou.hscript('oppresetload{}'.format(dopnet_smoke_basic))
  354.                 smoke_object = hou.node('{}'.format(dopnetPath)).createNode('smokeobject', 'smoke')
  355.                 gas_resize   = hou.node('{}'.format(dopnetPath)).createNode('gasresizefluiddynamic', 'gasresizefluiddynamic')
  356.                 source_vol   = hou.node('{}'.format(dopnetPath)).createNode('sourcevolume', 'sourcevolume_density')
  357.                 smoke_solver = hou.node('{}'.format(dopnetPath)).createNode('smokesolver::2.0', 'smokesolver')
  358.                 output       = hou.node('{}'.format(dopnetPath)).createNode('output', 'OUTPUT')
  359.  
  360.                 smoke_solver.setInput(0, smoke_object)
  361.                 smoke_solver.setInput(1, gas_resize)
  362.                 smoke_solver.setInput(4, source_vol)
  363.                 output.setInput(0, smoke_solver)
  364.  
  365.                 output.setDisplayFlag(True)
  366.  
  367.             for aNode in dopnet.children():
  368.                 aNode.moveToGoodPosition(relative_to_inputs=True)
  369.  
  370. def createNode(nodeType1, nodeName, parentNode):
  371.     dopnet = parentNode.createNode(nodeType1)
  372.     dopnet.setName(nodeName, unique_name=True)
  373.  
  374.     return dopnet
  375.  
  376. def createNode(nodeType2, nodeName2, parentNode):
  377.     dop_io = parentNode.createNode(nodeType2)
  378.     dop_io.setName(nodeName2, unique_name=True)
  379.  
  380.     return dop_io
  381.  
  382. def createNode(nodeType3, nodeName3, parentNode):
  383.     bounds = parentNode.createNode(nodeType3)
  384.     bounds.setName(nodeName3, unique_name=True)
  385.  
  386.     return bounds
  387. ****************************************************************************************************************************
  388.  
  389. Create merge switch:
  390.  
  391. import hou
  392. def main():
  393. # well just use one of the selected nodes to get the pwd and
  394. # make the merge
  395.     approvedCategories = ["Sop", "Cop2", "Driver", "Chop", "Dop"]
  396.     if hou.selectedNodes():
  397.         node = hou.selectedNodes()[0]
  398.     else:
  399.         None
  400.  
  401.     curCategory = node.type().category().name()
  402.  
  403.     nodeType = hou.ui.displayMessage("Merge or Switch?", buttons=("Merge", "Switch", "Cancel"))
  404.     if nodeType == 2:
  405.         None
  406.  
  407. # Ask if we want to gather the inputs
  408.     count = 0
  409.     for aNode in hou.selectedNodes():
  410.         if aNode.outputs():
  411.             count += 1
  412.         if count >= 1:
  413.             result = hou.ui.displayMessage("Gather connections?", buttons=("Yes", "No", "Cancel"))
  414.         else:
  415.             result = 1
  416.         if result == 2:
  417.             None
  418.  
  419.     if curCategory in approvedCategories:
  420.         if nodeType == 1:
  421.             mergeNode = node.parent().createNode("switch", "switch")
  422.         else:
  423.             mergeNode = node.parent().createNode("merge", "merge")
  424.  
  425. # We will get the lowest pos from the selected nodes so that
  426. # we can place the merge below this. We will also take the
  427. # average x pos to place them merge in the middle of the
  428. # selection
  429.         xPositions = []
  430.         yPositions = []
  431.         nodes = []
  432.         for aNode in hou.selectedNodes():
  433.             nodes.append( [aNode.position()[0], aNode] )
  434.             xPositions.append( aNode.position()[0] )
  435.             yPositions.append( aNode.position()[1] )
  436.  
  437.             xPos = sum(xPositions)/float(len(xPositions))
  438.  
  439. # If the nodes are right on top of each other, place the merge off to a side
  440.         if xPos == max(set(xPositions), key=xPositions.count):
  441.             xPos += 3
  442.  
  443.         yPos = min(yPositions)
  444.         mergeNode.setPosition( hou.Vector2(xPos, yPos-1.5) )
  445. # Sort the nodes by their x pos so it connects them to the
  446. # merge in the correct order
  447.         nodes.sort()
  448.  
  449. # Pick up all the outputs from the nodes being merged
  450. # and set the inputs on the merge and whatnot
  451.         for i in xrange(len(nodes)):
  452. # Try to set the input. If there is some error we will
  453. # just skip. This happens if one of the selected nodes
  454. # is a rop node or a chopnet, something like that.
  455.             if result == 0:
  456.                 for outputs in nodes[i][1].outputs():
  457.                     x = 0
  458.                 for inputs in outputs.inputs():
  459.                     if nodes[i][1].name() == inputs.name():
  460.                         outputs.setInput(x, mergeNode)
  461.                         x += 1
  462.             try:
  463.                 mergeNode.setNextInput(nodes[i][1])
  464.             except:
  465.                 pass
  466.  
  467.  
  468. # Set selections and display flags where proper
  469.         mergeNode.setCurrent(True, clear_all_selected=True)
  470.         if curCategory == "Sop":
  471.             mergeNode.setDisplayFlag(True)
  472.             mergeNode.setRenderFlag(True)
  473.  
  474. ****************************************************************************************************************************
  475.  
  476. Create Null Node:
  477.  
  478. import hou
  479. def main():
  480.     node = hou.pwd()
  481.     for i in hou.selectedNodes():
  482.         if hou.nodeTypeCategories().keys():
  483. ### Above function lets you call this function on any context ###
  484.             dir = i.path().split(i.name())[0]
  485.             selNodeName = i.path().split('/')[-1]
  486.             otherName = hou.ui.readInput('Name the node', buttons=('OK', 'CANCEL'), initial_contents='name_the_node')[1]
  487.             if otherName == "":
  488.                 null = hou.node('/%s'%dir).createNode('null', 'OUT_%s'%selNodeName)
  489.             else:
  490.                 null = hou.node('/%s'%dir).createNode('null', 'OUT_%s'%otherName)
  491.             selNodePos = i.position()
  492.             null.setColor(hou.Color( [0,0,0] ))
  493. ### Setting node position ###
  494.             null.setPosition(hou.Vector2(selNodePos[0],selNodePos[1]-1))
  495.             null.setInput(0,i)
  496.             i.setSelected(False)
  497.             null.setSelected(True)
  498.  
  499. ### Setting render and display flags for respective contexts ###
  500.             curContext = i.type().category().name()
  501.             if curContext in ['Dop','Chop','Pop']:
  502.                 null.setDisplayFlag(True)
  503.             if curContext in ['Sop', 'Cop2', 'CopNet']:
  504.                 null.setRenderFlag(True)
  505.                 null.setDisplayFlag(True)
  506.             if curContext in ['Vop']:
  507.                 null.setPosition(hou.Vector2(selNodePos[0]+1.5,selNodePos[1]))
  508.                 null.setInput(0,i)
  509. ### Match the name of incoming nodes to that of the names of the nodes you have selected
  510.             for aNode in i.outputs():
  511.                 x = 0
  512.                 for inputs in aNode.inputs():
  513.                     if inputs.name() == i.name():
  514.                         aNode.setInput(x,null)
  515.                     else:
  516.                         x += 1
  517.                 null.setInput(0,i)
  518.  
  519. ****************************************************************************************************************************
  520.  
  521. Create ObjMerge Node:
  522.  
  523. import hou
  524. def main():
  525.  
  526.     for node in hou.selectedNodes():
  527.         pathToNode   = node.path()
  528.         parentName   = pathToNode.split( "/" )[-3]
  529.         splitPath    = pathToNode.split( "/" )[-1]
  530.         nameOfNode   = parentName + "_" + splitPath
  531.         countPath    = len( "%s"%splitPath )
  532.         dir          = pathToNode[:-countPath]
  533.         objMerge     = hou.node( "%s"%dir ).createNode( "object_merge", "IN_%s"%nameOfNode )
  534.         selNodePos   = node.position()
  535.         objMerge.setPosition( hou.Vector2( selNodePos[0], selNodePos[1] - 1.5) )
  536.         objMerge.setParms( { "objpath1" : "%s"%pathToNode } )
  537.         objMerge.setColor( hou.Color( [ 0.6,0.4,0.2 ] ) )
  538.  
  539.  
  540. ****************************************************************************************************************************
  541.  
  542. Disconnect nodes:
  543.  
  544. import hou
  545. def main():
  546.     for i in hou.selectedNodes():
  547.             node = i.path()
  548.             numNodesConnected = len(i.inputs())
  549.             for aNode in i.inputs():
  550.                     nameNodesConnected = aNode.name()
  551.                     hou.hscript("opunwire %s 0"%node)
  552.  
  553. ****************************************************************************************************************************
  554.  
  555. Set Farm Options:
  556.  
  557. import hou
  558. import IEHoudiniFx
  559. import IECore
  560.  
  561. def main():
  562.  
  563.     ieRop = []
  564.     for node in hou.node( "/obj" ).allSubChildren():
  565.         if node.type().name().find( "ieSopRop" ) != -1:
  566.             ieRop.append( node )
  567.  
  568.     treeNodes = {}
  569.     for i in ieRop:
  570.         treeNodes[ i.path() ] = IEHoudiniFx.FnRop( i )
  571.     choices = hou.ui.selectFromTree( treeNodes.keys(), message="Select from List" )
  572.  
  573.  
  574.     if len( choices ) > 0:
  575.         ropDict = {}
  576.         for choice in choices:
  577.             ropDict[ choice ] = IEHoudiniFx.FnRop( choice )
  578.             rop   = ropDict.keys()[0]
  579.             parms = []
  580.             init  = []
  581.             for parm in hou.node( rop ).parms():
  582.                 if parm.name().find( "farmCores" ) != -1:
  583.                     parms.append( parm.name() )
  584.                     init.append( "8" )
  585.                 if parm.name().find( "farmMemory" ) != -1:
  586.                     parms.append( parm.name() )
  587.                     init.append( "15" )
  588.                 if parm.name().find( "farmClumping" ) != -1:
  589.                     parms.append( parm.name() )
  590.                     init.append( "25" )
  591.                 if parm.name().find( "ieFileType" ) != -1:
  592.                     parms.append( parm.name() )
  593.                     init.append( "bgeo.sc" )
  594.                 if parm.name().find( "ieVersionDescription" ) != -1:
  595.                     parms.append( parm.name() )
  596.             enterValues = hou.ui.readMultiInput( message="Enter Rop Info", input_labels=( parms ), buttons=( 'OK', 'CANCEL' ), initial_contents=( init ) )[1]
  597.  
  598.             assignCores          = enterValues[0]
  599.             assignMemory         = enterValues[1]
  600.             assignFarmClumping   = enterValues[2]
  601.             assignFileType       = enterValues[3]
  602.             assignVerDescription = enterValues[4]
  603.        
  604.             defCores       = hou.node( rop ).parm( "farmCores" ).eval()
  605.             defMemory      = hou.node( rop ).parm( "farmMemory" ).eval()
  606.             defFarmClumping= hou.node( rop ).parm( "farmClumping" ).eval()
  607.             defFileType    = hou.node( rop ).parm( "ieFileType" ).evalAsString()
  608.             defDescription = hou.node( rop ).parm( "ieVersionDescription" ).evalAsString()
  609.  
  610.             if defCores         != assignCores:
  611.                 hou.node( rop ).setParms( { "farmCores" : "%s"%assignCores } )
  612.             else:
  613.                 defCores         = defCores
  614.  
  615.  
  616.             if defMemory        != assignMemory:
  617.                 hou.node( rop ).setParms( { "farmMemory" : "%s"%assignMemory } )
  618.             else:
  619.                 defMemory        = defMemory
  620.  
  621.  
  622.             if defFarmClumping  != assignFarmClumping:
  623.                 hou.node( rop ).setParms( { "farmClumping" : "%s"%assignFarmClumping } )
  624.             else:
  625.                 defFarmClumping  = defFarmClumping
  626.  
  627.  
  628.             if defFileType      != assignFileType:
  629.                 hou.node( rop ).setParms( { "ieFileType" : "%s"%assignFileType } )
  630.             else:
  631.                 defFileType      = defFileType
  632.  
  633.              if defDescription   != "":
  634.                 defDescription   = defDescription
  635.             elif defDescription == "":
  636.                 hou.node( rop ).setParms( { "ieVersionDescription" : "%s"%assignVerDescription } )
  637.  
  638. ****************************************************************************************************************************
  639.  
  640. Ramp Copy:
  641.  
  642. ####################################
  643. def checkRamps(node):
  644.     rampList=[]
  645.     for parm in node.parms():
  646.         try:
  647.             parm.evalAsRamp()
  648.             rampList.append(parm)
  649.             #print parm.name()
  650.         except TypeError:
  651.             name = parm.name()
  652.             #print "not" + name
  653.     return rampList
  654. ####################################
  655. def selectRamp(rampList):
  656.     names = []
  657.     count = 0
  658.     for ramp in rampList:
  659.         names.append( ramp.name())
  660.     return hou.ui.selectFromList(names)
  661.    
  662. ####################################
  663.  
  664. selected = hou.selectedNodes()
  665. if len(selected)==2:
  666.  
  667.     origNode = hou.selectedNodes()[0]
  668.     destNode = hou.selectedNodes()[1]
  669.    
  670.     origRamps = []
  671.     destRamps = []
  672.    
  673.     origRamps = checkRamps(origNode)
  674.     destRamps = checkRamps(destNode)
  675.    
  676.     origRamp =  origRamps[selectRamp(origRamps)[0]]
  677.     destRamp =  destRamps[selectRamp(destRamps)[0]]
  678.    
  679.    
  680.     ramp = origRamp.evalAsRamp()
  681.     basis = ramp.basis()
  682.     keys = ramp.keys()
  683.     values = ramp.values()
  684.    
  685.     #print destRamp
  686.     if ramp.isColor() is destRamp.evalAsRamp().isColor():
  687.         destRamp.set( hou.Ramp(basis,keys,values))
  688.     else:
  689.         hou.ui.displayMessage("different type")
  690.    
  691.  
  692. else:
  693.     print hou.ui.displayMessage("select 2 nodes")
  694. ****************************************************************************************************************************
  695.  
  696. Add prefix to node name:
  697.  
  698. import hou
  699. def main():
  700.     for node in hou.selectedNodes():
  701.         nameOfNode = node.name()
  702.         nameEnter = hou.ui.readInput("Name the node", buttons=("OK", "CANCEL"), initial_contents='Asset_')[1]
  703.         newName = "%s_"%nameEnter +"%s"%nameOfNode
  704.         node.setName("%s"%newName)
  705. ****************************************************************************************************************************
  706.  
  707. Set camera:
  708.  
  709. viewports = hou.ui.paneTabOfType(hou.paneTabType.SceneViewer)
  710.  
  711. viewports.curViewport().setCamera(hou.node("nameOfTheCamera")
  712.  
  713. **************************************************************************************************************************
  714.  
  715. Python Sop attrib sanity check:
  716.  
  717. #######Paramters########
  718. ##Point Attribs(multiparmblock_list)##
  719. ##Label(aname#)##
  720. ##Type(atype#)##
  721. ##Check(check#)<toggle>##
  722. ##Weak sanity(weaksanity)##
  723.  
  724. node = hou.pwd()
  725. geo = node.geometry()
  726.  
  727. falseSanity = False
  728. message = ""
  729. attr_map = ["Float", "Int", "Float", "String"]
  730.  
  731. for i  in range(hou.parm("../pointattribs").eval()):
  732.     if hou.parm("../check%d" % (i+1)).eval() is 0:
  733.         continue
  734.    
  735.  
  736.     aname = hou.parm("../aname%d" % (i+1)).evalAsString()
  737.     #atype = hou.parm("../atype%d" % (i+1)).evalAsString()
  738.  
  739.     itype = int(hou.parm("../atype%d" % (i+1)).eval())
  740.     stype = hou.parm("../atype%d" % (i+1)).menuLabels()[itype]
  741.  
  742.     attrib = geo.findPointAttrib(aname)
  743.     if attrib is not None:
  744.         aType = attrib.dataType()
  745.         aSize = attrib.size()
  746.  
  747.         if aType.name() == attr_map[itype]:        
  748.             if itype==0 and aSize != 1:
  749.                 falseSanity = True
  750.                 message += "Attrib '%s' type doesn't match, is: %s, should be: %s\n" % (aname, "Vector", stype)
  751.  
  752.             if itype==2 and aSize != 3:
  753.                 falseSanity = True
  754.                 message += "Attrib '%s' type doesn't match, is: %s, should be: %s\n" % (aname, aType.name(), stype)
  755.  
  756.         else:
  757.             falseSanity = True
  758.             message += "Attrib '%s' type doesn't match, is: %s, should be: %s\n" % (aname, aType.name(), stype)
  759.        
  760.     else:
  761.         falseSanity = True
  762.         message += "Attrib: '%s' is missing\n" % aname
  763.        
  764.  
  765. if falseSanity and hou.parm("../weaksanity").eval() == 0:
  766.     raise hou.NodeError(message)
  767.  
  768. if falseSanity and hou.parm("../weaksanity").eval() == 1:
  769.     raise hou.NodeWarning(message)
  770.  
  771. **********************************************************************************************************************
  772.  
  773. Isolate groups:
  774.  
  775.  
  776. def isoPtsByPrefix():
  777.     node = hou.pwd()
  778.     geo  = node.geometry()
  779.    
  780.     prefix = node.parm( 'ptprefix' ).evalAsString()
  781.      
  782.     sP = node.position()[1]
  783.    
  784.     for ptGroup in geo.pointGroups():
  785.         if ptGroup.name().startswith( prefix ):
  786.             x = sP - 1.5
  787.             blastNode = hou.node("..").createNode("blast","iso_%s"%ptGroup.name())
  788.             blastNode.setPosition(hou.Vector2(sP, x))
  789.             blastNode.setParms({'grouptype' : 3 })
  790.             blastNode.setParms({'group' : ptGroup.name()})
  791.             blastNode.setParms({"negate" : True})
  792.             blastNode.setFirstInput(node)
  793.        
  794.             sP += 1
  795.            
  796. def isoPrsByPrefix():
  797.     node = hou.pwd()
  798.     geo  = node.geometry()
  799.    
  800.     prefix = node.parm( 'prprefix' ).evalAsString()
  801.      
  802.     sP = node.position()[1]
  803.    
  804.     for prGroup in geo.primGroups():
  805.         if prGroup.name().startswith( prefix ):
  806.             x = sP - 1.5
  807.             blastNode = hou.node("..").createNode("blast","iso_%s"%prGroup.name())
  808.             blastNode.setPosition(hou.Vector2(sP, x))
  809.             blastNode.setParms({'grouptype' : 4 })
  810.             blastNode.setParms({'group' : prGroup.name()})
  811.             blastNode.setParms({"negate" : True})
  812.             blastNode.setFirstInput(node)
  813.        
  814.             sP += 1
  815.                        
  816.  
  817. def isoPtsBySuffix():
  818.     node = hou.pwd()
  819.     geo  = node.geometry()
  820.    
  821.     suffix = node.parm( 'ptsuffix' ).evalAsString()
  822.    
  823.    
  824.     sP = node.position()[1]
  825.    
  826.     for ptGroup in geo.pointGroups():
  827.         if ptGroup.name().endswith( suffix ):
  828.             x = sP - 1.5
  829.             blastNode = hou.node("..").createNode("blast","iso_%s"%ptGroup.name())
  830.             blastNode.setPosition(hou.Vector2(sP, x))
  831.             blastNode.setParms({'grouptype' : 3 })
  832.             blastNode.setParms({'group' : ptGroup.name()})
  833.             blastNode.setParms({"negate" : True})
  834.             blastNode.setFirstInput(node)
  835.        
  836.             sP += 1
  837.            
  838. def isoPrsBySuffix():
  839.     node = hou.pwd()
  840.     geo  = node.geometry()
  841.    
  842.     suffix = node.parm( 'prsuffix' ).evalAsString()
  843.    
  844.    
  845.     sP = node.position()[1]
  846.    
  847.     for prGroup in geo.primGroups():
  848.         if prGroup.name().endswith( suffix ):
  849.             x = sP - 1.5
  850.             blastNode = hou.node("..").createNode("blast","iso_%s"%prGroup.name())
  851.             blastNode.setPosition(hou.Vector2(sP, x))
  852.             blastNode.setParms({'grouptype' : 4 })
  853.             blastNode.setParms({'group' : prGroup.name()})
  854.             blastNode.setParms({"negate" : True})
  855.             blastNode.setFirstInput(node)
  856.        
  857.             sP += 1
  858.            
  859.  
  860. def printPtGrps():
  861.     node = hou.pwd()
  862.     geo  = node.geometry()
  863.    
  864.     ptgs = []
  865.     for ptg in geo.pointGroups():
  866.         ptgs.append( ptg )
  867.     if not ptgs:
  868.         node.setParms( { 'pointGrps' : 'GROUPS DO NOT EXIST' } )
  869.     else:
  870.         node.setParms( { 'pointGrps' : '%s'%[ i.name() for i in ptgs ] } )
  871.    
  872. def printPrmGrps():
  873.     node = hou.pwd()
  874.     geo  = node.geometry()
  875.    
  876.     prgs = []
  877.     for prg in geo.primGroups():
  878.         prgs.append( prg )
  879.     if not prgs:
  880.         node.setParms( { 'primGrps' : 'GROUPS DO NOT EXIST' } )
  881.     else:
  882.         node.setParms( { 'primGrps' : '%s'%[ i.name() for i in prgs ] } )
  883.    
  884.  
  885.  
  886. def isoPrimGrps():
  887.  
  888.     node = hou.pwd()
  889.     geo  = node.geometry()
  890.  
  891.     inputNode = node.inputs()[0]
  892.    
  893.     groups  = []
  894.     sP = node.position()[1]
  895.  
  896.     for primGroup in geo.primGroups():    
  897.         x = sP - 1.5
  898.         blastNode = hou.node("..").createNode("blast","iso_%s"%primGroup.name())
  899.         blastNode.setPosition(hou.Vector2(sP, x))
  900.         blastNode.setParms({'grouptype' : 4 })
  901.         blastNode.setParms({'group' : primGroup.name()})
  902.         blastNode.setParms({"negate" : True})
  903.         blastNode.setFirstInput(node)
  904.        
  905.         sP += 1
  906.        
  907. def isoPointGrps():
  908.  
  909.     node = hou.pwd()
  910.     geo  = node.geometry()
  911.  
  912.     inputNode = node.inputs()[0]
  913.    
  914.     groups  = []
  915.     sP = node.position()[1]
  916.  
  917.     for pointGroup in geo.pointGroups():    
  918.         x = sP - 1.5
  919.         blastNode = hou.node("..").createNode("blast","iso_%s"%pointGroup.name())
  920.         blastNode.setPosition(hou.Vector2(sP, x))
  921.         blastNode.setParms({'grouptype' : 3 })
  922.         blastNode.setParms({'group' : pointGroup.name()})
  923.         blastNode.setParms({"negate" : True})
  924.         blastNode.setFirstInput(node)
  925.        
  926.         sP += 1
  927.        
  928. *******************************************************************************************************************
  929.  
  930. Create null/output node with functions:
  931.  
  932. import hou
  933. import re
  934.  
  935.  
  936. def main():
  937.     node = hou.pwd()
  938.     for i in hou.selectedNodes():
  939.         if hou.nodeTypeCategories().keys():
  940.             ### Above function lets you call this function on any context ###
  941.             dir = i.path().split(i.name())[0]
  942.             nodeName = i.path().split('/')[-1]
  943.  
  944.             nodeSel = hou.ui.displayMessage("Which type of node do you want to create?", buttons=('Null', 'Output'))
  945.  
  946.             if nodeSel == 0:
  947.                 nodeType = 'null'
  948.             else:
  949.                 nodeType = 'output'
  950.  
  951.             # nodeName
  952.             rawOtherName = hou.ui.readInput('Name the node', buttons=('OK', 'CANCEL'), initial_contents='geo')[1]
  953.             # remove white spaces
  954.             #otherName = re.sub(r'\s+', '', rawOtherName)
  955.             # remove special characters
  956.             otherName = 'OUT_'+re.sub(r'\W+', '_', rawOtherName)
  957.             if rawOtherName != "":
  958.                 nodeName = otherName
  959.             else:
  960.                 nodeName = 'OUT'
  961.             parentNode = hou.node(dir)
  962.  
  963.             new_node = createNode(nodeType, nodeName, parentNode)
  964.  
  965.             new_node_pos = i.position()
  966.             new_node.setColor(hou.Color([0, 0, 0]))
  967.             new_node.setUserData("nodeShape", "circle")
  968.             ### Setting node position ###
  969.             new_node.setPosition(hou.Vector2(new_node_pos[0], new_node_pos[1] - 1))
  970.             new_node.setInput(0, i)
  971.             i.setSelected(False)
  972.             new_node.setSelected(True)
  973. ### Setting render and display flags for respective contexts ###
  974.             curContext = i.type().category().name()
  975.             if curContext in ['Dop', 'Chop', 'Pop']:
  976.                 new_node.setDisplayFlag(True)
  977.             if curContext in ['Sop', 'Cop2', 'CopNet']:
  978.                 new_node.setRenderFlag(True)
  979.                 new_node.setDisplayFlag(True)
  980.             if curContext in ['Vop']:
  981.                 new_node.setPosition(hou.Vector2(new_node_pos[0] + 1.5, new_node_pos[1]))
  982.                 new_node.setInput(0, i)
  983.             ### Match the name of incoming nodes to that of the names of the nodes you have selected
  984.             for aNode in i.outputs():
  985.                 x = 0
  986.                 for inputs in aNode.inputs():
  987.                     if inputs.name() == i.name():
  988.                         aNode.setInput(x,new_node)
  989.                     else:
  990.                         x += 1
  991.                 new_node.setInput(0,i)
  992. def createNode(nodeType, nodeName, parentNode):
  993.  
  994.     new_node = parentNode.createNode(nodeType)
  995.     new_node.setName(nodeName, unique_name=True)
  996.  
  997.     return new_node
  998. *********************************************************************************************************************
  999. Source scripts and reload:
  1000.  
  1001. import sys
  1002. import traceback
  1003.  
  1004. try:
  1005.    pythonScriptPath = '/path/to/Script/on/disk'
  1006.    if not pythonScriptPath in sys.path:
  1007.        sys.path.append(pythonScriptPath)
  1008.    import name_of_script
  1009.    reload(name_of_script)
  1010.    name_of_script.main()
  1011. except ImportError, e:
  1012.    print "cannot import script"
  1013. except Exception, e:
  1014.    exc_type, exc_value, exc_traceback = sys.exc_info()
  1015.    print "*** print_exception:"
  1016.    traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stdout)
  1017.  
  1018. ************************************************************************************************************************
  1019.  
  1020. Copy Nodes To:
  1021. srcPath = hou.selectedNodes()[0].parent().path()
  1022. destPath = hou.ui.selectNode()
  1023. destNode = hou.node( destPath )
  1024.  
  1025. nodes = []
  1026. for node in hou.selectedNodes():
  1027.     nodes.append( node )
  1028. #dnodes = []
  1029. #for dnode in hou.node( destPath ).children():
  1030. #    dnodes.append( dnode )
  1031. #
  1032. #for node in nodes:
  1033. #    for dnode in dnodes:
  1034. #        print compare( node, dnode )
  1035. hou.copyNodesTo( nodes, hou.node( destPath ) )
  1036. ************************************************************************************************************************
  1037. Create viewport visualizers:
  1038.  
  1039. import hou, toolutils, re, math, random
  1040.  
  1041. def main():
  1042.     try:
  1043.         node = hou.selectedNodes()[0]
  1044.         geo  = node.geometry()
  1045.     except IndexError:
  1046.         raised = hou.ui.displayMessage('You must select a node!', buttons=('OK',), severity=hou.severityType.ImportantMessage, default_choice=0, close_choice=0, title='OOPS!')
  1047.         if raised == 0:
  1048.             return 0
  1049.     attrib_list      = []
  1050.     attrib_type_list = []
  1051.  
  1052.     floats   = []
  1053.     vectors  = []
  1054.     ints     = []
  1055.     vector4s = []
  1056.  
  1057.     points_data_list = geo.pointAttribs()
  1058.     prims_data_list  = geo.primAttribs()
  1059.     data_list = list(set(points_data_list + prims_data_list))
  1060.     for attr in data_list:
  1061.         if attr.dataType().name() == 'Float' and attr.size() == 3 and attr.name() != 'Cd':
  1062.             vectors.append(attr.name())
  1063.         if attr.dataType().name() == 'Float' and attr.size() == 4:
  1064.             vector4s.append(attr.name())
  1065.         if attr.dataType().name() == 'Int':
  1066.             ints.append(attr.name())
  1067.         if attr.dataType().name() == 'Float' and attr.size()==1:
  1068.             floats.append(attr.name())
  1069.  
  1070.         attrib_list.append(attr.name())
  1071.  
  1072.     sceneViewer = toolutils.sceneViewer()
  1073.     viewPort    = sceneViewer.curViewport
  1074.  
  1075. ### Create list of existing visualizers
  1076.     visualizersList = []
  1077.     visualizers = hou.viewportVisualizers.visualizers(category=hou.viewportVisualizerCategory.Scene)###Get current visualizers
  1078.     for viz in visualizers:
  1079.         visualizersList.append(viz.name())
  1080.  
  1081.     choices = hou.ui.selectFromList(attrib_list, exclusive=False, message='Choose attribute to visualize', title='Attribute List')
  1082.     if choices:
  1083.         vizType = hou.viewportVisualizers.types()[0]###Set the visualizers to be markers
  1084.         for choice in choices:
  1085.                 if attrib_list[choice] in vectors:### Catch vectors
  1086.                     createViz = hou.viewportVisualizers.createVisualizer(vizType, category=hou.viewportVisualizerCategory.Scene)
  1087.                     createViz.setName(attrib_list[choice])
  1088.                     createViz.setLabel(attrib_list[choice])
  1089.                     createViz.setParm('attrib', attrib_list[choice])
  1090.                     createViz.setParm('style', 4)
  1091.                     createViz.setParm('class', 4)###Set to auto-detect entity
  1092.                     createViz.setParm('arrowheads', 1)
  1093.                     createViz.setParm('vectorcoloring', 0)
  1094.                     #create random
  1095.                     pi    = math.pi
  1096.                     e     = math.e
  1097.                     phi   = math.log10(pi)
  1098.                     seed  = random.SystemRandom()
  1099.                     red   = seed.random() * pi
  1100.                     green = seed.random() * e
  1101.                     blue  = seed.random() * phi
  1102.                     #createViz.setParm('markercolor', red, green, blue)
  1103.                     createViz.setParm('markercolorr', red)
  1104.                     createViz.setParm('markercolorg', green)
  1105.                     createViz.setParm('markercolorb', blue)
  1106.                     createViz.setParm('markercolora',1)
  1107.                     createViz.setParm('rangespec', 1)
  1108.                     createViz.setParm('ramptype', 0)
  1109.  
  1110.                 if attrib_list[choice] in floats:### Catch floats
  1111.                     createViz = hou.viewportVisualizers.createVisualizer(vizType, category=hou.viewportVisualizerCategory.Scene)
  1112.                     createViz.setName(attrib_list[choice])
  1113.                     createViz.setLabel(attrib_list[choice])
  1114.                     createViz.setParm('attrib', attrib_list[choice])
  1115.                     createViz.setParm('style', 0)
  1116.                     createViz.setParm('class', 4)
  1117.  
  1118.                 if attrib_list[choice] in ints:### Catch ints
  1119.                     createViz = hou.viewportVisualizers.createVisualizer(vizType, category=hou.viewportVisualizerCategory.Scene)
  1120.                     createViz.setName(attrib_list[choice])
  1121.                     createViz.setLabel(attrib_list[choice])
  1122.                     createViz.setParm('attrib', attrib_list[choice])
  1123.                     createViz.setParm('style', 0)
  1124.                     createViz.setParm('class', 4)
  1125.  
  1126.                 if attrib_list[choice] in vector4s:
  1127.                     createViz = hou.viewportVisualizers.createVisualizer(vizType, category=hou.viewportVisualizerCategory.Scene)
  1128.                     createViz.setName(attrib_list[choice])
  1129.                     createViz.setLabel(attrib_list[choice])
  1130.                     createViz.setParm('attrib', attrib_list[choice])
  1131.                     createViz.setParm('style', 5)
  1132.                     createViz.setParm('class', 4)
  1133.  
  1134. def initial():
  1135.     ask = hou.ui.displayMessage('What would you like to do?', buttons=('Create new', 'Remove existing', 'Remove duplicates'), severity=hou.severityType.Message, default_choice=0, close_choice=0, title='Choose Operation')
  1136.     if ask == 0:
  1137.         main()
  1138.     if ask == 1:
  1139.         visualizers = hou.viewportVisualizers.visualizers(category=hou.viewportVisualizerCategory.Scene)
  1140.         for visualizer in visualizers:
  1141.             visualizer.destroy()
  1142.     if ask == 2:
  1143.         removeExisting()
  1144.  
  1145. def removeExisting():
  1146.     visualizersList = []
  1147.     visualizers = hou.viewportVisualizers.visualizers(category=hou.viewportVisualizerCategory.Scene)###Get current visualizers
  1148.     for viz in visualizers:
  1149.         if re.split('[^\d]', viz.name())[-1]:
  1150.             viz.destroy()
Add Comment
Please, Sign In to add comment