def export(): """Main export function.""" is_last = False try: T = timer('FrameExport') ps = soho.evaluate({ 'now': SohoParm('state:time', 'real', [0], False, key='now'), 'fps': SohoParm('state:fps', 'real', [24], False, key='fps'), 'hver': SohoParm('state:houdiniversion', 'string', [''], False, key='hver'), 'objpath': SohoParm('objpath', 'string', [''], False), 'abcoutput': SohoParm('abcoutput', 'string', [''], False), 'camera': SohoParm('camera', 'string', [None], False), 'trange': SohoParm('trange', 'int', [0], False), 'f': SohoParm('f', 'int', None, False) }) now = ps['now'].Value[0] fps = ps['fps'].Value[0] hver = ps['hver'].Value[0] camera = ps['camera'].Value[0] dbg("now=%.3f fps=%.3f" % (now, fps)) if not soho.initialize(now, camera): soho.error("couldn't initialize soho (make sure camera is set)") abc_cleanup() return # NOTE: this is prone to float inaccuracies frame = now*fps + 1.0 objpath = ps['objpath'].Value[0] abc_file = ps['abcoutput'].Value[0] trange = ps['trange'].Value[0] f = ps['f'].Value is_first = frame < f[0]+0.5 # working around float funniness is_last = frame > f[1]-0.5 if trange==0: is_first= is_last= True dbg("is_first=%d is_last=%d" % (is_first, is_last)) dbg("now=%.3f fps=%.3f -> %f" % (now, fps, frame)) dbg("objpath=%s camera=%s abcoutput=%s trange=%d f=%s" % \ (objpath, camera, abc_file, trange, str(f))) T.lap('init') # collect hierarchy to be exported # (read from scene directly, ie. not containing instances, etc.) # results in array [ (parentname, objname) [, ...] ] -- (full pathnames) # #dbg("COLLECTING ARCHY:") archy = collect_archy(objpath) archy_objs = [ n[1] for n in archy ] #dbg("DONE.") # collect geometry to be exported and their render SOPS # (including point- and other instances, etc) # (NOTE: the entire scene is to be searched, unfortunately) # soho.addObjects(now, '*', '*', '', do_culling=False) soho.lockObjects(now) soho_objs = {} # {objname: soho_obj} soho_only = {} # soho-only objects (can't be accessed directly with hdk) obj_list = [] sop_dict = {} # {objname: sopname} objs = soho.objectList('objlist:instance') #dbg("COLLECT soho instance/sop pairs ------------------") for obj in objs: n = obj.getName() # full pathname obj_list.append(n) soho_objs[n] = obj path = obj.getDefaultedString('object:soppath', now, [None])[0] #dbg(" -- %s (sop:%s)" % (n, str(path)) ) if path and path!="": sop_dict[n] = path T.lap('collect-objs') if False: dbg( '-' * 40 ) dbg("sop_dict: %s" % str(sop_dict)) # extend hierarchy with per-point instances # p1 = re.compile(":[^:]+:") for obj in obj_list: if re.search(p1, obj): m = obj.split(":") p = m[-2] # parent: 2nd from right if p in archy_objs: archy.append( ( p, obj, "%s__%s" % (m[-2], m[-1]) ) ) soho_only[obj]=p #dbg(" -+- %s %s" % (p, obj)) # fill rest of the archy array # elem: (parentpath, objpath, exportname, soppath) # archy2 = [] for a in archy: N = list(a) if len(N)<3: N.append(N[1]) # N = [ N[0], N[1], N[1] ] if N[1] in sop_dict: N = [ N[0], N[1], N[2], sop_dict[N[1]] ] else: # empty xform (no sop) N = [ N[0], N[1], N[1], None ] N[2] = re.search("[^/]+$", N[2]).group(0) archy2.append(N) archy = archy2 if False: dbg( '-' * 40 ) dbg("COLLECTED ARCHY:") for a in archy: dbg("- %s: " % (a[1], )) dbg("COLLECTED ARCHY: %d elems" % len(archy)) T.lap('got-archy') # we now have a list of all objects to be exported # (parentname, objname, exportname, soppath) # archy_objs = [ n[1] for n in archy ] skip_frame = False now_out = now+(1.0/fps) # check for user abort # if False: # TODO: check for user abort! skip_frame = True is_last = True warn("user abort") # first frame: init all internal stuff # if is_first: dbg("\n\n\n") dbg("IS_FIRST--INIT") G.archy = archy[:] G.archy_objs = archy_objs[:] s = abc_init(abc_file, tstep=1.0/fps, tstart=now_out) if s: # build objects for oarchive # for E in archy: objname = E[1] parent = E[0] outname = E[2] soppath = E[3] if parent is None: parent="-" if soppath is None: soppath="-" # TODO: if instance, objname should be the base obj name obj_src = objname if objname in soho_only: obj_src = soho_only[objname] #dbg("-- new xform\n\toutname= %s\n\tobj = %s\n\tparent = %s\n\tsop = %s" % (outname, objname, parent, soppath)) hou.hscript('%s newobject "%s" "%s" "%s" "%s" "%s"' % \ (CCMD, objname, obj_src, parent, outname, soppath)) # set object flags (static, etc.) # if objname in soho_objs: ps = soho_objs[objname].evaluate({ 'abc_staticgeo': SohoParm('abc_staticgeo', 'int', [0], False) }, now) if ps['abc_staticgeo'].Value[0]!=0: hou.hscript('%s objset "%s" static' % (CCMD, objname)) else: warn("couldn't output to file %s--aborting" % abc_file) skip_frame = True is_last = True T.lap('frame-first') # frame export: collect xforms, geoms, and export them # if archy_objs==G.archy_objs and not skip_frame: dbg("\n") dbg(" -- EXPORTING frame %.1f" % frame) for E in archy: #dbg("\n-") #dbg("- OBJ: %s" % str(E)) objname = E[1] soppath = E[3] #dbg("- OBJ: %s" % E[1]) # get xform matrix (TODO: get pretransform too!) # xform = '' # TODO: use this only for instances! #if objname in soho_objs: if objname in soho_only: # get matrix from soho #dbg(" --- (mtx from soho)") xform = [] soho_objs[objname].evalFloat('space:local', now, xform) xform = hou.Matrix4(xform) xform = ' '.join([ str(n) for n in xform.asTuple() ]) # perform sample write # (c++ code decides if geom is to be written) # if True: hou.hscript('%s writesample %f "%s" %s' % \ (CCMD, now_out, objname, xform)) else: #soho.error("couldn't export frame %.1f--no. of objects changed" % frame) warn("couldn't export frame %.1f--no. of objects changed" % frame) T.lap('frame-export') except: dbg("INTERRUPTED BY EXCEPTION") is_last=True # last frame: cleanup all internal stuff, # finish export # if is_last: dbg("\n\n\n") dbg("IS_LAST--FINISHING...") abc_cleanup() T.lap('frame-last') T.stats()
def main(): import sys import hou import soho import sohoglue import SOHOcommon import sys import ctypes if hasattr(sys, 'setdlopenflags'): sys.setdlopenflags(sys.getdlopenflags() | ctypes.RTLD_GLOBAL) import _vfh_ipr from soho import SohoParm LogLevel = type('Enum', (), { 'Info': 0, 'Progress': 1, 'Warning': 2, 'Error': 3, 'Debug': 4, }) def logMessage(level, fmt, *args): _vfh_ipr.logMessage(level, fmt % args) def printDebug(fmt, *args): logMessage(LogLevel.Debug, fmt, *args) def dumpObjects(listName): printDebug("Checking \"%s\"" % listName) for obj in soho.objectList(listName): printDebug(" %s", obj.getName()) def exportObjects(listName): for obj in soho.objectList(listName): _vfh_ipr.exportOpNode(opNode=obj.getName()) def deleteObjects(listName): for obj in soho.objectList(listName): _vfh_ipr.deleteOpNode(opNode=obj.getName()) def getViewParams(camera, sohoCam, t): camParms = { 'space:world': SohoParm('space:world', 'real', [], False), 'focal': SohoParm('focal', 'real', [0.050], False), 'aperture': SohoParm('aperture', 'real', [0.0414214], False), 'orthowidth': SohoParm('orthowidth', 'real', [2], False), 'near': SohoParm('near', 'real', [0.001], False), 'far': SohoParm('far', 'real', [1000], False), 'res': SohoParm('res', 'int', [640, 480], False), 'projection': SohoParm('projection', 'string', ["perspective"], False), 'cropl': SohoParm('cropl', 'real', [-1], False), 'cropr': SohoParm('cropr', 'real', [-1], False), 'cropb': SohoParm('cropb', 'real', [-1], False), 'cropt': SohoParm('cropt', 'real', [-1], False), 'camera': SohoParm('camera', 'string', ['/obj/cam1'], False), } camParmsEval = sohoCam.evaluate(camParms, t) if not camParmsEval: return {} viewParams = {} for key in camParmsEval: viewParams[key] = camParmsEval[key].Value[0] viewParams['transform'] = camParmsEval['space:world'].Value viewParams['ortho'] = 1 if camParmsEval['projection'].Value[0] in { 'ortho' } else 0 viewParams['res'] = camParmsEval['res'].Value cropX = viewParams['res'][0] * viewParams['cropl'] cropY = viewParams['res'][1] * (1.0 - viewParams['cropt']) cropW = viewParams['res'][0] * (viewParams['cropr'] - viewParams['cropl']) cropH = viewParams['res'][1] * (viewParams['cropt'] - viewParams['cropb']) printDebug(" Res: %s" % viewParams['res']) printDebug(" Crop: %i-%i %i x %i" % (cropX, cropY, cropW, cropH)) printDebug(" Camera: %s" % camera) return viewParams def exportView(rop, camera, sohoCam, t): printDebug("exportView()") _vfh_ipr.exportView(viewParams=getViewParams(camera, sohoCam, t)) mode = soho.getDefaultedString('state:previewmode', ['default'])[0] # Evaluate an intrinsic parameter (see HDK_SOHO_API::evaluate()) # The 'state:time' parameter evaluates the time from the ROP. now = soho.getDefaultedFloat('state:time', [0.0])[0] # Evaluate the 'camera' parameter as a string. # If the 'camera' parameter doesn't exist, use ['/obj/cam1']. # SOHO always returns lists of values. camera = soho.getDefaultedString('camera', ['/obj/cam1'])[0] # MPlay / Render View port. host = soho.getDefaultedString("vm_image_mplay_sockethost", [0])[0] port = soho.getDefaultedInt("vm_image_mplay_socketport", [0])[0] # ROP node. ropPath = soho.getOutputDriver().getName() ropNode = hou.node(ropPath) printDebug("Initialize SOHO...") # Initialize SOHO with the camera. # XXX: This doesn't work for me, but it should according to the documentation... # soho.initialize(now, camera) if not sohoglue.initialize(now, camera, None): soho.error("Unable to initialize rendering module with given camera") # Now, add objects to our scene soho.addObjects(now, "*", "*", "*", True) # Before we can evaluate the scene from SOHO, we need to lock the object lists. soho.lockObjects(now) for sohoCam in soho.objectList('objlist:camera'): break else: soho.error("Unable to find viewing camera for render") sohoOverride = soho.getDefaultedString('soho_overridefile', ['Unknown'])[0] printDebug("Processing Mode: \"%s\"" % mode) if mode in {"generate"}: # generate: Generation phase of IPR rendering # In generate mode, SOHO will keep the pipe (soho_pipecmd) # command open between invocations of the soho_program. # objlist:all # objlist:camera # objlist:light # objlist:instance # objlist:fog # objlist:space # objlist:mat # printDebug("IPR Host: %s:%s" % (host, port)) printDebug("Driver: %s" % ropPath) printDebug("Camera: %s" % camera) printDebug("Now: %.3f" % now) for obj in soho.objectList('objlist:instance'): # Register SOP as IPR dependency. obj.getDefaultedString('object:soppath', now, ['']) # Register SHOP as IPR dependency. # TODO: Investigave this. Use OP_Node::addOpInterest() for now. # shader = [] # shader_type = [] # shader_handle = [] # obj.evalShaderAndType("shop_materialpath", now, shader, shader_type, shader_handle) _vfh_ipr.init(rop=ropPath, port=port, now=now, viewParams=getViewParams(camera, sohoCam, now)) elif mode in {"update"}: # update: Send updated changes from previous generation # # In this rendering mode, the special object list parameters: # objlist:dirtyinstance # objlist:dirtylight # objlist:dirtyspace # objlist:dirtyfog # will contain the list of all objects modified since the last render # (whether a generate or update). # # As well, the parameters: # objlist:deletedinstance # objlist:deletedlight # objlist:deletedspace # objlist:deletedfog # will list all objects which have been deleted from the scene. # if not _vfh_ipr.isRopValid(): _vfh_ipr.init(rop=ropPath, port=port, now=now, viewParams=getViewParams(camera, sohoCam, now)) else: # Have to handle "time" event manually here. _vfh_ipr.setTime(now) for obj in soho.objectList('objlist:dirtyinstance'): obj.getDefaultedString('object:soppath', now, ['']) exportObjects("objlist:dirtyinstance") exportObjects("objlist:dirtylight") exportView(ropPath, camera, sohoCam, now)
def soho_render(): control_parms = { # The time at which the scene is being rendered "now": SohoParm("state:time", "real", [0], False, key="now"), "camera": SohoParm("camera", "string", ["/obj/cam1"], False), } parms = soho.evaluate(control_parms) now = parms["now"].Value[0] camera = parms["camera"].Value[0] options = {} if not soho.initialize(now, camera, options): soho.error("Unable to initialize rendering module with given camera") object_selection = { # Candidate object selection "vobject": SohoParm("vobject", "string", ["*"], False), "alights": SohoParm("alights", "string", ["*"], False), "forceobject": SohoParm("forceobject", "string", [""], False), "forcelights": SohoParm("forcelights", "string", [""], False), "excludeobject": SohoParm("excludeobject", "string", [""], False), "excludelights": SohoParm("excludelights", "string", [""], False), "sololight": SohoParm("sololight", "string", [""], False), } for cam in soho.objectList("objlist:camera"): break else: soho.error("Unable to find viewing camera for render") objparms = cam.evaluate(object_selection, now) stdobject = objparms["vobject"].Value[0] stdlights = objparms["alights"].Value[0] forceobject = objparms["forceobject"].Value[0] forcelights = objparms["forcelights"].Value[0] excludeobject = objparms["excludeobject"].Value[0] excludelights = objparms["excludelights"].Value[0] sololight = objparms["sololight"].Value[0] forcelightsparm = "forcelights" if sololight: stdlights = excludelights = "" forcelights = sololight forcelightsparm = "sololight" # First, we add objects based on their display flags or dimmer values soho.addObjects( now, stdobject, stdlights, "", True, geo_parm="vobject", light_parm="alights", fog_parm="", ) soho.addObjects( now, forceobject, forcelights, "", False, geo_parm="forceobject", light_parm=forcelightsparm, fog_parm="", ) soho.removeObjects( now, excludeobject, excludelights, "", geo_parm="excludeobject", light_parm="excludelights", fog_parm="", ) # Lock off the objects we've selected soho.lockObjects(now) with hou.undos.disabler(), scene_state: if "SOHO_PBRT_DEV" in os.environ: # pragma: no coverage import cProfile pr = cProfile.Profile() pr.enable() try: PBRTscene.render(cam, now) finally: pr.disable() pr.dump_stats("hou-prbt.stats") else: PBRTscene.render(cam, now) return
'vobject' : SohoParm('vobject', 'string', ['*'], False), 'alights' : SohoParm('alights', 'string', ['*'], False), 'vfog' : SohoParm('vfog', 'string', ['*'], False), 'forceobject' : SohoParm('forceobject', 'string', [''], False), 'forcelights' : SohoParm('forcelights', 'string', [''], False), 'forcefog' : SohoParm('forcefog', 'string', [''], False), 'excludeobject' : SohoParm('excludeobject', 'string', [''], False), 'excludelights' : SohoParm('excludelights', 'string', [''], False), 'excludefog' : SohoParm('excludefog', 'string', [''], False), 'sololight' : SohoParm('sololight', 'string', [''], False), } for cam in soho.objectList('objlist:camera'): break else: soho.error("Unable to find viewing camera for render") objparms = cam.evaluate(objectSelection, now) stdobject = objparms['vobject'].Value[0] stdlights = objparms['alights'].Value[0] stdfog = objparms['vfog'].Value[0] forceobject = objparms['forceobject'].Value[0] forcelights = objparms['forcelights'].Value[0] forcefog = objparms['forcefog'].Value[0] excludeobject = objparms['excludeobject'].Value[0] excludelights = objparms['excludelights'].Value[0] excludefog = objparms['excludefog'].Value[0]
'vobject': SohoParm('vobject', 'string', ['*'], False), 'alights': SohoParm('alights', 'string', ['*'], False), 'vfog': SohoParm('vfog', 'string', ['*'], False), 'forceobject': SohoParm('forceobject', 'string', [''], False), 'forcelights': SohoParm('forcelights', 'string', [''], False), 'forcefog': SohoParm('forcefog', 'string', [''], False), 'excludeobject': SohoParm('excludeobject', 'string', [''], False), 'excludelights': SohoParm('excludelights', 'string', [''], False), 'excludefog': SohoParm('excludefog', 'string', [''], False), 'matte_objects': SohoParm('matte_objects', 'string', [''], False), 'phantom_objects': SohoParm('phantom_objects', 'string', [''], False), 'sololight': SohoParm('sololight', 'string', [''], False), 'lv_cameralist': SohoParm('lv_cameralist', 'string', [''], False), } for cam in soho.objectList('objlist:camera'): break else: soho.error("Unable to find viewing camera for render") objparms = cam.evaluate(objectSelection, now) stdobject = objparms['vobject'].Value[0] stdlights = objparms['alights'].Value[0] stdfog = objparms['vfog'].Value[0] forceobject = objparms['forceobject'].Value[0] forcelights = objparms['forcelights'].Value[0] forcefog = objparms['forcefog'].Value[0] excludeobject = objparms['excludeobject'].Value[0] excludelights = objparms['excludelights'].Value[0] excludefog = objparms['excludefog'].Value[0] sololight = objparms['sololight'].Value[0]
geo_parm='phantom_objects', light_parm='', fog_parm='') soho.removeObjects(now, excludeobject, excludelights, excludefog, geo_parm='excludeobject', light_parm='excludelights', fog_parm='excludefog') # Lock off the objects we've selected soho.lockObjects(now) IFDsettings.clearLists() IFDsettings.load(now) IFDgeo.reset() if inheritedproperties: # Output object level properties which are defined on the output driver ray_comment('Object properties defined on output driver') IFDsettings.outputObject(soho.getOutputDriver(), now) if decl_shops: IFDgeo.declareAllMaterials(now, decl_shops > 1) # # Output objects # IFDframe.outputObjects(now, soho.objectList('objlist:instance'), soho.objectList('objlist:light'), soho.objectList('objlist:space'), soho.objectList('objlist:fog'), -1, -1)
# Evaluate an intrinsic parameter (see HDK_SOHO_API::evaluate()) # The 'state:time' parameter evaluates the time from the ROP. evaltime = soho.getDefaultedFloat('state:time', [0.0])[0] # Initialize SOHO with the camera. if not soho.initialize(evaltime, camera): soho.error('Unable to initialize rendering module with camera: %s' % repr(camera)) # Now, add objects to our scene # addObjects(time, geometry, light, fog, use_display_flags) soho.addObjects(evaltime, "*", "*", "*", True) # Before we can evaluate the scene from SOHO, we need to lock the object lists. soho.lockObjects(evaltime) # Now, traverse all the objects def outputObjects(fp, prefix, list): fp.write('%s = {' % prefix) for obj in list: fp.write('"%s",' % obj.getName()) fp.write('}\n') fp.flush() fp = sys.stdout outputObjects(fp, 'Geometry', soho.objectList('objlist:instance')) outputObjects(fp, 'Light', soho.objectList('objlist:light')) outputObjects(fp, 'Fog', soho.objectList('objlist:fog'))