Exemplo n.º 1
0
    def _create_sgtk_parms(self, node):
        """
        Create the parameters that are going to live within the sgtk folder.

        :param node: A :class:`hou.Node` instance.

        :rtype: list(:class:`hou.ParmTemplate`)
        """
        templates = super(AlembicNodeHandler, self)._create_sgtk_parms(node)

        templates[-1].setJoinWithNext(True)

        choices = self.get_work_template(node).keys["identifier"].labelled_choices
        sgtk_abc_identifier = hou.MenuParmTemplate(
            self.SGTK_ABC_INDENTIFIER,
            "Type Identifier",
            choices.keys(),
            menu_labels=choices.values(),
            script_callback=self.generate_callback_script_str("refresh_file_path"),
            script_callback_language=hou.scriptLanguage.Python,
        )
        sgtk_abc_identifier.setConditional(
            hou.parmCondType.DisableWhen, "{ use_sgtk != 1 }"
        )
        sgtk_abc_identifier.setJoinWithNext(True)
        templates.append(sgtk_abc_identifier)

        sgtk_single_frame = self._build_single_file_parm(True)
        templates.append(sgtk_single_frame)

        return templates
Exemplo n.º 2
0
def parm_create_menu(node, name, label, join, callback):
    pass
    menu_labels = ['(type)', 'Beat', 'Area', 'Connect', 'Mask', 'Sign']
    menu_items = [
        '(type)', 'midi_beat', 'midi_area', 'midi_connect', 'midi_mask',
        'midi_sign'
    ]
    new_template = hou.MenuParmTemplate(
        name,
        label,
        menu_items,
        menu_labels,
        join_with_next=True,
        script_callback=None,
        script_callback_language=hou.scriptLanguage.Python)

    try:
        ptg = node.parmTemplateGroup()
        #new_template.setMenuItems(menu_items)
        #new_template.setMenuLabels(menu_items)
        ptg.addParmTemplate(new_template)
        node.setParmTemplateGroup(ptg)
        existed = 0
    except:
        existed = 1
def hda_parameter_setup(hda, geo, project):
    parmGroup = hda.parmTemplateGroup()
    projectName = project.get_name().lower().replace(' ', '_')
    projectFolder = hou.FolderParmTemplate(projectName, project.get_name(), folder_type=hou.folderType.Tabs, default_value=0, ends_tab_group=False)

    source_menu = hou.MenuParmTemplate('source', 'Source', ('set', 'animated', 'object_space'), menu_labels=('Set', 'Animated', 'Object Space'), default_value=2)
    source_menu_index = hou.IntParmTemplate('source_index', 'Source Index', 1, is_hidden=True, default_expression=('ch("source")',))

    projectFolder.addParmTemplate(source_menu)
    projectFolder.addParmTemplate(source_menu_index)
    cook_script='hou.node("./' + geo.name() + '").parm("cook").pressButton()\nprint "Asset Refreshed"'
    projectFolder.addParmTemplate(create_shot_menu(hideWhen='source_index != 1', callback_script=cook_script))
    projectFolder.addParmTemplate(create_set_menu(hideWhen='source_index != 0', callback_script=cook_script))
    hide_toggle = hou.ToggleParmTemplate('hide', 'Hide')
    projectFolder.addParmTemplate(hide_toggle)
    recook = hou.ButtonParmTemplate('re_cook_hda', 'Reload', script_callback=cook_script, script_callback_language=hou.scriptLanguage.Python)
    projectFolder.addParmTemplate(recook)
    version = hou.IntParmTemplate('abcversion', 'Alembic Version', 1)
    projectFolder.addParmTemplate(version)
    lightlink = hou.StringParmTemplate("lightmask", "Light Mask", 1, default_value=(["*"]), string_type=hou.stringParmType.NodeReferenceList) #, menu_items=([]), menu_labels=([]), icon_names=([]))
    lightlink.setTags({"opfilter": "!!OBJ/LIGHT!!", "oprelative": "/"})
    projectFolder.addParmTemplate(lightlink)
    auto_archive = hou.properties.parmTemplate(get_latest_prman(),"ri_auto_archive")
    auto_archive.setDefaultValue(("exist",))
    projectFolder.addParmTemplate(auto_archive)
    parmGroup.addParmTemplate(projectFolder)
    hda.type().definition().setParmTemplateGroup(parmGroup)
    hda.parm("ri_auto_archive").set("force")

    return hda
Exemplo n.º 4
0
def EnumParmTemplate(parmName, parmLabel, parmDesc):
    parmArgs = {}
    parmArgs['menu_items'] = [item[0] for item in parmDesc['items']]
    parmArgs['menu_labels'] = [item[1] for item in parmDesc['items']]
    parmArgs['default_value'] = next(
        (i for i, x in enumerate(parmArgs['menu_items'])
         if x == parmDesc['default']), 0)
    return hou.MenuParmTemplate(parmName, parmLabel, **parmArgs)
Exemplo n.º 5
0
def intParm(p, dim=1, parent=None):
    name = parmName(p.name, prefix=parent)
    label = parmLabel(p)

    # only simple floats have min/max values
    if dim == 1:
        default = [(p.defaultValue.value)]
        initialValue = [p.getTypedValue()]
        min_val = 0
        max_val = 10
        min_lock = max_lock = False
        naming = hou.parmNamingScheme.Base1
        if p.hasMinValue():
            min_val = p.minValue
            min_lock = True
        if p.hasMaxValue():
            max_val = p.maxValue
            max_lock = True

    else:
        default = list(p.defaultValue.value)
        initialValue = list(p.getTypedValue())
        min_val = 0
        max_val = 10
        min_lock = max_lock = False
        naming = hou.parmNamingScheme.XYZW

    # Houdini can only handle presets for dim 1 ints, and even then its quite messy...
    if dim == 1 and p.presetsOnly:
        parm = hou.MenuParmTemplate(name,
                                    label,
                                    default_value=p.presetValues().index(
                                        p.defaultValue),
                                    help=p.description,
                                    **presetsMenuArgs(p))

        initialValue = [p.presetValues().index(p.getValue())]
    else:
        parm = hou.IntParmTemplate(name,
                                   label,
                                   dim,
                                   default_value=default,
                                   min=min_val,
                                   max=max_val,
                                   min_is_strict=min_lock,
                                   max_is_strict=max_lock,
                                   naming_scheme=naming,
                                   help=p.description)

    return {'name': name, 'tuple': parm, 'initialValue': initialValue}
Exemplo n.º 6
0
def c_collisionshape(n):
	group = n.parmTemplateGroup()
	folder = hou.FolderParmTemplate("folder", "Collision Shape Component")
	
	folder.addParmTemplate(hou.MenuParmTemplate("shapetype", "Shape Type",("Box","Sphere","StaticPlane","Cylinder","Capsule","Cone","TriangleMesh","ConvexHull","Terrain",)))
	folder.addParmTemplate(hou.FloatParmTemplate("size", "Size",3,(1.0,1.0,1.0,)))
	folder.addParmTemplate(hou.FloatParmTemplate("offsetposition", "Offset Position",3))
	folder.addParmTemplate(hou.FloatParmTemplate("offsetrotation", "Offset Rotation",3))
	folder.addParmTemplate(hou.StringParmTemplate("model", "Model", 1))
	folder.addParmTemplate(hou.FloatParmTemplate("lodlevel", "LOD Level", 1 ) )
	folder.addParmTemplate(hou.FloatParmTemplate("collisionmargin", "Collision Margin", 1 ,(0.04,)) )
	folder.addParmTemplate(hou.FloatParmTemplate("customnodeid", "CustomGeometry NodeID", 1 ) )

	group.append(folder)
	n.setParmTemplateGroup(group)
Exemplo n.º 7
0
    def _create_sgtk_parms(self, node):
        """
        Create the parameters that are going to live within the sgtk folder.

        :param node: A :class:`hou.Node` instance.

        :rtype: list(:class:`hou.ParmTemplate`)
        """
        templates = super(GeometryNodeHandler, self)._create_sgtk_parms(node)

        templates[-1].setJoinWithNext(True)

        sgtk_single_frame = self._build_single_file_parm(False)
        sgtk_single_frame.setJoinWithNext(True)
        templates.append(sgtk_single_frame)

        choices = self.get_work_template(
            node).keys["extension"].labelled_choices

        ordered_keys = sorted(choices.keys())
        ordered_values = []
        for key in ordered_keys:
            ordered_values.append(choices[key])

        sgtk_cache_ext = hou.MenuParmTemplate(
            self.SGTK_CACHE_EXTENSION,
            "File Extension",
            ordered_keys,
            menu_labels=ordered_values,
            script_callback=self.generate_callback_script_str(
                "refresh_file_path"),
            script_callback_language=hou.scriptLanguage.Python,
        )
        sgtk_cache_ext.setConditional(hou.parmCondType.DisableWhen,
                                      "{ use_sgtk != 1 }")
        templates.append(sgtk_cache_ext)

        return templates
Exemplo n.º 8
0
def c_light(n):
	group = n.parmTemplateGroup()
	folder = hou.FolderParmTemplate("folder", "Static Model Component")

	folder.addParmTemplate(hou.MenuParmTemplate("lighttype", "Light Type",("Directional","Spot","Point",),default_value=2))
	folder.addParmTemplate(hou.FloatParmTemplate("color", "Color",4,(1.0,1.0,1.0,1.0,)))
	folder.addParmTemplate(hou.FloatParmTemplate("specintensity", "Spec Intensity", 1, (1.0,) ) )
	folder.addParmTemplate(hou.FloatParmTemplate("brightmult", "Brightness Multiplier", 1, (1.0,) ) )
	folder.addParmTemplate(hou.FloatParmTemplate("range", "Range", 1, (10.0,) ) )
	folder.addParmTemplate(hou.FloatParmTemplate("spotfov", "Spot FOV", 1, (30.0,) ) )
	folder.addParmTemplate(hou.FloatParmTemplate("spotaspectratio", "Spot Aspect Ratio", 1, (1.0,) ) )
	folder.addParmTemplate(hou.StringParmTemplate("atttext", "Attenuation Texture", 1))
	folder.addParmTemplate(hou.StringParmTemplate("lightshapetext", "Light Shape Texture",1))
	folder.addParmTemplate(hou.ToggleParmTemplate("isoccludable", "Can Be Occluded", 1))
	folder.addParmTemplate(hou.ToggleParmTemplate("castshadows", "Cast Shadows", 0))
	folder.addParmTemplate(hou.ToggleParmTemplate("prevertex", "Per Vertex", 0))
	folder.addParmTemplate(hou.FloatParmTemplate("drawdistance", "Draw Distance", 1 ) )
	folder.addParmTemplate(hou.FloatParmTemplate("fadedistance", "Fade Distance", 1 ) )
	folder.addParmTemplate(hou.FloatParmTemplate("shadowdistance", "Shadow Distance", 1 ) )
	folder.addParmTemplate(hou.FloatParmTemplate("shadowfadedistance", "Shadow Fade Distance", 1 ) )
	folder.addParmTemplate(hou.FloatParmTemplate("shadowintensity", "Shadow Intensity", 1 ) )
	folder.addParmTemplate(hou.FloatParmTemplate("shadowresolution", "Shadow Resolution", 1 ) )
	folder.addParmTemplate(hou.ToggleParmTemplate("focustoscene", "Focus To Scene", 1))
	folder.addParmTemplate(hou.ToggleParmTemplate("nonuniformview", "Non Uniform View", 1))
	folder.addParmTemplate(hou.ToggleParmTemplate("autoreducesize", "Auto Reduce Size", 1))
	folder.addParmTemplate(hou.FloatParmTemplate("cmssplits", "CMS Splits",3,(1000.0,0.0,0.0,)))
	folder.addParmTemplate(hou.FloatParmTemplate("cmsfadestart", "CMS Fade Start", 1, (0,8,) ) )
	folder.addParmTemplate(hou.FloatParmTemplate("cmsbiasautoadjust", "CMS Bias Auto Adjust", 1, (1.0,) ) )
	folder.addParmTemplate(hou.FloatParmTemplate("viewsizequantize", "View Size Quantize", 1, (0.5,) ) )
	folder.addParmTemplate(hou.FloatParmTemplate("viewsizemin", "View Size Minimum", 1, (1.0,) ) )
	folder.addParmTemplate(hou.FloatParmTemplate("depthconstantbias", "Depth Constant Bias", 1, (0.0002,) ) )
	folder.addParmTemplate(hou.FloatParmTemplate("depthslopebias", "Depth Slope Bias", 1, (0.5,) ) )
	folder.addParmTemplate(hou.FloatParmTemplate("nearfarclip", "Near Far Clip Ratio", 1, (0.002,) ) )
	folder.addParmTemplate(hou.IntParmTemplate("viewmask", "View Mask",1,(-1,)))
	folder.addParmTemplate(hou.IntParmTemplate("lightmask", "Light Mask",1,(-1,)))

	group.append(folder)
	n.setParmTemplateGroup(group)
Exemplo n.º 9
0
def c_rigidbody(n):
	group = n.parmTemplateGroup()
	folder = hou.FolderParmTemplate("folder", "Rigid Body Component")

	folder.addParmTemplate(hou.FloatParmTemplate("mass", "Mass",1))
	folder.addParmTemplate(hou.FloatParmTemplate("friction", "Friction",1,(0.5,)))
	folder.addParmTemplate(hou.FloatParmTemplate("anifriction", "Anistropic Friction",3,(1.0,1.0,1.0,)))
	folder.addParmTemplate(hou.FloatParmTemplate("rollfriction", "Rolling Friction",1))
	folder.addParmTemplate(hou.FloatParmTemplate("restitution", "Restitution",1))
	folder.addParmTemplate(hou.FloatParmTemplate("linearvelocity", "Linear Velocity",3))
	folder.addParmTemplate(hou.FloatParmTemplate("angularvelocity", "Angular Velocity",3))
	folder.addParmTemplate(hou.FloatParmTemplate("linearfactor", "Linear Factor",3,(1.0,1.0,1.0,)))
	folder.addParmTemplate(hou.FloatParmTemplate("angularfactor", "Angular Factor",3,(1.0,1.0,1.0,)))
	folder.addParmTemplate(hou.FloatParmTemplate("lineardamping", "Linear Damping",1))
	folder.addParmTemplate(hou.FloatParmTemplate("angulardamping", "Angular Damping",1))
	folder.addParmTemplate(hou.FloatParmTemplate("linearrest", "Linear Rest Threshold",1,(0.8,)))
	folder.addParmTemplate(hou.FloatParmTemplate("angluarrest", "Angular Rest Threshold",1,(1.0,)))

	folder.addParmTemplate(hou.IntParmTemplate("collisionlayer", "Collision Layer",1,(1,)))
	folder.addParmTemplate(hou.IntParmTemplate("collisionmask", "Collision Mask",1,(-1,)))

	folder.addParmTemplate(hou.FloatParmTemplate("contactthreshold", "Contact Threshold",1,(1e+18,)))
	folder.addParmTemplate(hou.FloatParmTemplate("ccdradius", "CCD Radius",1))
	folder.addParmTemplate(hou.FloatParmTemplate("ccdmotion", "CCD Motion Threshold",1))

	#This needs to be a drop down
	#never, when active, always
	folder.addParmTemplate(hou.MenuParmTemplate("collisioneventmode", "Collision Event Mode",("Never","When Active","Always",),default_value=1))

	folder.addParmTemplate(hou.ToggleParmTemplate("usegravity", "Use Gravity", 0))
	folder.addParmTemplate(hou.ToggleParmTemplate("iskinematic", "Is Kinematic", 1))
	folder.addParmTemplate(hou.ToggleParmTemplate("istrigger", "Is Trigger", 0))

	folder.addParmTemplate(hou.FloatParmTemplate("gravityoverride", "Gravity Override",3))

	group.append(folder)
	n.setParmTemplateGroup(group)
Exemplo n.º 10
0
def resizeFluidSops(kwargs):
    """ Select fluid and set it up to be resizeable.
    """
    sceneviewer = toolutils.activePane(kwargs)
    if not isinstance(sceneviewer, hou.SceneViewer):
        raise hou.Error("Invalid pane type for this operation.")

    # Select the target fluid box.
    fluidobjects = sceneviewer.selectDynamics(
        prompt="Select fluid box to resize.  Press Enter to complete.",
        allow_multisel=False)
    if len(fluidobjects) < 1:
        raise hou.Error(
            "No fluid container selected to set initial conditions.")
    fluidobject = fluidobjects[0]

    fluidnode = doptoolutils.getDopObjectCreator(fluidobject)
    if fluidnode is None:
        raise hou.Error("No fluid object node found.")
    """ Create and configure the reference container for resizing.
    """

    dopnet = doptoolutils.getCurrentDopNetwork()
    refobject = fluidnode.parent().parent().createNode(
        "geo", "fluid_resize_container", run_init_scripts=False)
    fluidfields = refobject.createNode("dopio", "fluidfields")
    fluidfields.parm("doppath").set(dopnet.path())
    fluidfields.setParmExpressions(
        {"defobj": "chs(\"" + fluidnode.path() + "/object_name\")"})
    fluidfields.parm("fields").set(2)
    fluidfields.parm("fieldname1").set("density")
    fluidfields.parm("fieldname2").set("vel")
    parms = refobject.parmTemplateGroup()
    parms.hideFolder("Transform", True)
    parms.hideFolder("Material", True)
    parms.hideFolder("Render", True)
    parms.hideFolder("Misc", True)
    ref_folder = hou.FolderParmTemplate("ref_folder", "Resize Container")
    ref_folder.addParmTemplate(
        hou.IntParmTemplate(
            "nptsperarea",
            "Scatter per Area",
            1,
            default_value=([5000]),
            min=1000,
            max=20000,
            help="Scatter points on simulated density to calculate bounds"))
    ref_folder.addParmTemplate(
        hou.FloatParmTemplate(
            "treshold",
            "Density Treshold",
            1,
            default_value=([0]),
            min=0,
            max=1,
            help="Delete density below this value prior to scattering points"))
    ref_folder.addParmTemplate(hou.SeparatorParmTemplate("sep1"))
    ref_folder.addParmTemplate(
        hou.LabelParmTemplate("merge_source", "Merge Sources"))
    ref_folder.addParmTemplate(
        hou.ButtonParmTemplate(
            "update",
            "Update sources",
            help="Push this to update ObjectMerge node inside",
            tags={
                "script_callback":
                "import adddoputils; adddoputils.updateSourcesButton()",
                "script_callback_language": "python"
            }))
    ref_folder.addParmTemplate(
        hou.IntParmTemplate(
            "source_activation",
            "All Sources Activation",
            1,
            default_value=([1]),
            min=0,
            max=1,
            min_is_strict=True,
            max_is_strict=True,
            help=
            "Activation of merging all of the listed sources and additional objects"
        ))
    ref_folder.addParmTemplate(
        hou.MenuParmTemplate(
            "xformtype", "Transform", "012",
            ("None", "Into This Object", "Into Specified Object"), 1))
    ref_folder.addParmTemplate(
        hou.StringParmTemplate("xformpath",
                               "Transform object",
                               1,
                               "",
                               hou.parmNamingScheme.Base1,
                               hou.stringParmType.NodeReference,
                               disable_when=("{ xformtype != 2 }")))

    sources_folder = hou.FolderParmTemplate(
        "source_folder",
        "Sources to Merge",
        folder_type=hou.folderType.MultiparmBlock)
    sources_folder.addParmTemplate(
        hou.ToggleParmTemplate("source_activation#",
                               "Source # Activation",
                               default_value=True))
    sources_folder.addParmTemplate(
        hou.StringParmTemplate("objpath#", "Object #", 1, "",
                               hou.parmNamingScheme.Base1,
                               hou.stringParmType.NodeReference))
    sources_folder.addParmTemplate(
        hou.StringParmTemplate("group#", "Group #", 1, "",
                               hou.parmNamingScheme.Base1,
                               hou.stringParmType.Regular))

    ref_folder.addParmTemplate(sources_folder)
    parms.append(ref_folder)
    refobject.setParmTemplateGroup(parms)

    keep_density = refobject.createNode("blast", "keep_density")
    keep_density.setFirstInput(fluidfields)
    keep_density.parm("group").set("@name==vel*")

    keep_vel = refobject.createNode("blast", "keep_vel")
    keep_vel.setFirstInput(fluidfields)
    keep_vel.parm("group").set("@name==density")

    # VOLUME VOP clamping density field below given treshold
    density_treshold = keep_density.createOutputNode("volumevop",
                                                     "density_treshold")

    vopglobals = density_treshold.node("volumevopglobal1")

    treshold = density_treshold.createNode("parameter", "treshold")
    treshold.parm("parmname").set("treshold")
    treshold.parm("parmlabel").set("Treshold")

    compare_density = density_treshold.createNode("compare", "compare_density")
    compare_density.parm("cmp").set("gte")
    compare_density.setInput(0, vopglobals, 1)
    compare_density.setInput(1, treshold, 0)

    twoway = compare_density.createOutputNode("twoway", "switch_density")
    twoway.setInput(1, vopglobals, 1)

    vop_output = density_treshold.node("volumevopoutput1")
    vop_output.setFirstInput(twoway, 0)
    density_treshold.setParmExpressions({"treshold": "ch(\"../treshold\")"})
    # End of VOLUME VOP

    scatter = refobject.createNode("scatter", "scatter")
    scatter.setFirstInput(density_treshold)
    scatter.parm("ptsperarea").set(1)
    scatter.setParmExpressions({"nptsperarea": "ch(\"../nptsperarea\")"})

    add_particles = scatter.createOutputNode("add", "add_particles")
    add_particles.parm("addparticlesystem").set(1)

    # VOP SOP adding velocity field to density-based pointcloud
    add_vel = refobject.createNode("vopsop", "add_vel")
    add_vel.parm("vex_numthreads").set(1)
    add_vel.setFirstInput(add_particles)
    add_vel.setInput(1, keep_vel, 0)

    globals = add_vel.node("global1")
    volumesamplex = add_vel.createNode("volumesample", "volumesample_x")
    volumesamplex.setInput(2, globals, 0)
    volumesamplex.parm("input_index").set(1)
    volumesamplex.parm("primnum").set(0)

    volumesampley = add_vel.createNode("volumesample", "volumesample_y")
    volumesampley.setInput(2, globals, 0)
    volumesampley.parm("input_index").set(1)
    volumesampley.parm("primnum").set(1)

    volumesamplez = add_vel.createNode("volumesample", "volumesample_z")
    volumesamplez.setInput(2, globals, 0)
    volumesamplez.parm("input_index").set(1)
    volumesamplez.parm("primnum").set(2)

    vel = volumesamplex.createOutputNode("floattovec", "vel")
    vel.setInput(1, volumesampley, 0)
    vel.setInput(2, volumesamplez, 0)

    vel_by_fps = vel.createOutputNode("divconst", "vel_by_fps")
    vel_by_fps.setParmExpressions({"divconst": "$FPS"})

    add_vector = globals.createOutputNode("add", "add_vector")
    add_vector.setNextInput(vel_by_fps, 0)

    vex_output = add_vel.node("output1")
    vex_output.setFirstInput(add_vector, 0)
    # End of VOP SOP

    merge1 = refobject.createNode("merge", "merge1")
    merge1.setFirstInput(add_particles)
    merge1.setInput(1, add_vel, 0)

    bound = merge1.createOutputNode("bound", "bound")

    # Box to switch from after first simulation frame
    initial_box = refobject.createNode("box", "initial_box")
    initial_box.setParmExpressions({
        "sizex":
        "ch(\"" + initial_box.relativePathTo(fluidnode) + "/sizex\")",
        "sizey":
        "ch(\"" + initial_box.relativePathTo(fluidnode) + "/sizey\")",
        "sizez":
        "ch(\"" + initial_box.relativePathTo(fluidnode) + "/sizez\")"
    })
    initial_box.setParmExpressions({
        "tx":
        "ch(\"" + initial_box.relativePathTo(fluidnode) + "/tx\")",
        "ty":
        "ch(\"" + initial_box.relativePathTo(fluidnode) + "/ty\")",
        "tz":
        "ch(\"" + initial_box.relativePathTo(fluidnode) + "/tz\")"
    })

    initial_switch = initial_box.createOutputNode("switch", "initial_switch")
    initial_switch.setParmExpressions({
        "input":
        "$F>ch(\"" + initial_switch.relativePathTo(fluidnode) +
        "/createframe\")",
    })
    initial_switch.setInput(1, bound, 0)

    # Null to switch to if merging of simulation sources is disabled
    no_active_source = refobject.createNode("null", "no_active_source")

    merge_source = refobject.createNode("object_merge", "merge_source")
    merge_source.setParmExpressions({
        "numobj": "ch(\"../source_folder\")",
        "xformtype": "ch(\"../xformtype\")"
    })
    merge_source.parm("xformpath").set("`chsop(\"../xformpath\")`")
    numobj = merge_source.parm("numobj").eval()

    source_switch = no_active_source.createOutputNode("switch",
                                                      "source_switch")
    source_switch.setParmExpressions({"input": "ch(\"../source_activation\")"})
    source_switch.setInput(1, merge_source, 0)

    merge2 = initial_switch.createOutputNode("merge", "merge2")
    merge2.setInput(1, source_switch, 0)

    bound = merge2.createOutputNode("bound", "bound")

    unroll_edges = bound.createOutputNode("ends", "unroll_edges")
    unroll_edges.parm("closeu").set(4)

    out = unroll_edges.createOutputNode("null", "OUT")

    density_treshold.layoutChildren()
    add_vel.layoutChildren()
    refobject.layoutChildren()

    out.setDisplayFlag(True)
    out.setRenderFlag(True)

    resize = resizeFluidToMatchSops(fluidnode, refobject)
    resize.setCurrent(True, True)
    sceneviewer.enterCurrentNodeState()
Exemplo n.º 11
0
    def _customise_parameter_group(self, node, parameter_group, sgtk_folder):
        """
        Here is where you define where the sgtk folder is to be placed, but also
        any other parameters that you wish to add to the node.

        :param node: A :class:`hou.Node` instance.
        :param parameter_group: The node's :class:`ParmGroup`.
        :param sgtk_folder: A :class:`hou.ParmFolderTemplate` containing sgtk
            parameters.
        """
        index = parameter_group.index_of_template("images6")
        parameter_group.insert_template(index, sgtk_folder)

        # Insert sgtk folder before vm_picture
        images_folder = parameter_group.get("images6")

        # aovs
        image_planes_folder = images_folder.get("output6_1")
        vm_numaux = image_planes_folder.get(self.AOV_COUNT)
        vm_numaux_template = vm_numaux.template
        vm_numaux_template.setScriptCallback(
            self.generate_callback_script_str("lock_aov_parms"))
        vm_numaux_template.setScriptCallbackLanguage(hou.scriptLanguage.Python)

        index = vm_numaux.index_of_template(self.AOV_NAME_TMPL.format("#"))
        sgtk_aov_name = hou.StringParmTemplate(
            self.SGTK_AOV_NAME_TMPL.format("#"),
            "Channel Name",
            1,
            script_callback=self.generate_callback_script_str(
                "update_aov_path"),
            script_callback_language=hou.scriptLanguage.Python,
        )
        sgtk_aov_name.setConditional(
            hou.parmCondType.DisableWhen,
            '{ vm_disable_plane# == 1 } { vm_variable_plane# == "" }',
        )
        sgtk_aov_name.setConditional(hou.parmCondType.HideWhen,
                                     "{ use_sgtk != 1 }")
        vm_numaux.insert_template(index, sgtk_aov_name)

        vm_channel_plane = vm_numaux.get(self.AOV_NAME_TMPL.format("#"))
        vm_channel_plane_template = vm_channel_plane.template
        vm_channel_plane_template.setConditional(hou.parmCondType.HideWhen,
                                                 "{ use_sgtk == 1 }")

        vm_filename_plane = vm_numaux.get(self.AOV_FILE_TMPL.format("#"))
        vm_filename_plane_template = vm_filename_plane.template
        vm_filename_plane_template.setDefaultValue((self.AOV_ERROR, ))

        # deep
        deep_folder = images_folder.get("output6_2")
        index = deep_folder.index_of_template(self.VM_DCMFILENAME)
        deep_template_name = self.extra_args.get(self.DCM_WORK_TEMPLATE)
        deep_template = self.parent.get_template_by_name(deep_template_name)
        choices = deep_template.keys["extension"].labelled_choices
        sgtk_deep_ext = hou.MenuParmTemplate(
            self.SGTK_DEEP_EXT,
            "Extension (sgtk only)",
            choices.keys(),
            menu_labels=choices.values(),
            script_callback=self.generate_callback_script_str(
                "update_deep_paths"),
            script_callback_language=hou.scriptLanguage.Python,
        )
        sgtk_deep_ext.setConditional(
            hou.parmCondType.DisableWhen,
            "{ use_sgtk != 1 } { vm_deepresolver == null }",
        )
        deep_folder.insert_template(index, sgtk_deep_ext)

        # cryptomatte
        cryptomatte_folder = images_folder.get("output6_3")
        vm_cryptolayers = cryptomatte_folder.get(self.VM_CRYPTOLAYERS)
        vm_cryptolayers_template = vm_cryptolayers.template
        vm_cryptolayers_template.setScriptCallback(
            self.generate_callback_script_str("lock_crypto_parms"))
        vm_cryptolayers_template.setScriptCallbackLanguage(
            hou.scriptLanguage.Python)

        vm_cryptolayername = vm_cryptolayers.get(
            self.VM_CRYPTOLAYERNAME_TMPL.format("#"))
        vm_cryptolayername_template = vm_cryptolayername.template
        vm_cryptolayername_template.setConditional(hou.parmCondType.HideWhen,
                                                   "{ use_sgtk == 1 }")

        vm_cryptolayeroutput = vm_cryptolayers.get(
            self.VM_CRYPTOLAYEROUTPUT_TMPL.format("#"))
        vm_cryptolayeroutput_template = vm_cryptolayeroutput.template
        vm_cryptolayeroutput_template.setDefaultValue((self.AOV_ERROR, ))

        vm_cryptolayersidecar = vm_cryptolayers.get(
            self.VM_CRYPTOLAYERSIDECAR_TMPL.format("#"))
        vm_cryptolayersidecar_template = vm_cryptolayersidecar.template
        vm_cryptolayersidecar_template.setDefaultValue((self.AOV_ERROR, ))

        index = vm_cryptolayers.index_of_template(
            self.VM_CRYPTOLAYERNAME_TMPL.format("#"))
        sgtk_cryptolayername = hou.StringParmTemplate(
            self.SGTK_CRYPTOLAYERNAME_TMPL.format("#"),
            "Channel Name",
            1,
            default_value=("CryptoMaterial", ),
            script_callback=self.generate_callback_script_str(
                "update_crypto_layer_path"),
            script_callback_language=hou.scriptLanguage.Python,
        )
        sgtk_cryptolayername.setConditional(hou.parmCondType.HideWhen,
                                            "{ use_sgtk != 1 }")
        vm_cryptolayers.insert_template(index, sgtk_cryptolayername)
def _addDisplacementControls(ptg, vrayFolder):
    ptg.appendToFolder(
        vrayFolder,
        hou.ToggleParmTemplate(
            "vray_displ_use", "Use Displacement", **{
                'tags': {
                    'spare_category': 'vray'
                },
                'default_value': True,
            }))

    ptg.appendToFolder(
        vrayFolder,
        hou.MenuParmTemplate(
            "vray_displ_type", "Type", (['0', '1', '2']), **{
                'tags': {
                    'spare_category': 'vray'
                },
                'menu_labels':
                (["Displacement", "Subdivision", "From Material"]),
                'default_value': 0,
                'conditionals': {
                    hou.parmCondType.DisableWhen: "{ vray_displ_use == 0 }",
                },
            }))

    ptg.appendToFolder(
        vrayFolder,
        hou.FolderParmTemplate(
            "vray_displ_folder_GeomDisplacedMesh", "Displacement", **{
                'parm_templates': (vfh_ptg_utils.getParmTemplatesFromDS(
                    "ObjectGeomDisplacedMesh", prefix="GeomDisplacedMesh")),
                'folder_type':
                hou.folderType.Simple,
                'tags': {
                    'spare_category': 'vray'
                },
                'conditionals': {
                    hou.parmCondType.HideWhen:
                    "{ vray_displ_use == 0 } { vray_displ_type != 0 }"
                },
            }))

    ptg.appendToFolder(
        vrayFolder,
        hou.FolderParmTemplate(
            "vray_displ_folder_GeomStaticSmoothedMesh", "Subdivision", **{
                'parm_templates': (vfh_ptg_utils.getParmTemplatesFromDS(
                    "ObjectGeomStaticSmoothedMesh",
                    prefix="GeomStaticSmoothedMesh")),
                'folder_type':
                hou.folderType.Simple,
                'tags': {
                    'spare_category': 'vray'
                },
                'conditionals': {
                    hou.parmCondType.HideWhen:
                    "{ vray_displ_use == 0 } { vray_displ_type != 1 }"
                },
            }))

    ptg.appendToFolder(
        vrayFolder,
        hou.FolderParmTemplate(
            "vray_displ_folder_shopnet", "From Material", **{
                'parm_templates': ([
                    hou.StringParmTemplate(
                        "vray_displ_shoppath", "Material", 1, **{
                            'string_type': hou.stringParmType.NodeReference,
                            'tags': {
                                'spare_category': 'vray',
                                'opfilter': '!!VOP!!',
                                'oprelative': '.',
                            }
                        })
                ]),
                'folder_type':
                hou.folderType.Simple,
                'tags': {
                    'spare_category': 'vray',
                },
                'conditionals': {
                    hou.parmCondType.HideWhen:
                    "{ vray_displ_use == 0 } { vray_displ_type != 2 }",
                },
            }))
Exemplo n.º 13
0
def addVRayDisplamentParamTemplate(ptg):
    if not ptg.findFolder("V-Ray"):
        vfh_attrs.insertInFolderAfterLastTab(ptg, ptg, hou.FolderParmTemplate("vray", "V-Ray"))

    if not ptg.findFolder(("V-Ray", "Displacement")):
        vfh_attrs.insertInFolderAfterLastTab(ptg, ptg.findFolder('V-Ray'), hou.FolderParmTemplate("vray", "Displacement"))

    folder = ("V-Ray", "Displacement")
    # enable displacement
    if not ptg.find("vray_use_displ"):
        params = { }
        params["tags"] = {'spare_category': 'vray'}
        params["default_value"] = False
        params["script_callback_language"] = hou.scriptLanguage.Python
        ptg.appendToFolder(folder, hou.ToggleParmTemplate("vray_use_displ", "Use Displacement", **params))

    # displacement type
    if not ptg.find("vray_displ_type"):
        params = { }
        params["tags"] = {'spare_category': 'vray'}
        params["default_value"] = 0
        params["menu_items"]=(['0', '1', '2'])
        params["menu_labels"]=(['From Shop Net', 'Displaced', 'Smoothed'])
        params["conditionals"]={hou.parmCondType.DisableWhen: "{ vray_use_displ == 0 }"}
        params["script_callback_language"] = hou.scriptLanguage.Python
        ptg.appendToFolder(folder, hou.MenuParmTemplate("vray_displ_type", "Displacement Type", **params))

    # params for vray_displ_type = 'shopnet'
    if not ptg.findFolder("shopnet"):
        params = { }
        params["tags"] = {'spare_category': 'vray'}
        params["folder_type"] = hou.folderType.Simple
        params["conditionals"]={hou.parmCondType.HideWhen: "{ vray_displ_type != 0 }"}
        ptg.appendToFolder(folder, hou.FolderParmTemplate("vray", "shopnet",**params))

    shopnetFolder = ("V-Ray", "Displacement", "shopnet")
    if not ptg.find("vray_displshoppath"):
        params = { }
        params["string_type"] = hou.stringParmType.NodeReference
        params["tags"] = {'spare_category': 'vray', 'opfilter': '!!SHOP!!', 'oprelative': '.'}
        params["script_callback_language"] = hou.scriptLanguage.Python
        params["conditionals"]={hou.parmCondType.HideWhen: "{ vray_displ_type != 0 }", hou.parmCondType.DisableWhen: "{ vray_use_displ == 0 }"}
        ptg.appendToFolder(shopnetFolder, hou.StringParmTemplate("vray_displshoppath", "Shop path", 1, **params))

        # params for vray_displ_type = 'GeomDisplacedMesh'
    if not ptg.findFolder("gdm"):
        params = { }
        params["tags"] = {'spare_category': 'vray'}
        params["folder_type"] = hou.folderType.Simple
        params["conditionals"]={hou.parmCondType.HideWhen: "{ vray_displ_type != 1 }"}
        ptg.appendToFolder(folder, hou.FolderParmTemplate("vray", "gdm",**params))

    gdmFolder = ("V-Ray", "Displacement", "gdm")
    displDesc = vfh_json.getPluginDesc('GeomDisplacedMesh')
    paramDescList = filter(lambda parmDesc: parmDesc['attr'] != 'displacement_tex_float', displDesc['PluginParams'])
    for parmDesc in paramDescList:
        vfh_attrs.addPluginParm(ptg, parmDesc, parmPrefix = 'GeomDisplacedMesh', parmFolder = gdmFolder)

    # params for vray_displ_type = 'GeomStaticSmoothedMesh'
    if not ptg.findFolder("gssm"):
        params = { }
        params["tags"] = {'spare_category': 'vray'}
        params["folder_type"] = hou.folderType.Simple
        params["conditionals"]={hou.parmCondType.HideWhen: "{ vray_displ_type != 2}"}
        ptg.appendToFolder(folder, hou.FolderParmTemplate("vray", "gssm",**params))

    gssmFolder = ("V-Ray", "Displacement", "gssm")

    subdivDesc = vfh_json.getPluginDesc('GeomStaticSmoothedMesh')
    paramDescList = filter(lambda parmDesc: parmDesc['attr'] != 'displacement_tex_float', subdivDesc['PluginParams'])
    for parmDesc in paramDescList:
        vfh_attrs.addPluginParm(ptg, parmDesc, parmPrefix = 'GeomStaticSmoothedMesh', parmFolder = gssmFolder)
Exemplo n.º 14
0
    def update_rop_output_paths_for_selected_nodes(self, kwargs={}):
        print "Update Rop Output Paths for Selected SOP/TOP Nodes. Note: currently not handling @attributes $attributes in element names correctly."
        self.selected_nodes = kwargs['items']

        for node in self.selected_nodes:
            print 'Name', node.name()
            if node.type().name() == 'ropfetch':
                node = node.node(node.parm('roppath').eval())
            if node:
                print 'set path', node.path()
                #hou.hscriptExpression("cd "+node.path())
                hou.cd(node.path())

                bake_names = True
                print "evaluate env vars"
                if bake_names:
                    node_name = node.name()

                    show_var = hou.hscriptExpression("${SHOW}")
                    seq_var = hou.hscriptExpression("${SEQ}")
                    shot_var = hou.hscriptExpression("${SHOT}")

                    shot_var = show_var + '.' + seq_var + '.' + shot_var
                    shotpath_var = hou.hscriptExpression("${SHOTPATH}")
                    scene_name = hou.hscriptExpression("${SCENENAME}")
                else:
                    node_name = "${OS}"

                    show_var = "${SHOW}"
                    seq_var = "${SEQ}"
                    shot_var = "${SHOT}"

                    shot_var = "${SHOW}.${SEQ}.${SHOT}"
                    shotpath_var = "${SHOTPATH}"
                    scene_name = "${SCENENAME}"

                print shot_var
                scene_name_default = scene_name
                shot_default = shot_var
                file_template_default = "`chs('shot_path')`/`chs('output_type')`/`chs('element_name')`/`chs('versionstr')`/`chs('shot')`.`chs('scene_name')`.`chs('element_name')`.`chs('versionstr')`.`chs('wedge_string')`.`chs('frame')`.`chs('file_type')`"

                # If target matches node typ in dict, then apply versioning
                print 'node type', node.type().name()
                if node.type().name() in self.output_types:
                    lookup = self.output_types[node.type().name()]
                    extension = lookup['extension']
                    print 'extension', extension
                    static_expression = lookup['static_expression']
                    out_parm_name = lookup['output']
                    # check if overide for default
                    file_template = file_template_default
                    if 'file_template' in lookup:
                        print "overiding file tempalte"
                        file_template = lookup['file_template']
                    print "file_template", file_template

                    try:
                        parm_group = node.parmTemplateGroup()
                        parm_folder = hou.FolderParmTemplate(
                            "folder", "Versioning")
                        callback_expr = \
                            """
# This allows versioning to be inherited by the multi parm db
import hou
node = hou.pwd()
parm = hou.evaluatingParm()
print 'parm callback', parm.name()
"""
                        parm_folder.setScriptCallbackLanguage(
                            hou.scriptLanguage.Python)
                        parm_folder.setScriptCallback(callback_expr)
                        #parm_folder.addParmTemplate(hou.StringParmTemplate("element_name_template", "Element Name Template", 1, ["${OS}"]))
                        parm_folder.addParmTemplate(
                            hou.StringParmTemplate("element_name_template",
                                                   "Element Name Template", 1,
                                                   ["${OS}"]))

                        element_name_parm = hou.StringParmTemplate(
                            "element_name", "Element Name", 1, [node_name])
                        #elementName.setScriptCallback(callback_expr)
                        #elementName.setScriptCallbackLanguage(hou.scriptLanguage.Python)

                        parm_folder.addParmTemplate(element_name_parm)

                        parm_folder.addParmTemplate(
                            hou.ToggleParmTemplate(
                                "auto_version",
                                "Auto Version Set To Hip Version on Execute",
                                1))

                        parm_folder.addParmTemplate(
                            hou.IntParmTemplate("version_int", "Version", 1))

                        parm_folder.addParmTemplate(
                            hou.StringParmTemplate("versionstr",
                                                   "Version String", 1, [""]))

                        parm_folder.addParmTemplate(
                            hou.StringParmTemplate("wedge_string",
                                                   "Wedge String", 1,
                                                   ["w`@wedgenum`"]))

                        parm_folder.addParmTemplate(
                            hou.StringParmTemplate("output_type",
                                                   "Output Type", 1,
                                                   [lookup['type_path']]))

                        parm_folder.addParmTemplate(
                            hou.StringParmTemplate("shot", "Shot", 1,
                                                   [shot_default]))

                        parm_folder.addParmTemplate(
                            hou.MenuParmTemplate(
                                'location',
                                'Location',
                                ("submission_location", "cloud", "onsite"),
                                ("Submission Location", "Cloud", "Onsite"),
                                default_value=0))
                        # parm_folder.addParmTemplate(hou.MenuParmTemplate("location", "Location", menu_items=(["submission_location","cloud","onsite"]), menu_labels=(["Submission Location","Cloud","Onsite"]), default_value=0, icon_names=([]), item_generator_script="", item_generator_script_language=hou.scriptLanguage.Python, menu_type=hou.menuType.Normal, menu_use_token=False, is_button_strip=False, strip_uses_icons=False)

                        parm_folder.addParmTemplate(
                            hou.StringParmTemplate("shot_path_template",
                                                   "Shot Path Template", 1,
                                                   ["${SHOTPATH}"]))

                        parm_folder.addParmTemplate(
                            hou.StringParmTemplate("shot_path", "Shot Path", 1,
                                                   [shotpath_var]))

                        parm_folder.addParmTemplate(
                            hou.StringParmTemplate("scene_name", "Scene Name",
                                                   1, [scene_name_default]))

                        # default_expression=("hou.frame()"), default_expression_language=(hou.scriptLanguage.Python) ) )
                        parm_folder.addParmTemplate(
                            hou.StringParmTemplate("frame", "Frame", 1,
                                                   ["$F4"]))
                        parm_folder.addParmTemplate(
                            hou.StringParmTemplate("file_type", "File Type", 1,
                                                   [extension]))

                        parm_folder.addParmTemplate(
                            hou.StringParmTemplate("file_template",
                                                   "File Template", 1,
                                                   [file_template]))
                        #parm_folder.addParmTemplate(hou.FloatParmTemplate("amp", "Amp", 2))

                        parm_group.append(parm_folder)
                        node.setParmTemplateGroup(parm_group)

                        hou_parm = node.parm("versionstr")
                        hou_parm.lock(False)
                        hou_parm.setAutoscope(False)
                        hou_keyframe = hou.StringKeyframe()
                        hou_keyframe.setTime(0)
                        ver_expr = \
                            """
# This allows versioning to be inherited by the multi parm db
import hou
import re

node = hou.pwd()
parm = hou.evaluatingParm()

index_key = node.parm('index_key_template').eval()
multiparm_index = node.userData('verdb_'+index_key)

version = 0

if multiparm_index is not None:
    multiparm_index = str(multiparm_index)
    version_parm = node.parm('version'+multiparm_index)
    if version_parm is not None:
        version = version_parm.eval()        

return version
"""
                        hou_keyframe.setExpression(ver_expr,
                                                   hou.exprLanguage.Python)
                        hou_parm.setKeyframe(hou_keyframe)

                        expr = \
                            """
import hou
node = hou.pwd()
lookup = {'submission_location':'$PROD_ROOT', 'cloud':'$PROD_CLOUD_ROOT', 'onsite':'$PROD_ONSITE_ROOT'}
location = node.parm('location').evalAsString()
root = lookup[location]

template = root+'/$SHOW/$SEQ/$SHOT'
return template
"""

                        hou_parm = node.parm("shot_path_template")
                        hou_parm.lock(False)
                        hou_parm.setAutoscope(False)
                        hou_keyframe = hou.StringKeyframe()
                        hou_keyframe.setTime(0)
                        hou_keyframe.setExpression(expr,
                                                   hou.exprLanguage.Python)
                        hou_parm.setKeyframe(hou_keyframe)

                        parms_added = True
                    except:
                        parms_added = False

                    if static_expression:
                        hou_parm = node.parm("frame")
                        hou_parm.lock(False)
                        hou_parm.setAutoscope(False)
                        hou_keyframe = hou.StringKeyframe()
                        hou_keyframe.setTime(0)

                        if 'overrides' in lookup and 'frame' in lookup[
                                'overrides']:
                            print 'has override for static_expression'
                            hou_keyframe.setExpression(
                                lookup['overrides']['frame'],
                                hou.exprLanguage.Python)
                        else:
                            hou_keyframe.setExpression(
                                "import hou" + '\n' + "node = hou.pwd()" +
                                '\n' + "step = node.parm('f3').eval()" + '\n' +
                                "if node.parm('trange').evalAsString() == 'off':"
                                + '\n' + "    value = 'static'" + '\n' +
                                "elif step != 1:" + '\n' +
                                "    value = '$FF'" + '\n' + "else:" + '\n' +
                                "    value = '$F4'" + '\n' + "return value",
                                hou.exprLanguage.Python)
                        # if node.parm('framegeneration').evalAsString() == '0':
                        hou_parm.setKeyframe(hou_keyframe)

                    # set defaults here if parms already exist and changes are made
                    node.parm("scene_name").set(scene_name_default)
                    node.parm("shot").set(shot_default)

                    element_name_template = node.parm(
                        "element_name_template").evalAsString()
                    try:
                        shot_path_template = hou.expandString(
                            node.parm("shot_path_template").evalAsString())
                        #element_name_template = node.parm("element_name_template").evalAsString()
                    except:
                        shot_path_template = shotpath_var

                    node.parm('element_name').set(element_name_template)
                    node.parm("shot_path").set(shot_path_template)
                    node.parm('file_template').set(file_template)

                    bake_template = False
                    replace_env_vars_for_tops = True
                    auto_version = node.parm("auto_version").eval()
                    print 'auto_version', auto_version

                    # if autoversion tickbox enabled, then update version to hip version on execute of tool.
                    if node.parm("auto_version").eval():
                        set_version = int(
                            hou.hscriptExpression('opdigits($VER)'))
                        print 'set version', set_version
                        node.parm("version_int").set(set_version)

                    if bake_template:
                        file_path_split = node.parm(
                            'file_template').unexpandedString()
                        file_path_split = file_path_split.replace(
                            "`chs('frame')`", "{{ frame }}")
                        file_path_split = file_path_split.replace(
                            "`chs('versionstr')`", "{{ versionstr }}")
                        file_path_split = file_path_split.replace(
                            "`chs('wedge_string')`", "{{ wedge_string }}")
                        file_path_split = file_path_split.replace(
                            "`chs('element_name')`", "{{ element_name }}")

                        # expand any values that we do not wish to be dynamic.
                        file_path = hou.expandString(file_path_split)
                        try:
                            file_path = file_path.replace(
                                "{{ frame }}",
                                node.parm('frame').unexpandedString())
                        except:
                            file_path = file_path.replace(
                                "{{ frame }}",
                                node.parm('frame').eval())
                        file_path = file_path.replace("{{ versionstr }}",
                                                      "`chs('versionstr')`")
                        file_path = file_path.replace("{{ wedge_string }}",
                                                      "`chs('wedge_string')`")
                        file_path = file_path.replace("{{ element_name }}",
                                                      "`chs('element_name')`")

                        # overide, and use template
                    else:
                        file_path_split = node.parm(
                            'file_template').unexpandedString()
                        file_path_split = file_path_split.replace(
                            "`chs('frame')`", "{{ frame }}")
                        file_path_split = file_path_split.replace(
                            "`chs('element_name')`", "{{ element_name }}")
                        file_path = file_path_split
                        try:
                            file_path = file_path.replace(
                                "{{ frame }}",
                                node.parm('frame').unexpandedString())
                        except:
                            file_path = file_path.replace(
                                "{{ frame }}",
                                node.parm('frame').eval())

                        element_name = node.parm(
                            'element_name').unexpandedString()
                        if replace_env_vars_for_tops:
                            print 'replace environment vars in element name with @ lower case version attributes'
                            env_var_matches = re.findall(
                                r'\$\{.*?\}', element_name)
                            print 'element_name', element_name
                            print 'env_var_matches', env_var_matches
                            ignore = ['${OS}']
                            for match in env_var_matches:
                                if match not in ignore:
                                    replacement = match.strip('${}').lower()
                                    element_name = element_name.replace(
                                        match, '`@' + replacement + '`')
                        else:
                            print 'will preserve environment vars in element name'

                        # we bake the element name into the path so that copy of a node will not break refs in the event of a duplicate node existing in the target network to copy to.
                        # element name cannot be ${OS} because if it changes the reader will not function from the template parms schema.
                        file_path = file_path.replace("{{ element_name }}",
                                                      element_name)

                    # We bake the full definition of the cached output string into the output file string, except for the frame variable, version and wedge which remains as hscript/chanel refs.
                    # this provides a safe means for copying cache nodes into other scenes without breaking references.
                    # references should be updated on write via a prerender script executing this function to ensure $VER is updated to a current value.

                    print 'out path', file_path

                    node.parm(out_parm_name).set(file_path)
                    print "add defs"

                    def update_index(node, index_int):
                        index_key_parm_name = 'index_key' + str(index_int)
                        #print "update node", node, 'index_int', index_int, 'index_key_parm_name', index_key_parm_name
                        index_key_parm = node.parm(index_key_parm_name)
                        #print 'update index from parm', index_key_parm
                        index_key = index_key_parm.eval()
                        #version = node.parm('version' + str(index_int) ).eval()
                        node.setUserData('verdb_' + index_key, str(index_int))
                        #print "Changed parm index_key", index_key, "index_int", index_int

                    # ensure parameter callbacks exists
                    def parm_changed(node, event_type, **kwargs):
                        print "parm changed"
                        parm_tuple = kwargs['parm_tuple']

                        if parm_tuple is None:
                            parm_warn = int(
                                hou.node("/obj").cachedUserData(
                                    "parm_warn_disable") != '1')
                            if parm_warn:
                                hou.ui.displayMessage(
                                    "Too many parms were changed.  callback hasn't been designed to handle this yet, changes may be needed in cloud_submit.py to handle this.  see shell output"
                                )
                                print "Too many parms were changed.  callback hasn't been designed to handle this yet, changes may be needed in cloud_submit.py to handle this.  see shell output.  This warning will be displayed once for the current session."
                                hou.node("/obj").setCachedUserData(
                                    'parm_warn_disable', '1')
                            print "node", node
                            print "event_type", event_type
                            print "parm_tuple", parm_tuple
                            print "kwargs", kwargs
                        else:
                            name = parm_tuple.name()

                            # if a key has changed
                            is_multiparm = parm_tuple.isMultiParmInstance()

                            if is_multiparm and 'index_key' in name:

                                if len(parm_tuple.eval()) > 1:
                                    hou.ui.displayMessage(
                                        "multiple items in tuple, changes may be needed in cloud_submit.py to handle this"
                                    )

                                index_int = next(re.finditer(r'\d+$',
                                                             name)).group(0)

                                print 'index_key in name', name, 'update', index_int
                                update_index(node, index_int)

                            # if multiparm instance count has changed, update all and remove any missing.
                            if 'versiondb0' in name:
                                multiparm_count = parm_tuple.eval()[0]
                                print "Total parms changed.  validate and clean out old dict. total parms:", multiparm_count
                                index_keys = []
                                for index_int in range(
                                        1,
                                        int(multiparm_count) + 1):
                                    index_key_parm_name = 'index_key' + \
                                        str(index_int)
                                    index_key_parm = node.parm(
                                        index_key_parm_name)
                                    print 'update', index_key_parm.name()
                                    index_key = index_key_parm.eval()
                                    index_keys.append('verdb_' + index_key)
                                    print 'update index', index_int, 'node', node
                                    update_index(node, index_int)

                                # first all items in dict will be checked for existance on node.  if they dont exist they will be destroyed on the dict.
                                user_data_total = 0

                                keys_to_destroy = []
                                for index_key, value in node.userDataDict(
                                ).items():
                                    if index_key not in index_keys and 'verdb_' in index_key:
                                        print "node missing key", index_key, ":", value, 'will remove'
                                        keys_to_destroy.append(index_key)
                                    else:
                                        user_data_total += 1

                                if len(keys_to_destroy) > 0:
                                    for index_key in keys_to_destroy:
                                        node.destroyUserData(index_key)
                                        print "destroyed key", index_key

                                # all lookups and validation needs to double check the data is correct.  if incorrect, trigger cleanup.
                                # if number of entries dont match, trigger cleanup. this can occur if a wedge is entered in as an index manually, and then altered. we locked parms to avoid this.
                                # new indexes should be automated.

                        # remove callback to replace
                        #removeEventCallback((hou.nodeEventType.ParmTupleChanged, ), parm_changed)

                    print "add callback"
                    node.addEventCallback(
                        (hou.nodeEventType.ParmTupleChanged, ), parm_changed)
Exemplo n.º 15
0
Method is a function that works in relation to specific classes. Class is an object template that allows you to run specified methods that are related to it. In this example, ‘ui’ is a class and ‘displayMessage()’ is a method of that class. 

Whatever is inside parentheses following the method name is called ‘argument‘.

import hou
hou.ui.displayMessage('Hello
Pop up a message window with a text ‘hello’ and buttons ‘ok’ and ‘cancel’. returns 0 and 1 upon clicking on the buttons.
As you can see, methods can have multiple arguments that can change a way the method is executed.

import hou
hou.ui.displayMessage('hello'ok','cancel'])
Pop up an user input window with a text “Type your input”
import hou
hou.ui.readInput('Typer input')
Get a path to a first selected node, save it as a variable and print it.
Variable is any user defined data that can be referenced later by its name. This way you can execute the code once, save the result as a variable and then call it by name without having to execute it again. It also helps to keep your code clean and easy to work with.

import hou
my_variable = hou.selectedNodes()[0].path()
print my_variable
Select a node
Selects object sphere1 on /obj

import hou

node = hou.node('obj/sphere1
node.setCurrent(1, True)
For loops
This example shows a simple for loop. It loops over selected nodes and for each of them it prints out its path in the console. for and in are Python reserved words, ‘selected’ represents a list of objects to loop over, ‘item’ stands for any single item in that list (it can be called whatever you want). After this initial statement follows a colon ‘:’ Next line (or lines) has to be indented and states a code to be executed at each cycle of the loop (in this case prints a path to the currently processed node).

import hou
selected = hou.selectedNodes()
for item in selected:
  print item.path()
Another example of for loop:

Take selected nodes and assign a new name to each of them with trailing digit based on order in which they have been processed. This time list of our objects is called ‘nodes’ and each item is refered to as ‘n’

Resulting names will be newName1, newName2, newName3, etc.

import hou
count = 0
nodes = hou.selectedNodes()
for n in nodes:
 count += 1
 n.setName('newName' + str(count))
This example creates a sphere
This example introduces concept of function. Function is isolated block of code that has some functionality on its own and can be later called by its name, similar to variables. It allows to create modular code that can be reused, stacked and executed in desired order, and can also be easily modified. Function starts like this:

def createSphereGeo(): – def states this is a function. ‘createSphereGeo’ is its name. Name is up to the user, it can be anything. After name there always follows closed parentheses which can contain arguments (for example you may need some user input or something). Similar to loops, there has to be a colon after parentheses.

Follows an indented block of code with some functionality on its own. In this example function is to create a sphere object.

Function can be executed by typing name of a function: createSphereGeo() – without colon.

Important methods in this example:

hou.node(‘obj’).createNode(‘geo’) – this is a function that basically sets a scene location (path) at which you wish to operate (‘obj’). createNode() is a method that places a new node (which type has been set to ‘geo’) at the location specified by hou.node().

Another node will be created as a child of the geo node and it will be actual sphere this time aGeoNode.createNode(‘sphere’)

aSphereNode.setDisplayFlag() – sets a display flag on aSphereNode object. Argument is either 0 or 1.

import hou
def createSphereGeo():
  aGeoNode = hou.node('obj').createNode('geo
  aSphereNode = aGeoNode.createNode('sphere')
  aSphereNode.setDisplayFlag(1)
createSphereGeo()
List primitive groups on the current node
primGroups = hou.selectedNodes()[0].geometry().primGroups()
for prim in primGroups:
  print prim.name()
Set render flag on selected node
node = hou.selectedNodes()[0]
node.setRenderFlag(True)
Set node position in network view
import hou

newNode = hou.node('obj').createNode('geo
newNode.setPosition([1, 0])
Working with nodes. Nodes creation, naming, connections.
Interesting functions:

setPosition() – allows to set a nodes’ position in the network view

newShopNode.setPosition([4,0])

setInput() – this is for making new connections between nodes. it takes 3 arguments: 1. input connector number, 2. node to make connection to (destination), 3. destination nodes’ connector number.

addLayerUnpack.setInput(0,addPrincipled,2)

parm().set() – useful combo for setting values into existing parameters. “parm” and “set” both take one argument: parameter name and parameter value to set

newMatNode.parm(‘shop_materialpath1’).set(“../shopnet1/vopmaterial1”)

setName() – obviously, allows you to rename a node. argument is a new name (string)

newOutNode.setName(“OUT”)

note that name can be also added directly upon nodes’ creation by adding another argument:

newGeoNode.createNode(‘null’, “OUT”)

setColor() – assigning a color to a node is a bit trickier as it requires hou.Color object, containing tuple of values. so the syntax looks like this:

newOutNode.setColor(hou.Color((0,0.5,0)))

import hou

def createNewGeo():
 newGeoNode = hou.node('obj').createNode('geo
 
 newShopNode = newGeoNode.createNode('shopnet')
 newShopNode.setPosition([4,0])
 
 newMatBuilder = newShopNode.createNode('vopmaterial')
 
 addPrincipled = newMatBuilder.createNode('principledshader')
 addPrincipled.setPosition([0,7])
 
 addLayerUnpack = newMatBuilder.createNode('layerunpack')
 addLayerUnpack.setPosition([3,7])
 addLayerUnpack.setInput(0,addPrincipled,2)
 
 newMatNode = newGeoNode.createNode('material')
 newMatNode.setPosition([0,-1])
 newMatNode.parm('shop_materialpath1').set("../shopnet1/vopmaterial1
 
 newOutNode = newGeoNode.createNode('null')
 newOutNode.setPosition([0,-2])
 newOutNode.setColor(hou.Color((0,0.5,0)))
 newOutNode.setInput(0,newMatNode)
 newOutNode.setName("OUT")
 
createNewGeo()
When creating new nodes, moveToGoodPosition() comes in handy
node.moveToGoodPosition() – it will simply create node at a convenient location, avoiding any overlaps.

import hou

aNode = hou.node('obj').createNode('geo
aNode.moveToGoodPosition()
Button callback in HDA
kwargs[‘node’] – stands for “currently processed node”

hdaModule().onLoadPress() – says to execute function called onLoadPress() inside of hdaModule in digital assets’ scripts tab.

kwargs['node'].hdaModule().onLoadPress()
Add new UI items to a selected node interface
adding new parameters by Python is a bit tricky and there are few things you need to know:

hou.parmTemplateGroup() – this function is essential to call first. It represents nodes’ ui layout you can put your parameters into.

hou.addParmTemplate() – by this function you add a new parameter to the group. The argument in brackets defines what kind of parameter it will be. In this case we have FloatParmTemplate(), which is obviously a float parameter. Arguments  are name (‘myparm’), label (‘My Parm’) and number of components (1). Similarly, you can have StringParmTemplate(), IntParmTemplate(), ButtonParmTemplate(), FolderParmTemplate(), etc., with respective arguments.

see the docs for more info and syntax on Parameter templates: http://www.sidefx.com/docs/houdini/hom/hou/ParmTemplate

setParmTemplateGroup() – this line actually creates a user interface defined by templateGroup we’ve defined.

import hou
node = hou.selectedNodes()[0]
group = node.parmTemplateGroup()
group.addParmTemplate(hou.FloatParmTemplate('myparm', 'My Parm', 1))
node.setParmTemplateGroup(group)
as you can see, this way parameter is created as a last element at the bottom of a Parameter pane. Chances are you want to organize your stuff into a folder. It may seem simple to just add a line for creating a folder:

import hou
node = hou.selectedNodes()[0]
group = node.parmTemplateGroup()
group.addParmTemplate(hou.FolderParmTemplate('myfolder', 'My Folder'))
group.addParmTemplate(hou.FloatParmTemplate('myparm', 'My Parm', 1))
node.setParmTemplateGroup(group)
Unfortunately, even though the folder is created, there is no indication that our parameter is supposed to be a content of that folder and it is still placed outside of it.

What you need to do is to create sort of a hierarchy and specify that ‘myparm’ template is a child of ‘folder’ template:

import hou
node = hou.selectedNodes()[0]
group = node.parmTemplateGroup()
folder = hou.FolderParmTemplate('folder', 'My Parms') 
folder.addParmTemplate(hou.FloatParmTemplate('myparm', 'My Parm', 1))
group.append(folder)
node.setParmTemplateGroup(group)
so as you can see, folder = hou.FolderParmTemplate(‘folder’, ‘My Parms’) now defines its own template that is a Folder type.

folder.addParmTemplate(hou.FloatParmTemplate(‘myparm’, ‘My Parm’, 1)) – this line now says not to place the parameter directly into the main group but rather as a child of the ‘folder’.

group.append(folder) – this statement specifies the layout of our ui. it says to append our folder at the end of the nodes’ layout.

So that covers basics of ui elements. Say now I need to add something more complicated like a menu. This is how you go about that:

import hou
newGeo = hou.node('obj').createNode('geo
newUi = newGeo.parmTemplateGroup()
newUi.addParmTemplate(hou.MenuParmTemplate('geoType', 'Geo type', ('01','02','03','04'), ('Disk file','Grid','Sphere','Box'), 1))
newGeo.setParmTemplateGroup(newUi)
As you can see, it’s actually not very different from what we’ve done before. Syntax of MenuParmTemplate() calls for brief explanation though. MenuParmTemplate() takes multiple arguments:

‘name’, ‘label’, (menu_items), (menu_labels), default_value

Name and label are pretty self explanatory. Another two arguments enclosed in parentheses are tuples (it’s like groups of arguments) and they put together a list of menu items, their internal names and labels. Last integer argument default value – says which menu item will be selected by default (starting from 0 and going up).

Set viewport camera
It’s a nasty long and tricky line of code, but if you need your Python script to switch a viewport to desired camera for you, here’s what you can do about it:

hou.ui.paneTabOfType(hou.paneTabType.SceneViewer).curViewport().setCamera(hou.node('/obj/cam1
Now how that works:

ui.paneTabOfType() is a function of hou.ui module. Takes an argument that says what type of pane are you looking for. You might think that giving it something like SceneViewer will be enough, but no. You have to call a special module for that so argument looks like this: hou.paneTabType.SceneViewer. If you happen to have more viewports of the same type, there is a good news that viewports are indexed (0,1,2…) and you can add an optional second integer argument that helps to identify a desired instance.

curViewport() is a method of sceneViewer class and it just returns this viewer’s current viewport. The current viewport is the one containing the mouse cursor. If the cursor is not in a viewport, then the selected, or active, viewport is returned.

And finally, setCamera() lets you actually set the camera after all the hard work of picking up the viewport. setCamera() is a method of geometryViewport class and again, it takes one argument and it has to be a node instance. That means it’s not enough to specify a path to the node but it has to be encapsulated in hou.node class: hou.node(‘/obj/cam1’) 

How to load a node preset with Python
Only option right now seems to be using hscript within Python:

hou.hscript('oppresetload /out/mantra1 mantra_lookdev')
hou.script() is obviously a function that allows you to execute any hscript you put inside parenthesses.

oppresetload is a hscript command allowing to load an existing preset. out/mantra1 is then node you wish to modify and mantra_lookdev is a preset name you want to load.

Filtering nodes by name
import hou

sel = hou.selectedNodes()[0]
children = sel.children()
lookfor = "OUT"
for child in children:
 name = child.name()
 fndstr = name.find(lookfor)
 if fndstr != -1:
  print "found:" + name
Using variables outside functions
Basic syntax looks like this:

def myfunction():
 var = "this is my variable"
 second = 11
 return var, second

one, two = myfunction()
print one, two
As you can see, there is a function that defines two variables, named “var” and “second”. Then I can assign this function to couple of different (or same) variables and original variables are picked up by their order in return statement. This is great when you need to run function inside functions. Example:

 

import hou

def evalRops():
 current = hou.pwd()
 arnold = hou.node('/out/lookdev/arnold1
 mantra = hou.node('/out/lookdev/mantra1
 getValue = current.parm('rendererMenu').eval
 return arnold, mantra, getValue 

def setRop(): 
 arnold, mantra, getValue = evalRops() 
 if getValue == 0: 
  hou.ui.paneTabOfType(hou.paneTabType.IPRViewer).setRopNode(arnold)
 if getValue == 1:
  hou.ui.paneTabOfType(hou.paneTabType.IPRViewer).setRopNode(mantra)

def openRopDialog():
 arnold, mantra, getValue = evalRops() 

 if getValue == 0:
  node = arnold
 if getValue == 1:
  node = mantra
 
 desktop = hou.ui.curDesktop()
 pane = desktop.createFloatingPane(hou.paneTabType.Parm)
 pane.setCurrentNode(node)
 pane.setPin(True)
I have defined code for evaluating our variables in evalRops() function and then I’m calling that function inside two different functions. The return statement inside the evalRops() is what makes listed variables available even outside of the current function.

Without being able to do this I would have to embed the whole code of evalRops() function inside each of those functions. That would make my script not only longer but also harder to read and work with, more prone to errors.

Pop up floating windows
Quite commonly you may want to pop up a floating window with some content on button click. This is how you go about it, give you’ve got Mantra1 ROP in /out network:

import hou
node = hou.node('/out/mantra1')
desktop = hou.ui.curDesktop()
pane = desktop.createFloatingPane(hou.paneTabType.Parm)
pane.setCurrentNode(node)
pane.setPin(True)
This is similar to previous example but you need to work with curDesktop() method.

Accessing geometry attributes
Basic way of reading geometry attributes. Note that in hou.node() you have to point at SOP node, not an object itself. Code returns a string attribute called ‘str’, and it is a tuple of values (one for each primitive). Similarly you can access all kinds of primitive and point attributes with corresponding methods (pointFloatAttribValues(), primIntAttributeValues(), etc… you get the idea 🙂 For detail attributes you call similar methods but without type specification: FloatAttribValues()

import hou
geo = hou.node('obj/box_object1/material1').geometry()
attrib = geo.primStringAttribValues('str')
print attrib

Print kwargs
print hou.node("/obj/myHDA").hdaModule().kwargs


import hou
hou.ui.readInput('Typer input')
Exemplo n.º 16
0
        max=10,
        min_is_strict=False,
        max_is_strict=False,
        look=hou.parmLook.Regular,
        naming_scheme=hou.parmNamingScheme.Base1)
    selNode.addSpareParmTuple(hou_parm_template,
                              in_folder=(['Cache']),
                              create_missing_folders=True)

    hou_parm_template = hou.MenuParmTemplate(
        "trange",
        "Valid Frame Range",
        menu_items=(["off", "normal", "on"]),
        menu_labels=([
            "Render Current Frame", "Render Frame Range",
            "Render Frame Range Only (Strict)"
        ]),
        default_value=0,
        icon_names=([]),
        item_generator_script="",
        item_generator_script_language=hou.scriptLanguage.Python,
        menu_type=hou.menuType.Normal)
    hou_parm_template.setTags({"autoscope": "0000000000000000"})
    selNode.addSpareParmTuple(hou_parm_template,
                              in_folder=(['Cache']),
                              create_missing_folders=True)

    hou_parm_template = hou.FloatParmTemplate(
        "f",
        "Start/End/Inc",
        3,
def charAssetsToHDA():
    this = hou.node('.')
    importNode = hou.hipFile.importFBX(this.parm('char_fbx_file').eval(), suppress_save_prompt=True, merge_into_scene=True, import_cameras=False, import_joints_and_skin=True, import_geometry=True, import_lights=False, import_animation=False, import_materials=False, resample_animation=False, resample_interval=1.0, override_framerate=False,framerate=-1, hide_joints_attached_to_skin=True, convert_joints_to_zyx_rotation_order=False, material_mode=hou.fbxMaterialMode.FBXShaderNodes, compatibility_mode=hou.fbxCompatibilityMode.Maya, single_precision_vertex_caches=False, triangulate_nurbs=False, triangulate_patches=False, import_global_ambient_light=False, import_blend_deformers_as_blend_sops=False, segment_scale_already_baked_in=True, convert_file_paths_to_relative=False, unlock_geometry=True, unlock_deformations=True, import_nulls_as_subnets=False, import_into_object_subnet=True, convert_into_y_up_coordinate_system=False)
    fbxNode = importNode[0]   
    
    if fbxNode:
        # set up the parameters
        
        # CHOP mocap params
        hou_parm_template = hou.StringParmTemplate("fbxfile", "FBX File", 1, default_value=([""]), naming_scheme=hou.parmNamingScheme.Base1, string_type=hou.stringParmType.FileReference, menu_items=([]), menu_labels=([]), icon_names=([]), item_generator_script="", item_generator_script_language=hou.scriptLanguage.Python, menu_type=hou.menuType.StringReplace)
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Character']), create_missing_folders=True)
        
        hou_parm_template = hou.StringParmTemplate("fbxclip", "Clip", 1, default_value=([""]), naming_scheme=hou.parmNamingScheme.Base1, string_type=hou.stringParmType.Regular, menu_items=([]), menu_labels=([]), icon_names=([]), item_generator_script="opmenu -l CHOP/fbxagent/fbximport currentclip", item_generator_script_language=hou.scriptLanguage.Hscript, menu_type=hou.menuType.Normal)
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Character']), create_missing_folders=True)
        
        hou_parm_template = hou.ToggleParmTemplate("mocapswitch", "Use Mocap?", default_value=False)
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Character']), create_missing_folders=True)
        
        # Alembic params
        hou_parm_template = hou.LabelParmTemplate("labelparm", "Alembic", column_labels=([""]))
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.ToggleParmTemplate("use_cache", "Use Cache", default_value=False)
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.FloatParmTemplate("cache_scale", "Cache Scale", 1, default_value=([1]), min=0, max=10, min_is_strict=False, max_is_strict=False, look=hou.parmLook.Regular, naming_scheme=hou.parmNamingScheme.Base1)
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.MenuParmTemplate("trange", "Valid Frame Range", menu_items=(["off","normal","on"]), menu_labels=(["Render Current Frame","Render Frame Range","Render Frame Range Only (Strict)"]), default_value=0, icon_names=([]), item_generator_script="", item_generator_script_language=hou.scriptLanguage.Python, menu_type=hou.menuType.Normal)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.FloatParmTemplate("f", "Start/End/Inc", 3, default_value=([0, 0, 1]), default_expression=(["$FSTART","$FEND",""]), default_expression_language=([hou.scriptLanguage.Hscript,hou.scriptLanguage.Hscript,hou.scriptLanguage.Hscript]), min=0, max=10, min_is_strict=False, max_is_strict=False, look=hou.parmLook.Regular, naming_scheme=hou.parmNamingScheme.Base1)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.StringParmTemplate("cachefile", "Cache File", 1, default_value=(["$HIP/output.abc"]), naming_scheme=hou.parmNamingScheme.Base1, string_type=hou.stringParmType.FileReference, menu_items=([]), menu_labels=([]), icon_names=([]), item_generator_script="opmenu -l exportnet/alembic filename", item_generator_script_language=hou.scriptLanguage.Hscript, menu_type=hou.menuType.StringReplace)
        hou_parm_template.setTags({"autoscope": "0000000000000000", "filechooser_pattern": "*.abc"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.ButtonParmTemplate("cache_btn", "Cache to Disk")
        hou_parm_template.setTags({"autoscope": "0000000000000000", "takecontrol": "always"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        #FBX params
        hou_parm_template = hou.SeparatorParmTemplate("sepparm")
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.LabelParmTemplate("labelparm2", "FBX", column_labels=([""]))
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.MenuParmTemplate("trange2", "Valid Frame Range", menu_items=(["off","normal","on"]), menu_labels=(["Render Current Frame","Render Frame Range","Render Frame Range Only (Strict)"]), default_value=0, icon_names=([]), item_generator_script="", item_generator_script_language=hou.scriptLanguage.Python, menu_type=hou.menuType.Normal)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.FloatParmTemplate("f4", "Start/End/Inc", 3, default_value=([0, 0, 1]), default_expression=(["$FSTART","$FEND",""]), default_expression_language=([hou.scriptLanguage.Hscript,hou.scriptLanguage.Hscript,hou.scriptLanguage.Hscript]), min=0, max=10, min_is_strict=False, max_is_strict=False, look=hou.parmLook.Regular, naming_scheme=hou.parmNamingScheme.Base1)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.StringParmTemplate("take", "Render With Take", 1, default_value=(["_current_"]), naming_scheme=hou.parmNamingScheme.Base1, string_type=hou.stringParmType.Regular, menu_items=([]), menu_labels=([]), icon_names=([]), item_generator_script="opmenu -l exportnet/filmboxfbx1 take", item_generator_script_language=hou.scriptLanguage.Hscript, menu_type=hou.menuType.Normal)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.StringParmTemplate("sopoutput", "Output File", 1, default_value=(["$HIP/out.fbx"]), naming_scheme=hou.parmNamingScheme.Base1, string_type=hou.stringParmType.FileReference, menu_items=([]), menu_labels=([]), icon_names=([]), item_generator_script="opmenu -l exportnet/filmboxfbx1 sopoutput", item_generator_script_language=hou.scriptLanguage.Hscript, menu_type=hou.menuType.StringReplace)
        hou_parm_template.setTags({"autoscope": "0000000000000000", "filechooser_mode": "write"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.ToggleParmTemplate("mkpath", "Create Intermediate Directories", default_value=True, default_expression='on', default_expression_language=hou.scriptLanguage.Hscript)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.ToggleParmTemplate("exportkind", "Export in ASCII Format", default_value=True, default_expression='on', default_expression_language=hou.scriptLanguage.Hscript)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.StringParmTemplate("sdkversion", "FBX SDK Version", 1, default_value=([""]), naming_scheme=hou.parmNamingScheme.Base1, string_type=hou.stringParmType.Regular, menu_items=([]), menu_labels=([]), icon_names=([]), item_generator_script="opmenu -l exportnet/filmboxfbx1 sdkversion", item_generator_script_language=hou.scriptLanguage.Hscript, menu_type=hou.menuType.Normal)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.MenuParmTemplate("vcformat", "Vertex Cache Format", menu_items=(["mayaformat","maxformat"]), menu_labels=(["Maya Compatible (MC)","3DS MAX Compatible (PC2)"]), default_value=0, icon_names=([]), item_generator_script="", item_generator_script_language=hou.scriptLanguage.Python, menu_type=hou.menuType.Normal)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.MenuParmTemplate("invisobj", "Export Invisible Objects", menu_items=(["nullnodes","fullnodes"]), menu_labels=(["As Hidden Null Nodes","As Hidden Full Nodes"]), default_value=0, icon_names=([]), item_generator_script="", item_generator_script_language=hou.scriptLanguage.Python, menu_type=hou.menuType.Normal)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.FloatParmTemplate("polylod", "Conversion Level of Detail", 1, default_value=([1]), min=0, max=5, min_is_strict=True, max_is_strict=False, look=hou.parmLook.Regular, naming_scheme=hou.parmNamingScheme.Base1)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.ToggleParmTemplate("detectconstpointobjs", "Detect Constant Point Count Dynamic Objects", default_value=True, default_expression='on', default_expression_language=hou.scriptLanguage.Hscript)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.ToggleParmTemplate("convertsurfaces", "Convert NURBS and Bezier Surfaces to Polygons", default_value=False, default_expression='off', default_expression_language=hou.scriptLanguage.Hscript)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.ToggleParmTemplate("conservemem", "Conserve Memory at the Expense of Export Time", default_value=False, default_expression='off', default_expression_language=hou.scriptLanguage.Hscript)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.ToggleParmTemplate("deformsasvcs", "Export Deforms as Vertex Caches", default_value=False, default_expression='off', default_expression_language=hou.scriptLanguage.Hscript)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.ToggleParmTemplate("forceblendshape", "Force Blend Shape Export", default_value=False, default_expression='off', default_expression_language=hou.scriptLanguage.Hscript)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.ToggleParmTemplate("forceskindeform", "Force Skin Deform Export", default_value=False, default_expression='off', default_expression_language=hou.scriptLanguage.Hscript)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.ToggleParmTemplate("exportendeffectors", "Export End Effectors", default_value=True, default_expression='on', default_expression_language=hou.scriptLanguage.Hscript)
        hou_parm_template.setTags({"autoscope": "0000000000000000"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        hou_parm_template = hou.ButtonParmTemplate("execute", "Save to Disk")
        hou_parm_template.setTags({"autoscope": "0000000000000000", "takecontrol": "always"})
        fbxNode.addSpareParmTuple(hou_parm_template, in_folder=(['Cache']), create_missing_folders=True)
        
        children = fbxNode.children()
        fbxNodeName = fbxNode.name().rsplit('_', 1)
        
        charGeo = fbxNode.createNode('geo', fbxNodeName[0] + '_geo')
        if len(charGeo.children()) > 0:
            charGeo.children()[0].destroy() # older version of houdini had a lone file node

        ccache = charGeo.createNode('alembic', 'char_abc_cache')
        ccache.parm('fileName').set('`chs("../../cachefile")`')
        cscale = charGeo.createNode('xform', 'cache_scale')
        cscale.setFirstInput(ccache)
        cscale.parm('scale').setExpression('ch("../../cache_scale")')
        cswitch = charGeo.createNode('switch', 'cache_switch')
        cswitch.parm('input').setExpression('ch("../../use_cache")')
        
        exportNet = fbxNode.createNode('ropnet', 'exportnet')
        alembicRop = exportNet.createNode('alembic', 'alembic')
        alembicRop.parm('execute').setExpression('ch("../../cache_btn")')
        alembicRop.parm('trange').setExpression('ch("../../trange")')
        alembicRop.parm('f1').setExpression('ch("../../f1")')
        alembicRop.parm('f2').setExpression('ch("../../f2")')
        alembicRop.parm('f3').setExpression('ch("../../f3")')
        alembicRop.parm('use_sop_path').set(1)
        alembicRop.parm('sop_path').set('../../' + charGeo.name())
        alembicRop.parm('build_from_path').set(1)
        alembicRop.parm('path_attrib').set('path')
        alembicRop.parm('root').set('')

        fbxRop = exportNet.createNode('filmboxfbx', 'fbx')
        fbxRop.parm('startnode').set('`opfullpath("../../")`')
        fbxRop.parm('createsubnetroot').set(0)
        
        fbxRop.parm('trange').setExpression('ch("../../trange2")')
        fbxRop.parm('f1').setExpression('ch("../../f41")')
        fbxRop.parm('f2').setExpression('ch("../../f42")')
        fbxRop.parm('f3').setExpression('ch("../../f43")')
        fbxRop.parm('take').setExpression('ch("../../take")')
        fbxRop.parm('sopoutput').setExpression('ch("../../sopoutput")')
        fbxRop.parm('mkpath').setExpression('ch("../../mkpath")')
        fbxRop.parm('exportkind').setExpression('ch("../../exportkind")')
        fbxRop.parm('sdkversion').setExpression('ch("../../sdkversion")')
        fbxRop.parm('vcformat').setExpression('ch("../../vcformat")')
        fbxRop.parm('invisobj').setExpression('ch("../../invisobj")')
        fbxRop.parm('polylod').setExpression('ch("../../polylod")')
        fbxRop.parm('detectconstpointobjs').setExpression('ch("../../detectconstpointobjs")')
        fbxRop.parm('convertsurfaces').setExpression('ch("../../convertsurfaces")')
        fbxRop.parm('conservemem').setExpression('ch("../../conservemem")')
        fbxRop.parm('deformsasvcs').setExpression('ch("../../deformsasvcs")')
        fbxRop.parm('forceblendshape').setExpression('ch("../../forceblendshape")')
        fbxRop.parm('forceskindeform').setExpression('ch("../../forceskindeform")')
        fbxRop.parm('exportendeffectors').setExpression('ch("../../exportendeffectors")')
        fbxRop.parm('execute').setExpression('ch("../../execute")')
        
        rigBox = fbxNode.createNetworkBox()
        rigBox.setComment('Rig')
                        
        for child in children:
            # for the fbxchop we need to rename it and set up a bclip/agent network to
            # drive animation on the joints
            if child.type().name() == 'chopnet':
                child.destroy()
            
            if child.type().name() == 'null':
                 # we want to set CHOP expressions for nulls so they move the bones with our mocap CHOPs
                 if child.name() is not fbxNodeName[0]: # check to make sure this is not the root null
                    child.parmTuple('t').deleteAllKeyframes()
                    child.parmTuple('r').deleteAllKeyframes()
                    child.parm('rx').setExpression('chop("../CHOP/OUT/$OS:$CH")')
                    child.parm('ry').setExpression('chop("../CHOP/OUT/$OS:$CH")')
                    child.parm('rz').setExpression('chop("../CHOP/OUT/$OS:$CH")')
                    child.parm('tx').setExpression('chop("../CHOP/OUT/$OS:$CH")')
                    child.parm('ty').setExpression('chop("../CHOP/OUT/$OS:$CH")')
                    child.parm('tz').setExpression('chop("../CHOP/OUT/$OS:$CH")')
                    rigBox.addNode(child)
            
            if child.type().name() == 'bone':
                # add the bones to the rig net box
                rigBox.addNode(child)
                    
            if child.type().name() == 'geo':
                if child.name() is not charGeo.name():
                    # we want to convert these to a single geo pointing to a alembic
                    hou.copyNodesTo(child.children(), charGeo)
                    child.destroy()
        
        rigBox.fitAroundContents()
        
        # build the CHOP network
        child = fbxNode.createNode('chopnet', 'CHOP')
        
        #let's fetch the original tpose and place in in a bclip
        fetch = child.createNode('fetch')
        fetch.parm('rate').set(24)
        fetch.parm('nodepath').set('../../* ')
        
        bclip = fetch.clipData(True)
        fileName = this.parm('char_bclip_file').eval()
        
        f = open(hou.expandString(fileName), 'wb')
        f.write(bclip)
        
        f.close()
        
        fetch.destroy()
        
        tposeChop = child.createNode('file', 'tpose_clip')
        tposeChop.parm('file').set(fileName)
        agentChop = child.createNode('agent', 'mocap')
        agentChop.parm('clipname').set('`chs("../../fbxclip")`')
        switch = child.createNode('switch', 'switch')
        switch.parm('index').setExpression('ch("../../mocapswitch")')
        
        outChop = child.createNode('null', 'OUT')
        sopNode = child.createNode('sopnet', 'fbxagent')
        
        switch.setFirstInput(tposeChop)
        switch.setNextInput(agentChop)
        outChop.setFirstInput(switch)
        
        fbxImport = sopNode.createNode('agent', 'fbximport')
        fbxImport.parm('fbxfile').set('`chs("../../../fbxfile")`')
        
        fbxImport.parm('input').set(2)
        
        agentChop.parm('soppath').set('../fbxagent/fbximport')
        
        outChop.setDisplayFlag(True)
        #outChop.setRenderFlag(True)
        
        child.layoutChildren()
        
        # work on the character geo point all the captures to an alembic file
        overMerge = charGeo.createNode('merge', 'merge')
        
        alembic = charGeo.createNode('alembic', 'char_abc_geo')
        fileName = this.parm('char_abc_file').eval()
        alembic.parm('fileName').set(fileName)
        
        unpack = charGeo.createNode('unpack', 'unpack')
        unpack.setFirstInput(alembic)
        unpack.parm('transfer_attributes').set('path shop_materialpath')
        
        children = charGeo.children()
        for child in children:
            if child.type().name() == 'file':
                nodeName = child.name()   
                deleteNode = charGeo.createNode('delete', 'isolate_' + nodeName)
                deleteNode.parm('negate').set(1)
                deleteNode.parm('group').set('@path="/' + nodeName + '/*"')
                deleteNode.setFirstInput(unpack)
                if len(child.outputs()) > 0:
                    delOutput = child.outputs()[0]
                    delOutput.setFirstInput(deleteNode)
                
                child.destroy()
            elif child.type().name() == 'deform':
                child.destroy()
            elif child.type().name() == 'channel':
                child.destroy()
            elif child.type().name() == 'capture':
                child.setGenericFlag(hou.nodeFlag.Lock, False) 
            elif child.type().name() == 'captureoverride':
                overMerge.setNextInput(child)
        
        deform = charGeo.createNode('deform', 'deform')
        deform.setFirstInput(overMerge)
        cswitch.setFirstInput(deform)
        cswitch.setNextInput(cscale)
        
        cswitch.setDisplayFlag(True)
        cswitch.setRenderFlag(True)
        
        charGeo.layoutChildren()

        hdaNode = fbxNode.createDigitalAsset(this.parm('asset_name').eval(), this.parm('hda_location').eval(), this.parm('desc').eval())
        hdaDef = hdaNode.type().definition()
        hdaOptions = hdaDef.options()
        hdaDef.save(hdaDef.libraryFilePath(), hdaNode, hdaOptions)
Exemplo n.º 18
0
def _addProperties(node):
    """ Create all required parameters.

    :hou.HDADefinition node: the node receiving the new parameters.
    """

    parmTemplateGroup = node.parmTemplateGroup()

    if parmTemplateGroup.findFolder('Walter'):
        return

    addArnoldProperties(node, force=True)

    # To Get the lattest parmTemplateGroup with the Arnold group.
    parmTemplateGroup = node.parmTemplateGroup()

    parmName = 'ar_filename'
    dsoParm = hou.StringParmTemplate(parmName,
                                     'Procedural DSO',
                                     1,
                                     default_value=('walterProcedural',),
                                     is_hidden=True)

    ar_procedural_type = hou.StringParmTemplate(
        'ar_procedural_type',
        'Procedural Type',
        1,
        default_value=('walter',),
        is_hidden=True)

    ar_translate_as = hou.StringParmTemplate(
        'ar_translate_as',
        'Translate As',
        1,
        default_value=('arnold_procedural',),
        is_hidden=True)

    ar_bounding_box_padding = hou.FloatParmTemplate(
        'ar_bounding_box_padding',
        'Bounds Padding', 1, is_hidden=True)

    ar_data = hou.StringParmTemplate(
        'ar_data', 'Data String', 1, is_hidden=True)

    user_parms_separator = hou.SeparatorParmTemplate('user_parms_separator')

    parmName = 'ar_filePaths'
    filePaths = hou.StringParmTemplate(
        parmName, 'Layers', 1, default_value=('',), is_hidden=True)

    display_mode = hou.MenuParmTemplate(
        'display_mode', 'Display Mode', ('0', '1'),
        menu_labels=('None', 'Hydra'), default_value=0)

    layerPath = hou.StringParmTemplate(
        'layerPath#', 'Path', 1, default_value=('',),
        string_type=hou.stringParmType.FileReference,
        file_type=hou.fileType.Geometry,
        tags={'filechooser_pattern': '*.abc *.usd *.usda',
              'script_callback' : "kwargs['node'].hdaModule().update(kwargs['node'])",
              'script_callback_language': 'python'})

    parmName = 'ar_layers'
    layers = hou.FolderParmTemplate(
        parmName, 'Layers', parm_templates=([layerPath]),
        folder_type=hou.folderType.MultiparmBlock,
        tags={'script_callback': "kwargs['node'].hdaModule().update(kwargs['node'])",
              'script_callback_language': 'python'})

    parmName = 'ar_objectPath'
    objectPath = hou.StringParmTemplate(
        parmName, "Prim Path", 1, default_value=('/',),
        join_with_next=True)

    pick_path = hou.ButtonParmTemplate(
        "pick_path", '', is_label_hidden=True,
        tags={'button_icon': 'BUTTONS_tree',
              'script_callback':
                    "kwargs['node'].node('display/walter').parm('pickObjectPath').pressButton()",
              'script_callback_language': 'python'})

    parmName = 'ar_sessionLayer'
    sessionLayer = hou.StringParmTemplate(
        parmName, "Session Layer", 1, default_value=('',), is_hidden=True)

    parmName = 'ar_mayaStateLayer'
    mayaStateLayer = hou.StringParmTemplate(
        parmName, 'Maya State Layer', 1, default_value=('',), is_hidden=True)

    parms = [dsoParm,
             ar_procedural_type,
             ar_translate_as,
             ar_bounding_box_padding,
             ar_data,
             user_parms_separator,
             filePaths,
             display_mode,
             layers,
             objectPath,
             pick_path,
             sessionLayer,
             mayaStateLayer]

    parms = [p for p in parms if p is not None]

    walterFolder = hou.FolderParmTemplate(
        'walter', 'Walter', parm_templates=(parms),
        folder_type=hou.folderType.Tabs, is_hidden=False,
        ends_tab_group=False, tags={})

    xfo_idx = parmTemplateGroup.findIndicesForFolder('Transform')
    parmTemplateGroup.insertBefore(xfo_idx, walterFolder)

    node.setParmTemplateGroup(parmTemplateGroup)
Exemplo n.º 19
0
def my_null(parent, name):
    null = parent.createNode("geo", name)

    #creating the nodes inside for display
    null.node("file1").destroy()
    control = null.createNode("control")
    control.parm("scale").set(.1)
    trans = null.createNode("xform", "xform")
    #trans.parm("sy").set(.2)
    trans.setNextInput(control)
    trans.setDisplayFlag(1)
    trans.setRenderFlag(1)

    null_out = null.createNode("null", "Out")
    null_out.setNextInput(trans)
    null_out.setDisplayFlag(1)
    null_out.setRenderFlag(1)

    p1 = null.createNode("add", "point1")
    p1.parm("usept0").set(1)

    #creating the attributes at upper level
    tg = null.parmTemplateGroup()

    cd = hou.FloatParmTemplate("color",
                               "Color",
                               3,
                               default_value=([1, 1, 1]),
                               min=0,
                               max=10,
                               min_is_strict=False,
                               max_is_strict=False,
                               look=hou.parmLook.ColorSquare,
                               naming_scheme=hou.parmNamingScheme.RGBA)
    tg.appendToFolder("Misc", cd)
    sc = hou.FloatParmTemplate("geoscale",
                               "Scale",
                               1,
                               default_value=([1]),
                               min=0,
                               max=10,
                               min_is_strict=False,
                               max_is_strict=False,
                               look=hou.parmLook.Regular,
                               naming_scheme=hou.parmNamingScheme.Base1)
    tg.appendToFolder("Misc", sc)
    display_icon = hou.MenuParmTemplate(
        "displayicon",
        "Display",
        menu_items=(["icon", "axis", "iconandaxis"]),
        menu_labels=(["Icon", "Axis", "Icon and Axis"]),
        default_value=0,
        icon_names=([]),
        item_generator_script="",
        item_generator_script_language=hou.scriptLanguage.Python,
        menu_type=hou.menuType.Normal)
    tg.appendToFolder("Misc", display_icon)
    ct = hou.MenuParmTemplate(
        "controltype",
        "Control Type",
        menu_items=([
            "null", "circles", "box", "planes", "nullandcircles", "nullandbox",
            "nullandplanes", "custom"
        ]),
        menu_labels=([
            "Null", "Circles", "Box", "Planes", "Null and Circles",
            "Null and Box", "Null and Planes", "Custom"
        ]),
        default_value=2,
        icon_names=([]),
        item_generator_script="",
        item_generator_script_language=hou.scriptLanguage.Python,
        menu_type=hou.menuType.Normal)
    tg.appendToFolder("Misc", ct)
    ori = hou.MenuParmTemplate(
        "orientation",
        "Orientation",
        menu_items=(["xyz", "x", "y", "z", "xy", "xz", "yz"]),
        menu_labels=([
            "All planes", "YZ plane", "ZX plane", "XY plane", "YZ, ZX planes",
            "YZ, XY planes", "ZX, XY planes"
        ]),
        default_value=0,
        icon_names=([]),
        item_generator_script="",
        item_generator_script_language=hou.scriptLanguage.Python,
        menu_type=hou.menuType.Normal)
    tg.appendToFolder("Misc", ori)
    sm = hou.ToggleParmTemplate("shadedmode",
                                "Shaded Mode",
                                default_value=False)
    tg.appendToFolder("Misc", sm)
    null.setParmTemplateGroup(tg)

    #linking the parms
    control.parm("colorr").set(null.parm("colorr"))
    control.parm("colorg").set(null.parm("colorg"))
    control.parm("colorb").set(null.parm("colorb"))

    control.parm("scale").set(null.parm("geoscale"))

    control.parm("displayicon").set(null.parm("displayicon"))

    control.parm("controltype").set(null.parm("controltype"))

    control.parm("orientation").set(null.parm("orientation"))

    control.parm("shadedmode").set(null.parm("shadedmode"))

    null.layoutChildren()
    return null
Exemplo n.º 20
0
    script_callback_language=hou.scriptLanguage.Python, help="Smooth input hole boundaries"))
  inputs_smooth_factor = hou.IntParmTemplate("inputs_smooth_factor", "Smooth Boundaries Factor", 
    1, default_value=(50,), min=0, max=100,
    min_is_strict=True, max_is_strict=False,
    script_callback='hou.node(hou.pwd().path() + "/smooth_boundaries/smooth").parm("strength").set(int(hou.pwd().parm("inputs_smooth_factor").eval()) * int(hou.pwd().parm("isSmooth").eval()))',
    script_callback_language=hou.scriptLanguage.Python, help="Intensity of pre-repair smoothing")
  inputs_smooth_factor.setConditional(hou.parmCondType.DisableWhen, "{ isSmooth == 0 }")
  inputs_folder.addParmTemplate(inputs_smooth_factor)
  inputs_folder.addParmTemplate(hou.ButtonParmTemplate("new", "Full Reparation", script_callback = "hou.session.repair()", script_callback_language = hou.scriptLanguage.Python, help="Begin New Reparation"))
  
  # Low Frequency Folder
  low_folder = hou.FolderParmTemplate("low folder", "Low Frequency", folder_type = hou.folderType.Tabs)

  # - Low Frequency Small Folder
  low_small_folder = hou.FolderParmTemplate("low small folder", "Small Hole", folder_type = hou.folderType.Collapsible)
  low_small_options = hou.MenuParmTemplate("low_small_type", "Small Hole Repairer", ("MCT", "Centroid"), default_value = 0, help="hole filling technique to use on small holes")
  low_small_folder.addParmTemplate(low_small_options)

  # - Low Frequency Medium Folder
  low_med_folder = hou.FolderParmTemplate("low med folder", "Medium Hole", folder_type = hou.folderType.Collapsible)
  low_med_options =  hou.MenuParmTemplate("low_med_type", "Medium Hole Repairer", ("MCT with MRF",), default_value = 0, help="hole filling technique to use on medium holes")
  low_med_folder.addParmTemplate(low_med_options)

  # - Low Frequency Large Folder
  low_large_folder = hou.FolderParmTemplate("low large folder", "Large Hole", folder_type = hou.folderType.Collapsible)
  low_large_options =  hou.MenuParmTemplate("low_large_type", "Large Hole Repairer", ("MLS with MCT", "Improved AFT"), default_value = 0, help="hole filling technique to use on large holes")
  low_large_options.setMenuUseToken(True)
  low_large_folder.addParmTemplate(low_large_options)
  # -- AFT
  low_alpha_beta = hou.FloatParmTemplate("low_alpha_beta", "Alpha:Beta", 
    1, default_value=(0.5,), min=0.0, max=1.0, min_is_strict=True, max_is_strict=True,
Exemplo n.º 21
0
        rop.layoutChildren()
        hou.node(
            vrayRopNode.parm('render_network_environment').set(
                env_node.path()))

        menu_items = ('Angular', 'Cubic', 'Spherical', 'Mirror Ball', 'Screen',
                      'Spherical (3ds max)', 'Spherical (V-Ray)',
                      'Cylindrical (3ds max)', 'Shrink Wrap (3ds max)')

        env_node.addSpareParmTuple(
            hou.StringParmTemplate("file", "File", 1, (),
                                   hou.parmNamingScheme.Base1,
                                   hou.stringParmType.FileReference))

        env_node.addSpareParmTuple(
            hou.MenuParmTemplate("mapping_type", "Mapping Type", menu_items,
                                 menu_items, 2))
        env_node.addSpareParmTuple(
            hou.FloatParmTemplate('h_rotation', 'Horiz. Rotation', 1, (0, ),
                                  0.0, 360.0))
        #env_node.addSpareParmTuple(hou.FloatParmTemplate('v_rotation', 'Vert. Rotation', 1, (0,), 0.0, 360.0))
        env_node.addSpareParmTuple(
            hou.ToggleParmTemplate('h_flip', 'Flip Horizontally', 0))
        #env_node.addSpareParmTuple(hou.ToggleParmTemplate('v_flip', 'Flip Vertically', 0))

        env_node.addSpareParmTuple(
            hou.ToggleParmTemplate('ground_on', 'Ground Projection', 0))
        env_node.addSpareParmTuple(
            hou.FloatParmTemplate('ground_radius', 'Radius', 1, (1000, ), 0.0,
                                  1000000.0, False, False,
                                  hou.parmLook.Regular,
                                  hou.parmNamingScheme.XYZW, '{ground_on 0}'))
Exemplo n.º 22
0
    def _create_sgtk_parm_fields(self, node, hou=None):
        """
        Create the sgtk folder template.

        This contains the common parameters used by all node handlers.

        :param node: A :class:`hou.Node` instance.
        :param bool use_sgtk_default: Whether the "Use Shotgun" checkbox is to be
            checked by default.
        :param hou: The houdini module. We have to lazy load the houdini python
            module here, but not in the hooks, so use hook's imports and pass it
            for efficiency.
        """
        if not hou:
            import hou

        sgtk_templates = self._create_sgtk_parms(node)

        all_versions = hou.StringParmTemplate(self.SGTK_ALL_VERSIONS,
                                              "All Versions",
                                              1,
                                              is_hidden=True)
        sgtk_templates.append(all_versions)

        version = hou.MenuParmTemplate(
            self.SGTK_VERSION,
            "Version",
            tuple(),
            item_generator_script=self.generate_callback_script_str(
                "populate_versions"),
            item_generator_script_language=hou.scriptLanguage.Python,
            script_callback=self.generate_callback_script_str(
                "refresh_file_path_from_version"),
            script_callback_language=hou.scriptLanguage.Python,
        )
        version.setConditional(hou.parmCondType.DisableWhen,
                               "{ use_sgtk != 1 }")
        version.setJoinWithNext(True)
        sgtk_templates.append(version)

        refresh_button = hou.ButtonParmTemplate(
            self.SGTK_REFRESH_VERSIONS,
            "Refresh Versions",
            script_callback=self.generate_callback_script_str(
                "refresh_file_path_from_version"),
            script_callback_language=hou.scriptLanguage.Python,
        )
        refresh_button.setConditional(
            hou.parmCondType.DisableWhen,
            '{ use_sgtk != 1 } { sgtk_element == "" }')
        refresh_button.setJoinWithNext(True)
        sgtk_templates.append(refresh_button)

        resolved_version = hou.StringParmTemplate(self.SGTK_RESOLVED_VERSION,
                                                  "Resolved Version",
                                                  1,
                                                  default_value=("1", ))
        resolved_version.setConditional(hou.parmCondType.DisableWhen,
                                        "{ sgtk_version != -1 }")
        sgtk_templates.append(resolved_version)

        return sgtk_templates
Exemplo n.º 23
0
def light_blocker_transform(name):
    # create subnet
    light_blocker_transform.subnet = obj.createNode('subnet', name)
    
    # create geo and matnet
    geo = light_blocker_transform.subnet.createNode('geo', 'light_blocker_shape1')
    matnet = light_blocker_transform.subnet.createNode('matnet')
    light_blocker_transform.subnet.layoutChildren()
    
    # create light blocker
    amb = matnet.createNode('arnold_materialbuilder', 'light_blocker1')
    amb.children()[0].destroy()
    light_blocker_transform.out_light = amb.createNode('arnold_light')
    light_blocker = amb.createNode('arnold::light_blocker')
    light_blocker_transform.out_light.setInput(2, light_blocker, 0)
    amb.layoutChildren()
    
    # create shapes
    box = geo.createNode('box')
    sphere = geo.createNode('sphere')
    grid = geo.createNode('grid')
    tube = geo.createNode('tube')
    switch = geo.createNode('switch')
    color = geo.createNode('color')
    convline = geo.createNode('convertline')
    null = geo.createNode('null', 'OUT')
    
    # set geo Arnold Visibility values
    geo.parm('ar_visibility_camera').set(0)
    geo.parm('ar_visibility_shadow').set(0)
    geo.parm('ar_visibility_diffuse_transmit').set(0)
    geo.parm('ar_visibility_specular_transmit').set(0)
    geo.parm('ar_visibility_diffuse_reflect').set(0)
    geo.parm('ar_visibility_specular_reflect').set(0)
    geo.parm('ar_visibility_volume').set(0)
    geo.parm('ar_receive_shadows').set(0)
    geo.parm('ar_self_shadows').set(0)
    geo.parm('ar_opaque').set(0)
    geo.parm('ar_skip').set(1)
    
    # set connections
    switch.setInput(0, box, 0)
    switch.setInput(1, sphere, 0)
    switch.setInput(2, grid, 0)
    switch.setInput(3, tube, 0)
    color.setInput(0, switch, 0)
    convline.setInput(0, color, 0)
    null.setInput(0, convline, 0)
    geo.layoutChildren()
    
    # set shape nodes values
    sphere.parm('type').set(2)
    sphere.parm('scale').set(0.5)
    sphere.parm('rows').set(16)
    sphere.parm('cols').set(16)
    grid.parm('sizex').set(1)
    grid.parm('sizey').set(1)
    grid.parm('rx').set(90)
    grid.parm('rows').set(2)
    grid.parm('cols').set(2)
    tube.parm('type').set(1)
    tube.parm('cap').set(1)
    tube.parm('rad1').set(0.5)
    tube.parm('rad2').set(0.5)
    tube.parm('cols').set(20)
    color.parm('colorr').set(0.8)
    color.parm('colorg').set(0.0)
    color.parm('colorb').set(0.0)
    convline.parm('computelength').set(0)
    null.setDisplayFlag(1)
    null.setRenderFlag(1)
    
    # add Shape Transform folder
    subnet_tg = light_blocker_transform.subnet.parmTemplateGroup()
    shp_folder = hou.FolderParmTemplate('shape_transform', 'Shape Transform', folder_type = hou.folderType.Simple)
    
    # add Geometry Type parameter in Shape Transfer folder
    geo_type_menu = ('box', 'sphere', 'plane', 'cylinder')
    geo_type_label = ('Box', 'Sphere', 'Plane', 'Cylinder')
    geo_type = hou.MenuParmTemplate('geometry_type', "Geometry Type", geo_type_menu, menu_labels=(geo_type_label))
    shp_folder.addParmTemplate(geo_type)
    
    # extract default Transform parameters
    trans = subnet_tg.find('t')
    rot = subnet_tg.find('r')
    scale = subnet_tg.find('s')
    
    # delete default Transform parameters
    subnet_tg.remove(trans)
    subnet_tg.remove(rot)
    subnet_tg.remove(scale)
    
    # Transfer default Transform parameters under Shape Transform folder
    shp_folder.addParmTemplate(trans)
    shp_folder.addParmTemplate(rot)
    shp_folder.addParmTemplate(scale)
    subnet_tg.append(shp_folder)
    
    # add Parameters folder
    parm_folder = hou.FolderParmTemplate('parameters', 'Parameters', folder_type = hou.folderType.Simple)
    
    # add parameters under Parameters folder
    density = hou.FloatParmTemplate('density', 'Density', 1, min=0.0, max=1.0)
    roundness = hou.FloatParmTemplate('roundness', 'Roundness', 1, min=0.0, max=1.0)
    width_edge = hou.FloatParmTemplate('width_edge', 'Width Edge', 1, min=0.0, max=1.0)
    height_edge = hou.FloatParmTemplate('height_edge', 'Height Edge', 1, min=0.0, max=1.0)
    ramp = hou.FloatParmTemplate('ramp', 'Ramp', 1, min=0.0, max=1.0)
    
    axis_menu = ('x', 'y', 'z')
    axis_label = ('X', 'Y', 'Z')
    axis = hou.MenuParmTemplate('axis', "Axis", axis_menu, menu_labels=(axis_label))
    
    parm_folder.addParmTemplate(density)
    parm_folder.addParmTemplate(roundness)
    parm_folder.addParmTemplate(width_edge)
    parm_folder.addParmTemplate(height_edge)
    parm_folder.addParmTemplate(ramp)
    parm_folder.addParmTemplate(axis)
    subnet_tg.append(parm_folder)
    
    # hide all default parameters of subnet
    subnet_tg.hideFolder('Transform', 1)
    subnet_tg.hideFolder('Subnet', 1)
    light_blocker_transform.subnet.setParmTemplateGroup(subnet_tg)
    
    # set relative references
    hou.parm(light_blocker.path()+'/geometry_type').set(hou.parm(light_blocker_transform.subnet.path()+'/geometry_type'))
    hou.parm(switch.path()+'/input').setExpression("""ch("../../geometry_type")
0==box
1==sphere
2==plane
3==cylinder""")
    hou.parm(light_blocker.path()+'/density').set(hou.parm(light_blocker_transform.subnet.path()+'/density'))
    hou.parm(light_blocker.path()+'/roundness').set(hou.parm(light_blocker_transform.subnet.path()+'/roundness'))
    hou.parm(light_blocker.path()+'/width_edge').set(hou.parm(light_blocker_transform.subnet.path()+'/width_edge'))
    hou.parm(light_blocker.path()+'/height_edge').set(hou.parm(light_blocker_transform.subnet.path()+'/height_edge'))
    hou.parm(light_blocker.path()+'/ramp').set(hou.parm(light_blocker_transform.subnet.path()+'/ramp'))
    hou.parm(light_blocker.path()+'/axis').set(hou.parm(light_blocker_transform.subnet.path()+'/axis'))
    
    # set 4x4 matrix
    hou.parm(light_blocker.path()+'/geometry_matrix1').setExpression('ch("../../../sx")*(cos(ch("../../../ry"))*cos(ch("../../../rz")))')
    hou.parm(light_blocker.path()+'/geometry_matrix2').setExpression('ch("../../../sx")*(cos(ch("../../../ry"))*sin(ch("../../../rz")))')
    hou.parm(light_blocker.path()+'/geometry_matrix3').setExpression('-ch("../../../sx")*(sin(ch("../../../ry")))')
    hou.parm(light_blocker.path()+'/geometry_matrix5').setExpression('(-ch("../../../sy")*(cos(ch("../../../rx"))*sin(ch("../../../rz"))))+(ch("../../../sy")*(sin(ch("../../../rx"))*sin(ch("../../../ry"))*cos(ch("../../../rz"))))')
    hou.parm(light_blocker.path()+'/geometry_matrix6').setExpression('(ch("../../../sy")*(cos(ch("../../../rx"))*cos(ch("../../../rz"))))+(ch("../../../sy")*(sin(ch("../../../rx"))*sin(ch("../../../ry"))*sin(ch("../../../rz"))))')
    hou.parm(light_blocker.path()+'/geometry_matrix7').setExpression('ch("../../../sy")*(sin(ch("../../../rx"))*cos(ch("../../../ry")))')
    hou.parm(light_blocker.path()+'/geometry_matrix9').setExpression('(ch("../../../sz")*(sin(ch("../../../rx"))*sin(ch("../../../rz"))))+(ch("../../../sz")*(cos(ch("../../../rx"))*sin(ch("../../../ry"))*cos(ch("../../../rz"))))')
    hou.parm(light_blocker.path()+'/geometry_matrix10').setExpression('(-ch("../../../sz")*(sin(ch("../../../rx"))*cos(ch("../../../rz"))))+(ch("../../../sz")*(cos(ch("../../../rx"))*sin(ch("../../../ry"))*sin(ch("../../../rz"))))')
    hou.parm(light_blocker.path()+'/geometry_matrix11').setExpression('ch("../../../sz")*(cos(ch("../../../rx"))*cos(ch("../../../ry")))')
    hou.parm(light_blocker.path()+'/geometry_matrix13').setExpression('ch("../../../tx")')
    hou.parm(light_blocker.path()+'/geometry_matrix14').setExpression('ch("../../../ty")')
    hou.parm(light_blocker.path()+'/geometry_matrix15').setExpression('ch("../../../tz")')