Houdini: Python

Workflow tip:

If you find yourself editing a lot of python code, you might like the joy of an external editor. Place your python code in $HOME/houdiniXX.X/scripts/python, for example as "test.py", then inside Houdini, drop a python node and do as follows:

import test
reload(test)
from test import *

Another cool way is to use the exec() function. Whan doing this, you do not need to worry about importing any stuff in your external file. I like the following:

(For example, in a python SOP, to read myfile.py in my home dir)

import os
home=os.path.expanduser('~')
pyfile=os.path.join(home,'myfile.py')
execfile(pyfile)

You can add frame=hou.frame() so the SOP will become time-dependent. Now stepping through frames re-evaluates your node. You can then edit the source file using your favorite editor.

Misc

Where on disk is my scene file?
hou.hipFile.path()
(hou.hipFile has a lot of options)

Get parameter

print hou.ch('parm')

Delete primitives

deleteList=[]
for i in boundingGrp.prims():
    deleteList.append(i)
geo.deletePrims(deleteList)

Access local variables:

xBoundSize=lvar('SIZEX')

bang out point positions:

import json
node = hou.pwd()
geo = node.geometry()
pdata = []

for p in geo.points():
    pos = list(p.position())
    #print pos
    pdata.append(pos)
 
with open('/tmp/points.json','w') as f:  
    json.dump(pdata, f, indent=4)

Point <> Vert mapping

sometimes you need the vertices that belong to a point. You can query the point belonging to a vert, but not the verts belonging to a point. For connectivity checks, you might find yourself needing that, so:

# store every vertex with it's point
def gen_v_p_dict():
    dict = {}
    for prim in geo.prims():
        for vert in prim.vertices():
            dict[vert] = vert.point()
    return dict

# more useful to me, store all points with
# a list of vertices.
def gen_p_dict():
    dict = {}
    for prim in geo.prims():
        for vert in prim.vertices():
            pt = vert.point()
            if pt in dict:
                dict[pt].append(vert)
            else:
                dict[pt] = [vert]
    return dict

Group related:

Create group:

myGrp=geo.createPrimGroup('name')

Add Point to group:

point=geo.createPoint()
myGrp=geo.createPointGroup('name')
myGrp.add(point)

Iterate group:

groups = geo.primGroups()
for group in groups:
    print group.name()

Delete group, leaving contents intact:

group.destroy()

Attributes

Before setting an attribute, it must exist. Create it with:

geo.addAttrib(hou.attribType.Prim, 'myattrib', 0.0)

(In this case a primitive attribute)

Set attribute value

points[index].setAttribValue("Cd",(1.0,1.0,1.0))

Get attribute:

redVal=point.attribValue("Cd")[0]

Stuff

http://www.tokeru.com/cgwiki/index.php?title=HoudiniPython