Example #1
0
 def init_state(self):
     """Queries Soho to initialize the attributes of the class"""
     state_parms = {
         "rop":
         soho.SohoParm("object:name", "string", key="rop"),
         "hip":
         soho.SohoParm("$HIP", "string", key="hip"),
         "hipname":
         soho.SohoParm("$HIPNAME", "string", key="hipname"),
         "hipfile":
         soho.SohoParm("$HIPFILE", "string", key="hipfile"),
         "ver":
         soho.SohoParm("state:houdiniversion",
                       "string", ["9.0"],
                       False,
                       key="ver"),
         "now":
         soho.SohoParm("state:time", "real", [0], False, key="now"),
         "fps":
         soho.SohoParm("state:fps", "real", [24], False, key="fps"),
     }
     rop = soho.getOutputDriver()
     parms = soho.evaluate(state_parms, None, rop)
     for parm in parms:
         setattr(self, parm, parms[parm].Value[0])
     if not self.fps:
         self.fps = 24.0
     self.inv_fps = 1.0 / self.fps
     return
Example #2
0
def outputStyleSheets(now, dirtystylesheets, for_update):
    ss_parms = soho.evaluate(stylesheetParms)
    ss_declare = ss_parms['declare_stylesheets'].Value[0]
    ss_apply = ss_parms['apply_stylesheets'].Value[0]
    if dirtystylesheets is not None:
        ss_dirty_list = dirtystylesheets.split()
    else:
        ss_dirty_list = None
    # Declare style sheets and any materials used by the style sheets.
    for style in hou.styles.styles(ss_declare):
        if ss_dirty_list is None or style in ss_dirty_list:
            if ss_dirty_list is not None:
                ss_dirty_list.remove(style)
            stylesheet = hou.styles.stylesheet(style)
            (ss_bundles,
             ss_mats) = getBundlesAndMaterialsFromStyleSheet(stylesheet)
            for mat_path in ss_mats:
                if hou.node(mat_path):
                    outputMaterial(mat_path, now)
            for bundle in ss_bundles:
                outputBundle(bundle)
            cmd_textblock("stylesheet:" + style, stylesheet)

    # Remove style sheets that have been deleted.
    if ss_dirty_list is not None:
        for style in ss_dirty_list:
            cmd_textblock("stylesheet:" + style, '')

    # Output command to apply the requested style sheets.
    if for_update or (ss_apply != '' and not ss_apply.isspace()):
        cmd_stylesheet(ss_apply)
Example #3
0
 def init_state(self):
     """Queries Soho to initialize the attributes of the class"""
     state_parms = {
         "rop": soho.SohoParm("object:name", "string", key="rop"),
         "soho_outputmode": soho.SohoParm(
             "soho_outputmode", "integer", skipdefault=False, key="output_mode"
         ),
         "soho_diskfile": soho.SohoParm(
             "soho_diskfile", "string", skipdefault=False, key="disk_file"
         ),
         "hip": soho.SohoParm("$HIP", "string", key="hip"),
         "hipname": soho.SohoParm("$HIPNAME", "string", key="hipname"),
         "hipfile": soho.SohoParm("$HIPFILE", "string", key="hipfile"),
         "ver": soho.SohoParm(
             "state:houdiniversion", "string", ["9.0"], False, key="ver"
         ),
         "now": soho.SohoParm("state:time", "real", [0], False, key="now"),
         "fps": soho.SohoParm("state:fps", "real", [24], False, key="fps"),
         "pbrt_nanovdb_converter": soho.SohoParm(
             "pbrt_nanovdb_converter",
             "string",
             ["nanovdb_convert -z -f {vdb} {nanovdb}"],
             False,
             key="nanovdb_converter",
         ),
     }
     rop = soho.getOutputDriver()
     parms = soho.evaluate(state_parms, None, rop)
     for parm in parms:
         setattr(self, parm, parms[parm].Value[0])
     if not self.fps:
         self.fps = 24.0
     self.inv_fps = 1.0 / self.fps
     return
Example #4
0
 def init_state(self):
     """Queries Soho to initialize the attributes of the class"""
     state_parms = {
         'rop':
         soho.SohoParm('object:name', 'string', key='rop'),
         'hip':
         soho.SohoParm('$HIP', 'string', key='hip'),
         'hipname':
         soho.SohoParm('$HIPNAME', 'string', key='hipname'),
         'hipfile':
         soho.SohoParm('$HIPFILE', 'string', key='hipfile'),
         'ver':
         soho.SohoParm('state:houdiniversion',
                       'string', ["9.0"],
                       False,
                       key='ver'),
         'now':
         soho.SohoParm('state:time', 'real', [0], False, key='now'),
         'fps':
         soho.SohoParm('state:fps', 'real', [24], False, key='fps'),
     }
     rop = soho.getOutputDriver()
     parms = soho.evaluate(state_parms, None, rop)
     for parm in parms:
         setattr(self, parm, parms[parm].Value[0])
     if not self.fps:
         self.fps = 24.0
     self.inv_fps = 1.0 / self.fps
     return
Example #5
0
def outputBundles(now, dirtybundles, for_update):
    ss_parms = soho.evaluate(stylesheetParms)
    if for_update:
        bundle_list = dirtybundles.split()
    elif ss_parms['declare_bundles'].Value[0]:
        bundle_list = list(bundle.name() for bundle in hou.nodeBundles())
    else:
        bundle_list = []
    for bundle in bundle_list:
        outputBundle(bundle)
Example #6
0
def main():

    parameters = soho.evaluate(parameterDefines)

    #
    # init soho
    #
    logger = logging.getLogger()
    oldHandlers = logger.handlers
    handler = logging.StreamHandler(stream=sys.__stderr__)
    logger.handlers = [handler]

    ropName = parameters['ropname'].Value[0]
    node = hou.node(ropName)
    vStr = node.type().nameComponents()[-1]
    version = 0 if not vStr else int(vStr)

    now = parameters['now'].Value[0]

    soho.initialize(now, '')
    soho.lockObjects(now)

    if parameters['trange'].Value[0] == 0:
        ff = lf = int(now * parameters['fps'].Value[0] + 1)
    else:
        ff = int(parameters['f'].Value[0])
        lf = int(parameters['f'].Value[1])
    stride = int(parameters['f'].Value[2])

    sourcefiles = parameters['sourcefiles'].Value[0]
    outfile = parameters['outfile'].Value[0]

    try:

        coalesceFiles(outfile, sourcefiles, list(range(ff, lf + 1)), stride)

    except Exception as e:
        soho.error('Failed to stitch USD files: ' + str(e) + '\n' +
                   traceback.format_exc())

    finally:
        logger.handlers = oldHandlers
Example #7
0
def main():

    parameters = soho.evaluate(parameterDefines)

    #
    # init soho
    #
    logger = logging.getLogger()
    oldHandlers = logger.handlers
    handler = logging.StreamHandler( stream = sys.__stderr__ )
    logger.handlers = [handler]

    ropName = parameters['ropname'].Value[0]
    node = hou.node( ropName )
    vStr = node.type().nameComponents()[-1]
    version = 0 if not vStr else int( vStr )

    now = parameters['now'].Value[0]

    soho.initialize(now, '')
    soho.lockObjects(now)

    if parameters['trange'].Value[0] == 0:
        ff = lf = int(now * parameters['fps'].Value[0] + 1)
    else:
        ff = int(parameters['f'].Value[0])
        lf = int(parameters['f'].Value[1])
    stride = int(parameters['f'].Value[2])

    sourcefiles = parameters['sourcefiles'].Value[0]
    outfile = parameters['outfile'].Value[0]

    try:

        coalesceFiles( outfile, sourcefiles, range(ff,lf+1), stride )

    except Exception as e:
        soho.error( 'Failed to stitch USD files: ' + str(e) + '\n' + traceback.format_exc())

    finally:
        logger.handlers = oldHandlers
Example #8
0
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
    soho.SohoParm('camera', 'string', ['/obj/cam1'], False),
    'vm_picture':
    soho.SohoParm('vm_picture', 'string', ['$HIP/render/$HIPNAME.$OS.$F4.svg'],
                  False),
    'render_viewcamera':
    soho.SohoParm('render_viewcamera', 'bool', [True], False),
    'projection_attribute':
    soho.SohoParm('projection_attribute', 'string', ['uv'], False),
    'attribute_rendering_resolution':
    soho.SohoParm('attribute_rendering_resolution', 'int', [1024, 1024],
                  False),
    'attribute_scale_by_resolution':
    soho.SohoParm('attribute_scale_by_resolution', 'bool', [True], False)
}

parmlist = soho.evaluate(controlParameters)

project = bool(parmlist['render_viewcamera'].Value[0])
projection_attribute = parmlist['projection_attribute'].Value[0]
attribute_rendering_resolution = [
    parmlist['attribute_rendering_resolution'].Value[0],
    parmlist['attribute_rendering_resolution'].Value[1]
]
attribute_scale_by_resolution = bool(
    parmlist['attribute_scale_by_resolution'].Value[0])

now = parmlist['now'].Value[0]
camera = parmlist['camera'].Value[0]
fps = parmlist['fps'].Value[0]
options = {"state:autoheadlight": False}
Example #10
0
File: APS.py Project: symek/haps
    SohoParm('vm_renderengine', 'string', ['micropoly'], False, key='engine'),
    'vm_inheritproperties':
    SohoParm('vm_inheritproperties', 'int', [0], False),
    'vm_embedvex':
    SohoParm('vm_embedvex', 'int', [0], False, key='embedvex'),
    'vm_quickexit':
    SohoParm('vm_quickexit', 'int', [1], False),
    'vm_numpathmap':
    SohoParm('vm_numpathmap', 'int', [0], False),
    'vm_isuvrendering':
    SohoParm('vm_isuvrendering', 'bool', [False], False),
    'vm_defaults':
    SohoParm('vm_defaults', 'string', ['RenderProperties.json'], False),
}

parmlist = soho.evaluate(controlParameters)
options = {}
now = parmlist['now'].Value[0]
mode = parmlist['mode'].Value[0]
camera = parmlist['camera'].Value[0]
quickexit = parmlist['vm_quickexit'].Value[0]
propdefs = parmlist['vm_defaults'].Value[0]

if mode != 'default':
    # Don't allow for nested evaluation in IPR mode
    inheritedproperties = False
else:
    inheritedproperties = parmlist['vm_inheritproperties'].Value[0]

options = {}
if inheritedproperties:
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()
Example #12
0
    # The time at which the scene is being rendered
    'now'     : SohoParm('state:time',  'real', [0], False,  key='now'),
    'fps'     : SohoParm('state:fps',   'real', [24], False, key='fps'),
    'camera'  : SohoParm('camera', 'string', ['/obj/cam1'], False),
    'picture' : SohoParm('vm_picture', 'string', ['ip'], False),
    'samples' : SohoParm('vm_samples', 'real', [2], False),
    'sampler' : SohoParm('vm_sampler', 'string', ['ldsampler'], False),
    'reflectlimit' : SohoParm('vm_reflectlimit', 'int', [1], False),
    'integrator' : SohoParm('vm_integrator', 'string', ['path'], False),
     'camera' : SohoParm('camera', 'string', ['/obj/cam1'], False),
     'skip_geo_export' : SohoParm('skip_geo_export', 'int', [0], False)}



# Evaluate the control parameters to determine settings for the render
parmlist = soho.evaluate(controlParameters)

# Extract the values from the evaluation
now     = parmlist['now'].Value[0]
camera  = parmlist['camera'].Value[0]
fps     = parmlist['fps'].Value[0]
picture = parmlist['vm_picture'].Value[0]
samples = parmlist['vm_samples'].Value[0]
sampler = parmlist['vm_sampler'].Value[0]
reflectlimit = parmlist['vm_reflectlimit'].Value[0]
integrator   = parmlist['vm_integrator'].Value[0]
camera       = parmlist['camera'].Value[0]
skip_geo_export = parmlist['skip_geo_export'].Value[0]


if not soho.initialize(now, camera):
Example #13
0
clockstart = time.clock()

controlParameters = {
    # The time at which the scene is being rendered
    'now'     : SohoParm('state:time', 'real',  [0], False,  key='now'),

    'main'    : SohoParm('render_viewcamera','int', [1], False, key='main'),
    'decl'    : SohoParm('declare_all_shops', 'int', [0], False, key='decl'),
    'engine'  : SohoParm('vm_renderengine',  'string', ['micropoly'],
                                            False, key='engine'),
    'vm_inheritproperties' : SohoParm('vm_inheritproperties', 'int', [0], False),
    'vm_embedvex' :SohoParm('vm_embedvex',  'int', [0], False, key='embedvex'),
}

parmlist = soho.evaluate(controlParameters)

now     = parmlist['now'].Value[0]
IFDapi.ForceEmbedVex = parmlist['embedvex'].Value[0]
decl_shops = parmlist['decl'].Value[0]

inheritedproperties = parmlist['vm_inheritproperties'].Value[0]

options = {}
if inheritedproperties:
    # Turn off object->output driver inheritance
    options['state:inheritance'] = '-rop'

    
if not soho.initialize(now, None):
    soho.error("Unable to initialize rendering module")
Example #14
0
def declareBakingParms(now, for_update):
    plist = soho.evaluate(bakingParms, now)
    for pname, parm in plist.iteritems():
        if parm.Value == parm.Default:
            continue
        cmd_declare('global', parm.Type, 'global:%s' % pname, parm.Value)
Example #15
0
    return (frameRange, defaultPrim, firstRoot)


###############################################################################
# parameters
###############################################################################

parameterDefines = {
    'f'         : soho.SohoParm('f', 'real', [1, 1, 1], False),
    'now'       : soho.SohoParm('state:time', 'real', [0], False, key = 'now'),
    'destfile'  : soho.SohoParm('destfile', 'string', [''], False ),
    'path'      : soho.SohoParm('path', 'string', [''], False ),
    'reffile'   : soho.SohoParm('reffile', 'string', [''], False ),
}

parameters = soho.evaluate(parameterDefines)

#
# init soho
#
now = parameters['now'].Value[0]
soho.initialize(now, '')
soho.lockObjects(now)

destFile =  parameters['destfile'].Value[0]
path     =  parameters['path'].Value[0]
reffile  =  parameters['reffile'].Value[0]

try:

    insertReference( destFile, path, reffile )
Example #16
0
def soho_render():
    control_parms = {
        # The time at which the scene is being rendered
        'now': SohoParm('state:time', 'real', [0], False, key='now'),
        'fps': SohoParm('state:fps', 'real', [24], False, key='fps'),
        'camera': SohoParm('camera', 'string', ['/obj/cam1'], False),
    }

    parms = soho.evaluate(control_parms)

    now = parms['now'].Value[0]
    camera = parms['camera'].Value[0]
    fps = parms['fps'].Value[0]

    options = {'state:precision': 6}
    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 = None
        forcelights = sololight
        forcelightsparm = 'sololight'

    # First, we add objects based on their display flags or dimmer values
    soho.addObjects(now, stdobject, stdlights, '', True)
    soho.addObjects(now, forceobject, forcelights, '', False)
    soho.removeObjects(now, excludeobject, excludelights, '')

    # Lock off the objects we've selected
    soho.lockObjects(now)

    with hou.undos.disabler(), scene_state:
        PBRTscene.render(cam, now)
    return
Example #17
0
def soho_render():
    control_parms = {
        # The time at which the scene is being rendered
        "now": SohoParm("state:time", "real", [0], False, key="now")
    }

    parms = soho.evaluate(control_parms)

    now = parms["now"].Value[0]
    camera = None

    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),
        "forceobject": SohoParm("forceobject", "string", [""], False),
        "excludeobject": SohoParm("excludeobject", "string", [""], False),
    }

    objparms = soho.evaluate(object_selection, now)

    stdobject = objparms["vobject"].Value[0]
    forceobject = objparms["forceobject"].Value[0]
    excludeobject = objparms["excludeobject"].Value[0]

    # First, we add objects based on their display flags or dimmer values
    soho.addObjects(now,
                    stdobject,
                    "",
                    "",
                    True,
                    geo_parm="vobject",
                    light_parm="",
                    fog_parm="")
    soho.addObjects(
        now,
        forceobject,
        "",
        "",
        False,
        geo_parm="forceobject",
        light_parm="",
        fog_parm="",
    )
    soho.removeObjects(now,
                       excludeobject,
                       "",
                       "",
                       geo_parm="excludeobject",
                       light_parm="",
                       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.archive(now)
            finally:
                pr.disable()
                pr.dump_stats("hou-prbtarchive.stats")
        else:
            PBRTscene.archive(now)
    return
Example #18
0
    return (frameRange, defaultPrim, firstRoot)


###############################################################################
# parameters
###############################################################################

parameterDefines = {
    'f': soho.SohoParm('f', 'real', [1, 1, 1], False),
    'now': soho.SohoParm('state:time', 'real', [0], False, key='now'),
    'destfile': soho.SohoParm('destfile', 'string', [''], False),
    'path': soho.SohoParm('path', 'string', [''], False),
    'reffile': soho.SohoParm('reffile', 'string', [''], False),
}

parameters = soho.evaluate(parameterDefines)

#
# init soho
#
now = parameters['now'].Value[0]
soho.initialize(now, '')
soho.lockObjects(now)

destFile = parameters['destfile'].Value[0]
path = parameters['path'].Value[0]
reffile = parameters['reffile'].Value[0]

try:

    insertReference(destFile, path, reffile)
Example #19
0
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()