def registerShapeID():
    """
    Registers a new ShapeID node type using the NodeTypeBuilder utility class.
    """

    from Katana import Nodes3DAPI
    from Katana import FnAttribute

    def buildShapeIDOpChain(node, interface):
        """
        Defines the callback function used to define the Ops chain for the
        node type being registered.

        @type node: C{Nodes3DAPI.NodeTypeBuilder.ShapeID}
        @type interface: C{Nodes3DAPI.NodeTypeBuilder.BuildChainInterface}
        @param node: The node for which to define the Ops chain
        @param interface: The interface providing the functions needed to set
            up the Ops chain for the given node.
        """
        # Get the current frame time
        frameTime = interface.getGraphState().getTime()

        # Set the minimum number of input ports
        interface.setMinRequiredInputs(1)

        argsGb = FnAttribute.GroupBuilder()

        # Parse the CEL parameter
        celParam = node.getParameter('CEL')
        if celParam:
            argsGb.set('CEL', celParam.getValue(frameTime))

        # Parse the displacement parameter
        pathParam = node.getParameter('regedit')
        if pathParam:
            argsGb.set('regedit', pathParam.getValue(frameTime))

        # Add the ShapeID Op to the Ops chain
        interface.appendOp('ShapeID', argsGb.build())

    # Create a NodeTypeBuilder to register the new type
    nodeTypeBuilder = Nodes3DAPI.NodeTypeBuilder('ShapeID')

    # Add an input port
    nodeTypeBuilder.setInputPortNames(('in', ))

    # Build the node's parameters
    gb = FnAttribute.GroupBuilder()
    gb.set('CEL', FnAttribute.StringAttribute(''))
    gb.set('regedit', FnAttribute.StringAttribute('*.json'))

    # Set the parameters template
    nodeTypeBuilder.setParametersTemplateAttr(gb.build())
    # Set parameter hints
    nodeTypeBuilder.setHintsForParameter('CEL', {'widget': 'cel'})
    # Set the callback responsible to build the Ops chain
    nodeTypeBuilder.setBuildOpChainFnc(buildShapeIDOpChain)

    # Build the new node type
    nodeTypeBuilder.build()
예제 #2
0
def buildOpChain(self, interface):
    interface.setMinRequiredInputs(0)
    
    graphState = interface.getGraphState()
    pxrUsdInArgs = self.buildPxrUsdInOpArgsAtGraphState(graphState)
    
    # When buildOpChain is reached as result of a call to
    # buildPxrUsdInOpArgsFromDownstreamNode, an additional entry will be
    # present in the graphState (otherwise not meaningful to the cooked scene).
    # If found, we'll record opArgs at the specified key in a member variable
    # dict.
    argsCookTmpKey = graphState.getDynamicEntry(kArgsCookTmpKeyToken)
    if isinstance(argsCookTmpKey, FnAttribute.StringAttribute):
        self._argsCookTmp[argsCookTmpKey.getValue('', False)] = pxrUsdInArgs
    
    
    # our primary op in the chain that will create the root location
    sscb = FnGeolibServices.OpArgsBuilders.StaticSceneCreate(True)

    sscb.addSubOpAtLocation(self.getScenegraphLocation(
        interface.getFrameTime()), 'PxrUsdIn', pxrUsdInArgs)

    sscb.setAttrAtLocation('/root', 'info.usdLoader', FnAttribute.StringAttribute('PxrUsdIn'))

    interface.appendOp('StaticSceneCreate', sscb.build())
예제 #3
0
def buildPxrUsdInOpArgsFromDownstreamNode(self,
                                          downstreamNode,
                                          graphState,
                                          portIndex=0):
    if not hasattr(self, '_argsCookTmp'):
        self._argsCookTmp = {}

    key = (FnAttribute.GroupBuilder().set('graphState',
                                          graphState.getOpSystemArgs()).set(
                                              'node',
                                              hash(downstreamNode)).set(
                                                  'portIndex',
                                                  portIndex).build().getHash())

    # Set a dynamic entry that's not prefixed with "var:" so it won't show up
    # in op system args (or other graph state comparisons other than hash
    # uniqueness)
    useGraphState = graphState.edit().setDynamicEntry(
        kArgsCookTmpKeyToken, FnAttribute.StringAttribute(key)).build()

    # trigger a cook with this unique graph state
    Nodes3DAPI.CreateClient(downstreamNode,
                            graphState=useGraphState,
                            portIndex=portIndex)

    if key in self._argsCookTmp:
        result = self._argsCookTmp[key]
        return result
    else:
        # TODO, exception?
        pass
예제 #4
0
파일: PxrUsdIn.py 프로젝트: MWDD/USD
def buildOpChain(self, interface):
    interface.setMinRequiredInputs(0)

    gb = FnAttribute.GroupBuilder()

    gb.set('fileName', interface.buildAttrFromParam(
        self.getParameter('fileName')))

    gb.set('location', interface.buildAttrFromParam(
        self.getParameter('location')))

    gb.set('isolatePath', interface.buildAttrFromParam(
        self.getParameter('isolatePath')))

    gb.set('variants', interface.buildAttrFromParam(
        self.getParameter('variants')))

    gb.set('ignoreLayerRegex', interface.buildAttrFromParam(
        self.getParameter('ignoreLayerRegex')))

    gb.set('motionSampleTimes', interface.buildAttrFromParam(
        self.getParameter('motionSampleTimes')))

    gb.set('verbose', interface.buildAttrFromParam(
        self.getParameter('verbose'), 
            numberType=FnAttribute.IntAttribute))
    
    gb.set('instanceMode', interface.buildAttrFromParam(
        self.getParameter('instanceMode')))

    sessionValues = (
            interface.getGraphState().getDynamicEntry("var:pxrUsdInSession"))
    if isinstance(sessionValues, FnAttribute.GroupAttribute):
        gb.set('session', sessionValues)

    
    gb.set('system', interface.getGraphState().getOpSystemArgs())

    # our primary op in the chain that will create the root location
    sscb = FnGeolibServices.OpArgsBuilders.StaticSceneCreate(True)

    # check for any extra attributes or namespaces set downstream
    # via graph state
    extra = interface.getGraphState().getDynamicEntry('var:usdExtraAttributesOrNamespaces')
    if extra:
        gb.set('extraAttributesOrNamespaces', extra)

    argsOverride = interface.getGraphState().getDynamicEntry('var:pxrUsdInArgs')
    if isinstance(argsOverride, FnAttribute.GroupAttribute):
        gb.update(argsOverride)

    # add the PxrUsdIn op as a sub op
    pxrUsdInArgs = gb.build()
    sscb.addSubOpAtLocation(self.getScenegraphLocation(
        interface.getFrameTime()), 'PxrUsdIn', pxrUsdInArgs)

    sscb.setAttrAtLocation('/root', 'info.usdLoader', FnAttribute.StringAttribute('PxrUsdIn'))

    interface.appendOp('StaticSceneCreate', sscb.build())
 def __init__(self, locationPath, locationType):
     self.locationPath = locationPath
     self.locationType = locationType
     self.staticSCB = FnGeolibServices.OpArgsBuilders.StaticSceneCreate()
     self.staticSCB.createEmptyLocation(self.locationPath)
     self.staticSCB.setAttrAtLocation(
         self.locationPath, 'type',
         FnAttribute.StringAttribute(self.locationType))
예제 #6
0
    def buildMaterialDescribeOpChain(node, interface):
        interface.setMinRequiredInputs(0)

        baseLocationParam = node.getParameter('baseLocation')
        baseLocationString = baseLocationParam.getValue(0)

        materialNameParam = node.getParameter('materialName')
        materialNameString = materialNameParam.getValue(0)

        descriptionParam = node.getParameter('description')
        descriptionString = descriptionParam.getValue(0)

        specRoughnessValuesConversionTypeParam = node.getParameter(
            'specRoughnessValuesConversionType')
        specRoughnessValuesConversionTypeValue = specRoughnessValuesConversionTypeParam.getValue(
            0)

        enableCausticsInArnoldParam = node.getParameter(
            'enableCausticsInArnold')
        enableCausticsInArnoldValue = bool(
            enableCausticsInArnoldParam.getValue(0))

        materialDefinition = parseMaterialDescription(descriptionString)

        rendererListGroupParam = node.getParameter('rendererList')
        renderersToMakeMatsFor = []
        numRendererItems = rendererListGroupParam.getNumChildren()
        for i in range(0, numRendererItems):
            subItemParam = rendererListGroupParam.getChildByIndex(i)
            intValue = subItemParam.getValue(0)
            if intValue == 0:
                continue

            rendererName = MaterialPlugin.pluginsNameList[i]
            renderersToMakeMatsFor.append(rendererName)

            materialLocationPath = os.path.join(baseLocationString,
                                                rendererName,
                                                materialNameString)

            materialStaticSCB = FnGeolibServices.OpArgsBuilders.StaticSceneCreate(
            )
            materialStaticSCB.createEmptyLocation(materialLocationPath)
            materialStaticSCB.setAttrAtLocation(
                materialLocationPath, 'type',
                FnAttribute.StringAttribute('material'))

            # invoke the renderer material plugin to create its attributes on the location...
            pluginResult = MaterialPlugin.pluginsDict[rendererName]
            pluginInstance = pluginResult[2]
            # todo: use keyword / dict for all these options...
            pluginInstance.generateMaterialAttributes(
                materialDefinition, materialStaticSCB, materialLocationPath,
                specRoughnessValuesConversionTypeValue,
                enableCausticsInArnoldValue)

            interface.appendOp("StaticSceneCreate", materialStaticSCB.build())
예제 #7
0
def buildOpChain(self, interface):
    interface.setMinRequiredInputs(0)
    
    frameTime = interface.getGraphState().getTime()
    
    
    # simpler case for the archive
    if self.getParameter('asArchive').getValue(frameTime):
        sscb = FnGeolibServices.OpArgsBuilders.StaticSceneCreate(True)
        location = self.getScenegraphLocation(frameTime)
        sscb.createEmptyLocation(location, 'usd archive')
        
        
        gb = FnAttribute.GroupBuilder()
        
        
        for name in ('fileName', 'isolatePath'):
            gb.set(name, interface.buildAttrFromParam(
                    self.getParameter(name)))
        
        gb.set('currentTime', FnAttribute.DoubleAttribute(frameTime))
        
        attrs = gb.build()
        
        sscb.setAttrAtLocation(location, 'geometry', attrs)
        
        if self.getParameter('includeProxyForArchive').getValue(frameTime):
            sscb.addSubOpAtLocation(location,
                    'UsdIn.AddViewerProxy', attrs)
        
        
        interface.appendOp('StaticSceneCreate', sscb.build())
        return
    
    
    graphState = interface.getGraphState()
    pxrUsdInArgs = self.buildPxrUsdInOpArgsAtGraphState(graphState)
    
    # When buildOpChain is reached as result of a call to
    # buildPxrUsdInOpArgsFromDownstreamNode, an additional entry will be
    # present in the graphState (otherwise not meaningful to the cooked scene).
    # If found, we'll record opArgs at the specified key in a member variable
    # dict.
    argsCookTmpKey = graphState.getDynamicEntry(kArgsCookTmpKeyToken)
    if isinstance(argsCookTmpKey, FnAttribute.StringAttribute):
        self._argsCookTmp[argsCookTmpKey.getValue('', False)] = pxrUsdInArgs
    
    
    # our primary op in the chain that will create the root location
    sscb = FnGeolibServices.OpArgsBuilders.StaticSceneCreate(True)

    sscb.addSubOpAtLocation(self.getScenegraphLocation(
        interface.getFrameTime()), 'UsdIn', pxrUsdInArgs)

    sscb.setAttrAtLocation('/root', 'info.usdLoader', FnAttribute.StringAttribute('UsdIn'))

    interface.appendOp('StaticSceneCreate', sscb.build())
예제 #8
0
    def addImageShadingNode(self, materialStaticSCB, materialLocationPath,
                            imagePath, nodeName):
        matAttrPath = "material.nodes." + nodeName + "."
        materialStaticSCB.setAttrAtLocation(
            materialLocationPath, matAttrPath + "name",
            FnAttribute.StringAttribute(nodeName))
        materialStaticSCB.setAttrAtLocation(
            materialLocationPath, matAttrPath + "type",
            FnAttribute.StringAttribute("image"))
        materialStaticSCB.setAttrAtLocation(
            materialLocationPath, matAttrPath + "target",
            FnAttribute.StringAttribute("arnold"))
        materialStaticSCB.setAttrAtLocation(
            materialLocationPath, matAttrPath + "srcName",
            FnAttribute.StringAttribute(nodeName))

        materialStaticSCB.setAttrAtLocation(
            materialLocationPath, matAttrPath + "parameters.filename",
            FnAttribute.StringAttribute(imagePath))
예제 #9
0
def build_pass_resolve_op_chain(node, interface):
    """
    """
    module_logger.debug("PassResolve - build_pass_resolve_op_chain()")

    interface.setMinRequiredInputs(0)

    frame_time = interface.getGraphState().getTime()
    active_pass_location_param = node.getParameter("activePassLocation")

    # Setup the currently active pass in the SceneGraph.
    attribute_set_args_builder = FnGeolibServices.OpArgsBuilders.AttributeSet()

    attribute_set_args_builder.setCEL(["/root"])
    if active_pass_location_param.getValue(frame_time):
        attribute_set_args_builder.setAttr(
            "passResolve.activePassLocation",
            FnAttribute.StringAttribute(
                active_pass_location_param.getValue(frame_time)))

    interface.appendOp("AttributeSet", attribute_set_args_builder.build())

    # Expose all locations under "/root/world" to the PassVisibility Op that will
    # set the appropriate locations as visible or not, as per the setup of the currently
    # active pass.
    group_builder = FnAttribute.GroupBuilder()
    attribute_set_args_builder = FnGeolibServices.OpArgsBuilders.AttributeSet()

    attribute_set_args_builder.setCEL(["/root/world//*"])
    attribute_set_args_builder.addSubOp("PassVisibility",
                                        group_builder.build())

    interface.appendOp("AttributeSet", attribute_set_args_builder.build())

    # Expose all locations under "/root/world" to the PassRays Op that will
    # set the rays related attributes on the appropriate locations, which are renderer dependent,
    # as per the setup of the currently active pass.
    group_builder = FnAttribute.GroupBuilder()
    attribute_set_args_builder = FnGeolibServices.OpArgsBuilders.AttributeSet()

    attribute_set_args_builder.setCEL(["/root/world//*"])
    attribute_set_args_builder.addSubOp("PassRays", group_builder.build())

    interface.appendOp("AttributeSet", attribute_set_args_builder.build())

    # Expose the "/root" location to the PassCollections Op that will
    # create collections attributes on the root location, according the to active pass configuration.
    group_builder = FnAttribute.GroupBuilder()
    attribute_set_args_builder = FnGeolibServices.OpArgsBuilders.AttributeSet()

    attribute_set_args_builder.setCEL(["/root"])
    attribute_set_args_builder.addSubOp("PassCollections",
                                        group_builder.build())

    interface.appendOp("AttributeSet", attribute_set_args_builder.build())
예제 #10
0
    def addImageShadingNode(self, materialStaticSCB, materialLocationPath,
                            imagePath, nodeName):
        matAttrPath = "material.nodes." + nodeName + "."
        materialStaticSCB.setAttrAtLocation(
            materialLocationPath, matAttrPath + "name",
            FnAttribute.StringAttribute(nodeName))
        materialStaticSCB.setAttrAtLocation(
            materialLocationPath, matAttrPath + "type",
            FnAttribute.StringAttribute("PxrTexture"))
        materialStaticSCB.setAttrAtLocation(
            materialLocationPath, matAttrPath + "target",
            FnAttribute.StringAttribute("prman"))
        materialStaticSCB.setAttrAtLocation(
            materialLocationPath, matAttrPath + "srcName",
            FnAttribute.StringAttribute(nodeName))

        convertedFilename = self.replacementTexture(imagePath)
        materialStaticSCB.setAttrAtLocation(
            materialLocationPath, matAttrPath + "parameters.filename",
            FnAttribute.StringAttribute(convertedFilename))
예제 #11
0
def buildOpChain(self, interface):
    interface.setExplicitInputRequestsEnabled(True)

    graphState = interface.getGraphState()
    frameTime = interface.getFrameTime()
    locationsParam = self.getParameter("locations")

    locations = [
        y for y in (x.getValue(frameTime)
                    for x in locationsParam.getChildren()) if y
    ]

    if locations:
        existingValue = (graphState.getDynamicEntry("var:pxrUsdInSession")
                         or FnAttribute.GroupAttribute())

        # later nodes set to 'replace' win out
        maskIsFinal = existingValue.getChildByName('maskIsFinal')
        if not maskIsFinal:

            gb = FnAttribute.GroupBuilder()

            gb.update(existingValue)

            mode = self.getParameter('mode').getValue(frameTime)

            if mode == 'replace':
                gb.set('mask', FnAttribute.StringAttribute(locations))
                gb.set('maskIsFinal', 1)
            else:
                existingLocationsAttr = existingValue.getChildByName('mask')
                if isinstance(existingLocationsAttr,
                              FnAttribute.StringAttribute):
                    locations.extend(existingLocationsAttr.getNearestSample(0))

                gb.set('mask', FnAttribute.StringAttribute(locations))

            graphState = (graphState.edit().setDynamicEntry(
                "var:pxrUsdInSession", gb.build()).build())

    interface.addInputRequest("in", graphState)
예제 #12
0
def buildOpChain(self, interface):
    interface.setExplicitInputRequestsEnabled(True)
    
    graphState = interface.getGraphState()
    
    frameTime = interface.getFrameTime()
    
    location = self.getParameter("location").getValue(frameTime)
    
    variantSetName = ''
    if self.getParameter("args.variantSetName.enable").getValue(frameTime):
        variantSetName = self.getParameter("args.variantSetName.value").getValue(
                frameTime)
    
    
    variantSelection = None
    if self.getParameter("args.variantSelection.enable").getValue(frameTime):
         variantSelection = self.getParameter(
                "args.variantSelection.value").getValue(frameTime)
    
    if location and variantSetName and variantSelection is not None:
        entryName = FnAttribute.DelimiterEncode(location)
        entryPath = "variants." + entryName + "." + variantSetName
        
        valueAttr = FnAttribute.StringAttribute(variantSelection)
        gb = FnAttribute.GroupBuilder()
        gb.set(entryPath, valueAttr)
        
        for addLocParam in self.getParameter(
                'additionalLocations').getChildren():
            location = addLocParam.getValue(frameTime)
            if location:
                entryName = FnAttribute.DelimiterEncode(location)
                entryPath = "variants." + entryName + "." + variantSetName
                gb.set(entryPath, valueAttr)
        
        
        existingValue = (
                interface.getGraphState().getDynamicEntry("var:pxrUsdInSession"))
        
        if isinstance(existingValue, FnAttribute.GroupAttribute):
            gb.deepUpdate(existingValue)
        
        graphState = (graphState.edit()
                .setDynamicEntry("var:pxrUsdInSession", gb.build())
                .build())
        
    
    interface.addInputRequest("in", graphState)
def buildPointCloudCreateOpChain(node, interface):
	interface.setMinRequiredInputs(0)
	argsGb = FnAttribute.GroupBuilder()

	targetLocationParam = node.getParameter('location')
	generateTypeParam = node.getParameter('generateType')
	fileTypeParam = node.getParameter('fileType')
	filePathParam = node.getParameter('filePath')
	numPointsParam = node.getParameter('numPoints')
	splitPointcloudLocationsParam = node.getParameter('splitPointcloudLocations')
	pointWidthTypeParam = node.getParameter('pointWidthType')
	constantPointWidthParam = node.getParameter('constantPointWidth')
	randomPointWidthMinParam = node.getParameter('randomPointWidthMin')
	randomPointWidthMaxParam = node.getParameter('randomPointWidthMax')
	areaSpreadParamX = node.getParameter('areaSpread.i0')
	areaSpreadParamY = node.getParameter('areaSpread.i1')
	areaSpreadParamZ = node.getParameter('areaSpread.i2')
	extraFloatPrimvarTypeParam = node.getParameter('extraFloatPrimvarType')
	extraVectorPrimvarTypeParam = node.getParameter('extraVectorPrimvarType')
	extraColorPrimvarTypeParam = node.getParameter('extraColorPrimvarType')
	if targetLocationParam:
		location = targetLocationParam.getValue(0)

		locationPaths = location[1:].split('/')[1:]
		attrsHierarchy = 'c.' + '.c.'.join(locationPaths)

		argsGb.set(attrsHierarchy + '.a.generateType', FnAttribute.IntAttribute(generateTypeParam.getValue(0)))
		if generateTypeParam.getValue(0) == 1:
			argsGb.set(attrsHierarchy + '.a.fileType', FnAttribute.IntAttribute(fileTypeParam.getValue(0)))
			argsGb.set(attrsHierarchy + '.a.filePath', FnAttribute.StringAttribute(filePathParam.getValue(0)))
		else:
			argsGb.set(attrsHierarchy + '.a.numPoints', FnAttribute.IntAttribute(numPointsParam.getValue(0)))
			argsGb.set(attrsHierarchy + '.a.splitPointcloudLocations', FnAttribute.IntAttribute(splitPointcloudLocationsParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.pointWidthType', FnAttribute.IntAttribute(pointWidthTypeParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.constantPointWidth', FnAttribute.FloatAttribute(constantPointWidthParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.randomPointWidthMin', FnAttribute.FloatAttribute(randomPointWidthMinParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.randomPointWidthMax', FnAttribute.FloatAttribute(randomPointWidthMaxParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.areaSpread', FnAttribute.FloatAttribute([areaSpreadParamX.getValue(0), areaSpreadParamY.getValue(0), areaSpreadParamZ.getValue(0)], 3))
		argsGb.set(attrsHierarchy + '.a.extraFloatPrimvarType', FnAttribute.IntAttribute(extraFloatPrimvarTypeParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.extraVectorPrimvarType', FnAttribute.IntAttribute(extraVectorPrimvarTypeParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.extraColorPrimvarType', FnAttribute.IntAttribute(extraColorPrimvarTypeParam.getValue(0)))

	interface.appendOp('PointCloudCreate', argsGb.build())
			argsGb.set(attrsHierarchy + '.a.splitPointcloudLocations', FnAttribute.IntAttribute(splitPointcloudLocationsParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.pointWidthType', FnAttribute.IntAttribute(pointWidthTypeParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.constantPointWidth', FnAttribute.FloatAttribute(constantPointWidthParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.randomPointWidthMin', FnAttribute.FloatAttribute(randomPointWidthMinParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.randomPointWidthMax', FnAttribute.FloatAttribute(randomPointWidthMaxParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.areaSpread', FnAttribute.FloatAttribute([areaSpreadParamX.getValue(0), areaSpreadParamY.getValue(0), areaSpreadParamZ.getValue(0)], 3))
		argsGb.set(attrsHierarchy + '.a.extraFloatPrimvarType', FnAttribute.IntAttribute(extraFloatPrimvarTypeParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.extraVectorPrimvarType', FnAttribute.IntAttribute(extraVectorPrimvarTypeParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.extraColorPrimvarType', FnAttribute.IntAttribute(extraColorPrimvarTypeParam.getValue(0)))

	interface.appendOp('PointCloudCreate', argsGb.build())

nodeTypeBuilder = Nodes3DAPI.NodeTypeBuilder('PointCloudCreate')

gb = FnAttribute.GroupBuilder()
gb.set('location', FnAttribute.StringAttribute('/root/world/geo/pointcloud1'))
gb.set('generateType', FnAttribute.IntAttribute(0))
gb.set('fileType', FnAttribute.IntAttribute(0))
gb.set('filePath', FnAttribute.StringAttribute(""))
gb.set('numPoints', FnAttribute.IntAttribute(10000))
gb.set('splitPointcloudLocations', FnAttribute.IntAttribute(0))
gb.set('pointWidthType', FnAttribute.IntAttribute(0))
gb.set('constantPointWidth', FnAttribute.FloatAttribute(0.1))
gb.set('randomPointWidthMin', FnAttribute.FloatAttribute(0.1))
gb.set('randomPointWidthMax', FnAttribute.FloatAttribute(0.2))
gb.set('areaSpread', FnAttribute.FloatAttribute([20.0, 20.0, 20.0], 3))
gb.set('extraFloatPrimvarType', FnAttribute.IntAttribute(0))
gb.set('extraVectorPrimvarType', FnAttribute.IntAttribute(0))
gb.set('extraColorPrimvarType', FnAttribute.IntAttribute(0))

nodeTypeBuilder.setParametersTemplateAttr(gb.build())
예제 #15
0
    def buildLocationDescribeOpChain(node, interface):
        interface.setMinRequiredInputs(0)

        locationParam = node.getParameter('location')
        if not locationParam:
            # set an error
            staticSCB = FnGeolibServices.OpArgsBuilders.StaticSceneCreate()
            staticSCB.createEmptyLocation('/root/world/geo/')
            staticSCB.setAttrAtLocation(
                '/root/world/', 'errorMessage',
                FnAttribute.StringAttribute(
                    'Invalid location used for LocationDescribe'))
            interface.appendOp('StaticSceneCreate', staticSCB.build())
        else:
            # do the actual work creating location and attributes
            locationPath = locationParam.getValue(0)

            modeParam = node.getParameter('mode')
            modeParamValue = modeParam.getValue(0)
            descriptionParam = node.getParameter('description')
            typeParam = node.getParameter('type')
            typeParamValue = typeParam.getValue(0)

            interface.setMinRequiredInputs(0 if modeParamValue ==
                                           "create" else 1)

            internalBuilder = InternalBuilderSSC(
                locationPath, typeParamValue
            ) if modeParamValue == "create" else InternalBuilderAS(
                locationPath, typeParamValue)

            descriptionString = descriptionParam.getValue(0)
            attributeItems = parseDescription(descriptionString)

            for attribItem in attributeItems:
                if attribItem[0] == 1:
                    # single item
                    if attribItem[1] == "int":
                        internalBuilder.addAttribute(
                            attribItem[2],
                            FnAttribute.IntAttribute(int(attribItem[3])))
                    elif attribItem[1] == "string":
                        internalBuilder.addAttribute(
                            attribItem[2],
                            FnAttribute.StringAttribute(attribItem[3]))
                    elif attribItem[1] == "float":
                        internalBuilder.addAttribute(
                            attribItem[2],
                            FnAttribute.FloatAttribute(
                                float(attribItem[3].translate(None, 'f'))))
                    elif attribItem[1] == "double":
                        internalBuilder.addAttribute(
                            attribItem[2],
                            FnAttribute.DoubleAttribute(
                                float(attribItem[3].translate(None, 'f'))))
                elif attribItem[0] == 2:
                    # array item
                    itemDataType = attribItem[1]

                    if itemDataType == "int":
                        intArray = [
                            int(stringItem) for stringItem in attribItem[3]
                        ]
                        internalBuilder.addAttribute(
                            attribItem[2],
                            FnAttribute.IntAttribute(intArray, attribItem[4]))
                    elif itemDataType == "float" or itemDataType == "double":
                        floatArray = [
                            float(stringItem.translate(None, 'f'))
                            for stringItem in attribItem[3]
                        ]
                        # print floatArray
                        if itemDataType == "float":
                            internalBuilder.addAttribute(
                                attribItem[2],
                                FnAttribute.FloatAttribute(
                                    floatArray, attribItem[4]))
                        elif itemDataType == "double":
                            internalBuilder.addAttribute(
                                attribItem[2],
                                FnAttribute.DoubleAttribute(
                                    floatArray, attribItem[4]))

            interface.appendOp(internalBuilder.getOpName(),
                               internalBuilder.build())
예제 #16
0
from Katana import FnAttribute, Nodes3DAPI

nb = Nodes3DAPI.NodeTypeBuilder('TestOp')
nb.setInputPortNames(('in', ))

nb.setParametersTemplateAttr(FnAttribute.GroupBuilder().set(
    'argParent', FnAttribute.StringAttribute("father")).set(
        'argChild', FnAttribute.StringAttribute("son")).build())

nb.setHintsForNode({'help': 'Node hints here!!!'})
nb.setHintsForParameter('attrName', {'help': 'Arg hints here!!!'})


def myBuildOps(node, interface):
    op = interface.buildOp('testParentOp')

    if op.areParametersDirty():
        frameTime = interface.getFrameTime()

        op.setOpType('TestParentOp')
        op.setOpArg('argParent',
                    node.getParameter('argParent').getValue(frameTime))
        op.setOpArg('argChild',
                    node.getParameter('argChild').getValue(frameTime))

    if op.areInputsDirty():
        op.setOpInputs(interface.getAllInputOps())

    return op

예제 #17
0
    def generateMaterialAttributes(self, materialDefinition, materialStaticSCB,
                                   materialLocationPath,
                                   convertSpecRoughnessValues,
                                   enableCausticsInArnold):
        shaderNameItem = "imagineSurfaceShader"
        shaderParamsItem = "imagineSurfaceParams"

        materialStaticSCB.setAttrAtLocation(
            materialLocationPath, "material." + shaderNameItem,
            FnAttribute.StringAttribute("StandardImage"))

        attrLevelItemPath = "material." + shaderParamsItem + "."

        for matDefName, matDefItem in materialDefinition.iteritems():
            if matDefName == "diffColour":
                if matDefItem[0] == "col3":
                    materialStaticSCB.setAttrAtLocation(
                        materialLocationPath, attrLevelItemPath + "diff_col",
                        FnAttribute.FloatAttribute(matDefItem[1], 3))
                elif matDefItem[0] == "image":
                    materialStaticSCB.setAttrAtLocation(
                        materialLocationPath,
                        attrLevelItemPath + "diff_col_texture",
                        FnAttribute.StringAttribute(matDefItem[1]))
            elif matDefName == "diffRoughness":
                if matDefItem[0] == "float":
                    materialStaticSCB.setAttrAtLocation(
                        materialLocationPath,
                        attrLevelItemPath + "diff_roughness",
                        FnAttribute.FloatAttribute(matDefItem[1]))
                elif matDefItem[0] == "image":
                    materialStaticSCB.setAttrAtLocation(
                        materialLocationPath,
                        attrLevelItemPath + "diff_roughness_texture",
                        FnAttribute.StringAttribute(matDefItem[1]))
            elif matDefName == "refraIndex" and matDefItem[0] == "float":
                materialStaticSCB.setAttrAtLocation(
                    materialLocationPath,
                    attrLevelItemPath + "refraction_index",
                    FnAttribute.FloatAttribute(matDefItem[1]))
            elif matDefName == "specColour":
                # Arnold is always GGX, so we'll match that
                materialStaticSCB.setAttrAtLocation(
                    materialLocationPath,
                    attrLevelItemPath + "microfacet_type",
                    FnAttribute.StringAttribute("ggx"))
                if matDefItem[0] == "col3":
                    materialStaticSCB.setAttrAtLocation(
                        materialLocationPath, attrLevelItemPath + "spec_col",
                        FnAttribute.FloatAttribute(matDefItem[1], 3))
                elif matDefItem[0] == "image":
                    materialStaticSCB.setAttrAtLocation(
                        materialLocationPath,
                        attrLevelItemPath + "spec_col_texture",
                        FnAttribute.StringAttribute(matDefItem[1]))
            elif matDefName == "specRoughness":
                if matDefItem[0] == "float":
                    actualRoughnessValue = matDefItem[1]
                    if convertSpecRoughnessValues == 2:
                        actualRoughnessValue = self.adjustSpecRoughnessFromAlpha(
                            actualRoughnessValue)
                    materialStaticSCB.setAttrAtLocation(
                        materialLocationPath,
                        attrLevelItemPath + "spec_roughness",
                        FnAttribute.FloatAttribute(actualRoughnessValue))
                elif matDefItem[0] == "image":
                    materialStaticSCB.setAttrAtLocation(
                        materialLocationPath,
                        attrLevelItemPath + "spec_roughness_texture",
                        FnAttribute.StringAttribute(matDefItem[1]))
예제 #18
0
    def buildBgeoInOpChain(node, interface):
        """
        Defines the callback function used to create the Ops chain for the
        node type being registered.

        @type node: C{Nodes3DAPI.NodeTypeBuilder.BgeoIn}
        @type interface: C{Nodes3DAPI.NodeTypeBuilder.BuildChainInterface}
        @param node: The node for which to define the Ops chain
        @param interface: The interface providing the functions needed to set
            up the Ops chain for the given node.
        """
        # Get the current frame time
        frameTime = interface.getGraphState().getTime()

        # Set the minimum number of input ports
        interface.setMinRequiredInputs(0)

        argsGb = FnAttribute.GroupBuilder()

        # Parse node parameters
        locationParam = node.getParameter('location')
        fileNameParam = node.getParameter('fileName')
        makeFacesetsParam = node.getParameter('makeFacesets')
        reportEmptyParam = node.getParameter('reportEmpty')
        computeBoundParam = node.getParameter('computePointCloudBound')
        createSubdParam = node.getParameter('createSubd')
        checkVersionParam = node.getParameter('checkVersion')

        # resolve file path so that it can include frame number replacement
        # i.e. %04d
        filePath = fileNameParam.getValue(frameTime)
        fileSequencePlugin = AssetAPI.GetDefaultFileSequencePlugin()
        if fileSequencePlugin and fileSequencePlugin.isFileSequence(filePath):
            fileSequence = fileSequencePlugin.getFileSequence(filePath)
            resolvedPath = fileSequence.getResolvedPath(int(frameTime))
        else:
            resolvedPath = filePath

        argsGb.set('fileName', FnAttribute.StringAttribute(resolvedPath))
        argsGb.set(
            'makeFacesets',
            FnAttribute.IntAttribute(makeFacesetsParam.getValue(frameTime)))
        argsGb.set(
            'reportEmpty',
            FnAttribute.IntAttribute(reportEmptyParam.getValue(frameTime)))
        argsGb.set(
            'computePointCloudBound',
            FnAttribute.IntAttribute(computeBoundParam.getValue(frameTime)))
        argsGb.set(
            'createSubd',
            FnAttribute.IntAttribute(createSubdParam.getValue(frameTime)))
        argsGb.set(
            'checkVersion',
            FnAttribute.IntAttribute(checkVersionParam.getValue(frameTime)))

        # We want to use the StaticSceneCreate Op to build the parent
        # hierarchy, so that our op only has to worry about generating its
        # children. Its args are somewhat complex, but fortunately, there
        # is a helper class that makes it all much easier.

        rootLocation = locationParam.getValue(frameTime)

        sscb = FnGeolibServices.OpArgsBuilders.StaticSceneCreate()
        sscb.addSubOpAtLocation(rootLocation, 'BgeoIn', argsGb.build())

        interface.appendOp('StaticSceneCreate', sscb.build())
예제 #19
0
def registerMaterialDescribe():
    def buildMaterialDescribeOpChain(node, interface):
        interface.setMinRequiredInputs(0)

        baseLocationParam = node.getParameter('baseLocation')
        baseLocationString = baseLocationParam.getValue(0)

        materialNameParam = node.getParameter('materialName')
        materialNameString = materialNameParam.getValue(0)

        descriptionParam = node.getParameter('description')
        descriptionString = descriptionParam.getValue(0)

        specRoughnessValuesConversionTypeParam = node.getParameter(
            'specRoughnessValuesConversionType')
        specRoughnessValuesConversionTypeValue = specRoughnessValuesConversionTypeParam.getValue(
            0)

        enableCausticsInArnoldParam = node.getParameter(
            'enableCausticsInArnold')
        enableCausticsInArnoldValue = bool(
            enableCausticsInArnoldParam.getValue(0))

        materialDefinition = parseMaterialDescription(descriptionString)

        rendererListGroupParam = node.getParameter('rendererList')
        renderersToMakeMatsFor = []
        numRendererItems = rendererListGroupParam.getNumChildren()
        for i in range(0, numRendererItems):
            subItemParam = rendererListGroupParam.getChildByIndex(i)
            intValue = subItemParam.getValue(0)
            if intValue == 0:
                continue

            rendererName = MaterialPlugin.pluginsNameList[i]
            renderersToMakeMatsFor.append(rendererName)

            materialLocationPath = os.path.join(baseLocationString,
                                                rendererName,
                                                materialNameString)

            materialStaticSCB = FnGeolibServices.OpArgsBuilders.StaticSceneCreate(
            )
            materialStaticSCB.createEmptyLocation(materialLocationPath)
            materialStaticSCB.setAttrAtLocation(
                materialLocationPath, 'type',
                FnAttribute.StringAttribute('material'))

            # invoke the renderer material plugin to create its attributes on the location...
            pluginResult = MaterialPlugin.pluginsDict[rendererName]
            pluginInstance = pluginResult[2]
            # todo: use keyword / dict for all these options...
            pluginInstance.generateMaterialAttributes(
                materialDefinition, materialStaticSCB, materialLocationPath,
                specRoughnessValuesConversionTypeValue,
                enableCausticsInArnoldValue)

            interface.appendOp("StaticSceneCreate", materialStaticSCB.build())

    nodeTypeBuilder = Nodes3DAPI.NodeTypeBuilder('MaterialDescribe')

    # build params
    gb = FnAttribute.GroupBuilder()
    gb.set('baseLocation', FnAttribute.StringAttribute('/root/materials/'))
    gb.set('materialName', FnAttribute.StringAttribute('material1'))

    gb.set('description',
           FnAttribute.StringAttribute('diffColour = RGB(0.18);'))

    gb.set('specRoughnessValuesConversionType', FnAttribute.IntAttribute(1))

    # it's pretty annoying that this isn't an Arnold option, but...
    gb.set('enableCausticsInArnold', FnAttribute.IntAttribute(1))

    rendererListGb = FnAttribute.GroupBuilder()
    for pluginName in MaterialPlugin.pluginsNameList:
        rendererListGb.set(pluginName, FnAttribute.IntAttribute(1))
    gb.set('rendererList', rendererListGb.build())

    nodeTypeBuilder.setParametersTemplateAttr(gb.build())
    nodeTypeBuilder.setHintsForParameter('description',
                                         {'widget': 'scriptEditor'})

    nodeTypeBuilder.setHintsForParameter(
        'specRoughnessValuesConversionType', {
            'widget':
            'mapper',
            'options':
            'none - as raw value per renderer:0|convert to microfacet alpha:1|convert to sqr(roughness):2'
        })

    nodeTypeBuilder.setHintsForParameter('enableCausticsInArnold',
                                         {'widget': 'checkBox'})

    for pluginName in MaterialPlugin.pluginsNameList:
        nodeTypeBuilder.setHintsForParameter('rendererList.' + pluginName,
                                             {'widget': 'checkBox'})

    nodeTypeBuilder.setInputPortNames(('in', ))

    nodeTypeBuilder.setBuildOpChainFnc(buildMaterialDescribeOpChain)

    nodeTypeBuilder.build()
예제 #20
0
def registerViewerTagSet():
    """
    Registers a new node type using the NodeTypeBuilder utility class.
    """

    from Katana import Nodes3DAPI
    from Katana import FnAttribute

    def buildViewerTagSetOpChain(node, interface):
        """
        Defines the callback function used to define the Ops chain for the
        node type being registered.

        @type node: C{Nodes3DAPI.NodeTypeBuilder.Messer}
        @type interface: C{Nodes3DAPI.NodeTypeBuilder.BuildChainInterface}
        @param node: The node for which to define the Ops chain
        @param interface: The interface providing the functions needed to set
            up the Ops chain for the given node.
        """
        # Get the current frame time
        frameTime = interface.getGraphState().getTime()

        # Set the minimum number of input ports
        interface.setMinRequiredInputs(1)

        argsGb = FnAttribute.GroupBuilder()

        # Parse the CEL parameter
        celParam = node.getParameter('CEL')
        if celParam:
            argsGb.set('CEL', celParam.getValue(frameTime))

        # Parse the color parameter
        colorRParam = node.getParameter('color.red')
        if colorRParam:
            argsGb.set('color.red', colorRParam.getValue(frameTime))
        colorGParam = node.getParameter('color.green')
        if colorGParam:
            argsGb.set('color.green', colorGParam.getValue(frameTime))
        colorBParam = node.getParameter('color.blue')
        if colorBParam:
            argsGb.set('color.blue', colorBParam.getValue(frameTime))
        colorParam = node.getParameter('color')

        # Parse the pickable parameter
        pickableParam = node.getParameter('pickable')
        if pickableParam:
            argsGb.set(
                'pickable',
                FnAttribute.IntAttribute(pickableParam.getValue(frameTime)))

        # Add the Messer Op to the Ops chain
        interface.appendOp('ViewerTagSet', argsGb.build())

    # Create a NodeTypeBuilder to register the new type
    nodeTypeBuilder = Nodes3DAPI.NodeTypeBuilder('ViewerTagSet')

    # Add an input port
    nodeTypeBuilder.setInputPortNames(('in', ))

    # Build the node's parameters
    gb = FnAttribute.GroupBuilder()
    gb.set('CEL', FnAttribute.StringAttribute(''))
    colorb = FnAttribute.GroupBuilder()
    colorb.set('red', FnAttribute.FloatAttribute(0.0))
    colorb.set('green', FnAttribute.FloatAttribute(0.0))
    colorb.set('blue', FnAttribute.FloatAttribute(0.0))
    colorg = colorb.build()
    gb.set("color", colorg)
    gb.set('pickable', FnAttribute.IntAttribute(1))
    # Set the parameters template
    nodeTypeBuilder.setParametersTemplateAttr(gb.build())
    # Set parameter hints
    nodeTypeBuilder.setHintsForParameter('CEL', {'widget': 'cel'})
    nodeTypeBuilder.setHintsForParameter(
        'color.red', {'help': "set viewer.default.annotation.color.red value"})
    nodeTypeBuilder.setHintsForParameter(
        'color.green',
        {'help': "set viewer.default.annotation.color.green value"})
    nodeTypeBuilder.setHintsForParameter(
        'color.blue',
        {'help': "set viewer.default.annotation.color.blue value"})
    nodeTypeBuilder.setHintsForParameter(
        'pickable', {
            'widget': 'checkBox',
            'help': 'Whether you can select object in viewer'
        })

    # Set the callback responsible to build the Ops chain
    nodeTypeBuilder.setBuildOpChainFnc(buildViewerTagSetOpChain)

    # Build the new node type
    nodeTypeBuilder.build()
예제 #21
0
def registerBgeoIn():
    """
    Registers a new BgeoIn node type using the NodeTypeBuilder utility
    class.
    """

    from Katana import Nodes3DAPI
    from Katana import AssetAPI
    from Katana import FnAttribute
    from Katana import FnGeolibServices

    def buildBgeoInOpChain(node, interface):
        """
        Defines the callback function used to create the Ops chain for the
        node type being registered.

        @type node: C{Nodes3DAPI.NodeTypeBuilder.BgeoIn}
        @type interface: C{Nodes3DAPI.NodeTypeBuilder.BuildChainInterface}
        @param node: The node for which to define the Ops chain
        @param interface: The interface providing the functions needed to set
            up the Ops chain for the given node.
        """
        # Get the current frame time
        frameTime = interface.getGraphState().getTime()

        # Set the minimum number of input ports
        interface.setMinRequiredInputs(0)

        argsGb = FnAttribute.GroupBuilder()

        # Parse node parameters
        locationParam = node.getParameter('location')
        fileNameParam = node.getParameter('fileName')
        makeFacesetsParam = node.getParameter('makeFacesets')
        reportEmptyParam = node.getParameter('reportEmpty')
        computeBoundParam = node.getParameter('computePointCloudBound')
        createSubdParam = node.getParameter('createSubd')
        checkVersionParam = node.getParameter('checkVersion')

        # resolve file path so that it can include frame number replacement
        # i.e. %04d
        filePath = fileNameParam.getValue(frameTime)
        fileSequencePlugin = AssetAPI.GetDefaultFileSequencePlugin()
        if fileSequencePlugin and fileSequencePlugin.isFileSequence(filePath):
            fileSequence = fileSequencePlugin.getFileSequence(filePath)
            resolvedPath = fileSequence.getResolvedPath(int(frameTime))
        else:
            resolvedPath = filePath

        argsGb.set('fileName', FnAttribute.StringAttribute(resolvedPath))
        argsGb.set(
            'makeFacesets',
            FnAttribute.IntAttribute(makeFacesetsParam.getValue(frameTime)))
        argsGb.set(
            'reportEmpty',
            FnAttribute.IntAttribute(reportEmptyParam.getValue(frameTime)))
        argsGb.set(
            'computePointCloudBound',
            FnAttribute.IntAttribute(computeBoundParam.getValue(frameTime)))
        argsGb.set(
            'createSubd',
            FnAttribute.IntAttribute(createSubdParam.getValue(frameTime)))
        argsGb.set(
            'checkVersion',
            FnAttribute.IntAttribute(checkVersionParam.getValue(frameTime)))

        # We want to use the StaticSceneCreate Op to build the parent
        # hierarchy, so that our op only has to worry about generating its
        # children. Its args are somewhat complex, but fortunately, there
        # is a helper class that makes it all much easier.

        rootLocation = locationParam.getValue(frameTime)

        sscb = FnGeolibServices.OpArgsBuilders.StaticSceneCreate()
        sscb.addSubOpAtLocation(rootLocation, 'BgeoIn', argsGb.build())

        interface.appendOp('StaticSceneCreate', sscb.build())

    # Create a NodeTypeBuilder to register the new type
    nodeTypeBuilder = Nodes3DAPI.NodeTypeBuilder('BgeoIn')

    nodeTypeBuilder.setHintsForNode({'help': buildHelp("BgeoInHelp.txt")})

    # Build the node's parameters
    gb = FnAttribute.GroupBuilder()
    gb.set('location', FnAttribute.StringAttribute('/root/world/geo/BgeoIn'))
    gb.set('fileName', FnAttribute.StringAttribute(''))
    gb.set('makeFacesets', FnAttribute.IntAttribute(0))
    gb.set('reportEmpty', FnAttribute.IntAttribute(1))
    gb.set('computePointCloudBound', FnAttribute.IntAttribute(0))
    gb.set('createSubd', FnAttribute.IntAttribute(1))
    gb.set('checkVersion', FnAttribute.IntAttribute(1))

    # Set the parameters template
    nodeTypeBuilder.setParametersTemplateAttr(gb.build())

    # Set parameter hints
    nodeTypeBuilder.setHintsForParameter('location', {
        'label': 'Location',
        'widget': 'scenegraphLocation'
    })
    nodeTypeBuilder.setHintsForParameter('fileName', {
        'label': 'File Name',
        'widget': 'fileInput'
    })
    nodeTypeBuilder.setHintsForParameter(
        'makeFacesets', {
            'label': 'Make Facesets',
            'widget': 'checkBox',
            'help': 'Create facesets from primitive groups.'
        })
    nodeTypeBuilder.setHintsForParameter(
        'reportEmpty', {
            'label': 'Report Empty Geometry',
            'widget': 'checkBox',
            'help': 'Report empty BGEO files (i.e. no geometry) as an error.'
        })
    nodeTypeBuilder.setHintsForParameter(
        'computePointCloudBound', {
            'label':
            'Compute Point Cloud Bound',
            'widget':
            'checkBox',
            'help':
            'Compute the bound based on point P and width attributes, ' +
            'instead of using the embedded header bound. This will prevent ' +
            'points at the edges of the bound from be clipped. Enabling this '
            + 'option prevents deferred loading of the BGEO file.'
        })
    nodeTypeBuilder.setHintsForParameter(
        'createSubd', {
            'label': 'Create Subdivision Surfaces',
            'widget': 'checkBox',
            'help': 'Create subdivision surfaces for polymesh primitives.'
        })
    nodeTypeBuilder.setHintsForParameter(
        'checkVersion', {
            'label':
            'Check Version',
            'widget':
            'checkBox',
            'help':
            'Verify the version in the bgeo file is compatible. ' +
            'Turn this off if you know the file is compatible regardless of ' +
            'the version it was written out from, i.e. from use of ' +
            'HOUDINIX_Y_GEO_COMPATIBILITY environment variables.'
        })

    # Set the callback responsible to build the Ops chain
    nodeTypeBuilder.setBuildOpChainFnc(buildBgeoInOpChain)

    # Build the new node type
    nodeTypeBuilder.build()
예제 #22
0
파일: PxrUsdIn.py 프로젝트: zxwzxw/USD
      When using <i>expanded</i> USD instances will be unrolled as though
      the children of their masters were naturally present.
      </p>
      When using <i>as sources and instances</i>, masters will be created
      under a sibling of World named /Masters. Instanced USD prims will
      be of type "instance" and have no children.
    """,
        'conditionalVisOps': _offForArchiveCondVis,
    })

gb.set('usePurposeBasedMaterialBinding', 0)
nb.setHintsForParameter('usePurposeBasedMaterialBinding', {
    'widget': 'boolean',
})

gb.set('additionalBindingPurposeNames', FnAttribute.StringAttribute([], 1))

nb.setHintsForParameter(
    'additionalBindingPurposeNames', {
        'widget': 'sortableArray',
        'conditionalVisOp': 'notEqualTo',
        'conditionalVisPath': '../usePurposeBasedMaterialBinding',
        'conditionalVisValue': '',
    })

gb.set('prePopulate', FnAttribute.IntAttribute(1))
nb.setHintsForParameter(
    'prePopulate', {
        'widget': 'checkBox',
        'help': """
      Controls USD pre-population.  Pre-population loads all payloads
예제 #23
0
def registerMesser():
    """
    Registers a new Messer node type using the nb utility class.
    """
    import sys
    print sys.path
    from Katana import Nodes3DAPI, NodegraphAPI
    from Katana import FnAttribute
    import NodegraphAPI.Constants.ApplyWhenOptions as ApplyWhenOptions
    import NodegraphAPI.Constants.ApplyWhereOptions as ApplyWhereOptions
    import NodegraphAPI.Constants.ExecutionModeOptions as ExecutionModeOptions
    from Katana import FnGeolibServices

    def _DoInputRequests(interface, inputBehavior, inputPorts, graphState):
        interface.setExplicitInputRequestsEnabled(True)
        if inputBehavior == 'only valid':
            state = interface.SKIP
        else:
            state = interface.NO_OP
        for inputPort in inputPorts:
            interface.addInputRequest(inputPort.getName(),
                                      graphState,
                                      invalidInputBehavior=state)

    def buildMesserOpChain(node, interface):
        """
        Defines the callback function used to define the Ops chain for the
        node type being registered.

        @type node: C{Nodes3DAPI.nb.Messer}
        @type interface: C{Nodes3DAPI.nb.BuildChainInterface}
        @param node: The node for which to define the Ops chain
        @param interface: The interface providing the functions needed to set
            up the Ops chain for the given node.
        """
        # Get the current frame time
        # Set the minimum number of input ports
        interface.setMinRequiredInputs(1)

        graphState = interface.getGraphState()
        frameTime = graphState.getTime()

        argsGb = FnAttribute.GroupBuilder()
        argsGb.set('system', graphState.getOpSystemArgs())

        argsGb.set('inputIndex', FnAttribute.FloatAttribute(1))
        # Parse the CEL parameter
        celParam = node.getParameter('CEL')
        if celParam:
            argsGb.set('CEL', celParam.getValue(frameTime))

        userParam = node.getParameter('user')
        if userParam:
            userAttr = NodegraphAPI.BuildAttrFromGroupParameter(
                userParam, graphState)
            if userAttr is not None:
                argsGb.set('user', userAttr)

        # Parse the script parameter
        scriptParam = node.getParameter('script')
        if scriptParam:
            argsGb.set('script', scriptParam.getValue(frameTime))

        # xform
        transformParam = node.getParameter('transform')
        if transformParam:
            transformAttr = NodegraphAPI.BuildAttrFromGroupParameter(
                transformParam, graphState)
            if transformAttr is not None:
                argsGb.set('transform', transformAttr)

        opArgs = argsGb.build()
        if opArgs is not None:
            argsGb.deepUpdate(opArgs)

        opType = 'CartesianScript'
        #executionMode = node.getParameter('executionMode').getValue(frameTime)
        #if executionMode == ExecutionModeOptions.Immediate:
        #gb = FnAttribute.GroupBuilder()
        #gb.set('system', graphState.getOpSystemArgs())
        #if opArgs is not None:
        #    gb.deepUpdate(opArgs)
        #opArgs = gb.build()
        #asb = FnGeolibServices.OpArgsBuilders.AttributeSet()
        #asb.setCEL(FnAttribute.StringAttribute(node.getParameter('CEL').getValue(frameTime)))
        #asb.addSubOp(opType, opArgs)
        #interface.appendOp('AttributeSet', asb.build())
        #_DoInputRequests(interface, node.getParameter('inputBehavior').getValue(frameTime), node.getInputPorts(), graphState)
        # Add the explicit input request for our input port with the modified graph state
        # Add a variable to the local graph state
        #interface.setExplicitInputRequestsEnabled(True)
        #interface.addInputRequest('i0', graphState)
        #interface.addInputRequest('i1', graphState)

        # Add the Messer Op to the Ops chain
        interface.appendOp('CartesianScript', argsGb.build())

    # Create a nb to register the new type
    nb = Nodes3DAPI.NodeTypeBuilder('CartesianScript')

    print dir(nb)
    # Add an input port
    nb.setInputPortNames((
        'i0',
        'i1',
    ))
    nb.setOutputPortNames(('out', ))

    # Build the node's parameters
    gb = FnAttribute.GroupBuilder()
    gb.set('CEL', FnAttribute.StringAttribute(''))
    gb.set('script', FnAttribute.StringAttribute('print(Time)'))
    gb.set('executionMode', FnAttribute.StringAttribute('immediate'))
    gb.set('inputBehavior', FnAttribute.StringAttribute('by index'))
    nb.addTransformParameters(gb)
    nb.addMakeInteractiveParameter(gb)
    nb.addTimingParameters(gb)
    #gb.set('transform.rotate', FnAttribute.DoubleAttribute([0,0,0]))
    #gb.set('transform.scale', FnAttribute.DoubleAttribute([0,0,0]))
    # Set the parameters template
    nb.setParametersTemplateAttr(gb.build())
    # Set parameter hints
    nb.setHintsForParameter('CartesianScript', {'widget': 'opScriptNode'})
    nb.setHintsForParameter('CEL', {'widget': 'cel'})
    nb.setHintsForParameter(
        'script', {
            'widget': 'scriptEditor',
            'highlighter': 'Lua',
            'supportsNonmodalExternalEditing': 'True',
            'resistLabelResize': 'True',
            'externalEditorSuffix': '.lua',
            'mono': 'True'
        })
    nb.setHintsForParameter(
        'executionMode', {
            'widget':
            'popup',
            'options':
            [ExecutionModeOptions.Immediate, ExecutionModeOptions.Deferred]
        })
    nb.setHintsForParameter('inputBehavior', {
        'widget': 'popup',
        'options': ['by index', 'only valid']
    })
    # Set the callback responsible to build the Ops chain
    nb.setBuildOpChainFnc(buildMesserOpChain)
    # Build the new node type
    nb.build()
예제 #24
0
파일: PxrUsdIn.py 프로젝트: zxwzxw/USD
def buildPxrUsdInOpArgsAtGraphState(self, graphState):
    gb = FnAttribute.GroupBuilder()

    frameTime = graphState.getTime()

    gb.set('fileName', self.getParameter('fileName').getValue(frameTime))
    gb.set('location', self.getParameter('location').getValue(frameTime))

    gb.set('isolatePath', self.getParameter('isolatePath').getValue(frameTime))

    gb.set('variants', self.getParameter('variants').getValue(frameTime))

    gb.set('ignoreLayerRegex',
           self.getParameter('ignoreLayerRegex').getValue(frameTime))

    gb.set('motionSampleTimes',
           self.getParameter('motionSampleTimes').getValue(frameTime))

    gb.set('verbose', int(self.getParameter('verbose').getValue(frameTime)))

    gb.set('instanceMode',
           self.getParameter('instanceMode').getValue(frameTime))

    gb.set('prePopulate',
           int(self.getParameter('prePopulate').getValue(frameTime)))

    if self.getParameter('usePurposeBasedMaterialBinding').getValue(frameTime):
        purposes = [
            "",
        ]

        for p in self.getParameter(
                'additionalBindingPurposeNames').getChildren():
            v = p.getValue(frameTime).strip()
            if v:
                purposes.append(v)

        gb.set('materialBindingPurposes',
               FnAttribute.StringAttribute(purposes, 1))

    sessionValues = (graphState.getDynamicEntry("var:pxrUsdInSession"))
    if isinstance(sessionValues, FnAttribute.GroupAttribute):
        gb.set('session', sessionValues)

    gb.set('system', graphState.getOpSystemArgs())
    gb.set('processStageWideQueries', FnAttribute.IntAttribute(1))

    gb.set('setOpArgsToInfo', FnAttribute.IntAttribute(1))

    # check for any extra attributes or namespaces set downstream
    # via graph state
    extra = graphState.getDynamicEntry('var:usdExtraAttributesOrNamespaces')
    if extra:
        gb.set('extraAttributesOrNamespaces', extra)

    argsOverride = graphState.getDynamicEntry('var:pxrUsdInArgs')
    if isinstance(argsOverride, FnAttribute.GroupAttribute):
        gb.update(argsOverride)

    pxrUsdInArgs = gb.build()

    return pxrUsdInArgs
def registerGeoScaler():
    """
    Registers a new GeoScaler node type using the NodeTypeBuilder utility
    class.
    """

    from Katana import Nodes3DAPI
    from Katana import FnAttribute

    def buildGeoScalerOpChain(node, interface):
        """
        Defines the callback function used to create the Ops chain for the
        node type being registered.

        @type node: C{Nodes3DAPI.NodeTypeBuilder.GeoScaler}
        @type interface: C{Nodes3DAPI.NodeTypeBuilder.BuildChainInterface}
        @param node: The node for which to define the Ops chain
        @param interface: The interface providing the functions needed to set
            up the Ops chain for the given node.
        """
        # Get the current frame time
        frameTime = interface.getGraphState().getTime()

        # Set the minimum number of input ports
        interface.setMinRequiredInputs(1)

        argsGb = FnAttribute.GroupBuilder()

        # Parse node parameters
        CELParam = node.getParameter("CEL")
        if CELParam:
            CEL = CELParam.getValue(frameTime)
            argsGb.set("CEL", CEL)

        scaleParam = node.getParameter('scale')
        if scaleParam:
            scale = scaleParam.getValue(frameTime)
            argsGb.set("scale", scale)

        # Add the GeoScaler Op to the Ops chain
        interface.appendOp('GeoScaler', argsGb.build())

    # Create a NodeTypeBuilder to register the new type
    nodeTypeBuilder = Nodes3DAPI.NodeTypeBuilder('GeoScaler')

    # Add input port
    nodeTypeBuilder.setInputPortNames(("in",))

    # Build the node's parameters
    gb = FnAttribute.GroupBuilder()
    gb.set('CEL', FnAttribute.StringAttribute(''))
    gb.set('scale', FnAttribute.FloatAttribute(1.0))

    # Set the parameters template
    nodeTypeBuilder.setParametersTemplateAttr(gb.build())

    # Set parameter hints
    nodeTypeBuilder.setHintsForParameter('CEL', {'widget': 'scenegraphLocation'})

    # Set the callback responsible to build the Ops chain
    nodeTypeBuilder.setBuildOpChainFnc(buildGeoScalerOpChain)

    # Build the new node type
    nodeTypeBuilder.build()
예제 #26
0
 def __init__(self, locationPath, locationType):
     self.locationPath = locationPath
     self.locationType = locationType
     self.attribSet = FnGeolibServices.OpArgsBuilders.AttributeSet()
     self.attribSet.setCEL(FnAttribute.StringAttribute(self.locationPath))
예제 #27
0
def registerSphereMaker():
    """
    Registers a new SphereMaker node type using the NodeTypeBuilder utility
    class.
    """

    from Katana import Nodes3DAPI
    from Katana import FnAttribute

    def buildSphereMakerOpChain(node, interface):
        """
        Defines the callback function used to create the Ops chain for the
        node type being registered.

        @type node: C{Nodes3DAPI.NodeTypeBuilder.SphereMaker}
        @type interface: C{Nodes3DAPI.NodeTypeBuilder.BuildChainInterface}
        @param node: The node for which to define the Ops chain
        @param interface: The interface providing the functions needed to set
            up the Ops chain for the given node.
        """
        # Get the current frame time
        frameTime = interface.getGraphState().getTime()

        # Set the minimum number of input ports
        interface.setMinRequiredInputs(0)

        argsGb = FnAttribute.GroupBuilder()

        # Parse node parameters
        locationParam = node.getParameter('location')
        numberOfSpheresParam = node.getParameter('numberOfSpheres')
        if locationParam:
            location = locationParam.getValue(frameTime)

            # The base location is encoded using nested group attributes
            # defining a hierarchy where the elements in the location paths
            # are interleaved with group attributes named 'c' (for child).
            # The last element will contain a group attribute, named 'a',
            # which in turn will hold an attribute defining the number of
            # spheres to be generated.
            # See the Op source code for more details
            locationPaths = location[1:].split('/')[1:]
            attrsHierarchy = 'c.' + '.c.'.join(locationPaths)
            argsGb.set(
                attrsHierarchy + '.a.numberOfSpheres',
                FnAttribute.IntAttribute(
                    numberOfSpheresParam.getValue(frameTime)))

        # Add the SphereMaker Op to the Ops chain
        interface.appendOp('SphereMaker', argsGb.build())

    # Create a NodeTypeBuilder to register the new type
    nodeTypeBuilder = Nodes3DAPI.NodeTypeBuilder('SphereMaker')

    # Build the node's parameters
    gb = FnAttribute.GroupBuilder()
    gb.set('location',
           FnAttribute.StringAttribute('/root/world/geo/SphereMaker'))
    gb.set('numberOfSpheres', FnAttribute.IntAttribute(20))

    # Set the parameters template
    nodeTypeBuilder.setParametersTemplateAttr(gb.build())

    # Set parameter hints
    nodeTypeBuilder.setHintsForParameter('location',
                                         {'widget': 'scenegraphLocation'})
    nodeTypeBuilder.setHintsForParameter('numberOfSpheres', {'int': True})

    # Set the callback responsible to build the Ops chain
    nodeTypeBuilder.setBuildOpChainFnc(buildSphereMakerOpChain)

    # Build the new node type
    nodeTypeBuilder.build()
예제 #28
0
def registerLocationDescribe():
    def buildLocationDescribeOpChain(node, interface):
        interface.setMinRequiredInputs(0)

        locationParam = node.getParameter('location')
        if not locationParam:
            # set an error
            staticSCB = FnGeolibServices.OpArgsBuilders.StaticSceneCreate()
            staticSCB.createEmptyLocation('/root/world/geo/')
            staticSCB.setAttrAtLocation(
                '/root/world/', 'errorMessage',
                FnAttribute.StringAttribute(
                    'Invalid location used for LocationDescribe'))
            interface.appendOp('StaticSceneCreate', staticSCB.build())
        else:
            # do the actual work creating location and attributes
            locationPath = locationParam.getValue(0)

            modeParam = node.getParameter('mode')
            modeParamValue = modeParam.getValue(0)
            descriptionParam = node.getParameter('description')
            typeParam = node.getParameter('type')
            typeParamValue = typeParam.getValue(0)

            interface.setMinRequiredInputs(0 if modeParamValue ==
                                           "create" else 1)

            internalBuilder = InternalBuilderSSC(
                locationPath, typeParamValue
            ) if modeParamValue == "create" else InternalBuilderAS(
                locationPath, typeParamValue)

            descriptionString = descriptionParam.getValue(0)
            attributeItems = parseDescription(descriptionString)

            for attribItem in attributeItems:
                if attribItem[0] == 1:
                    # single item
                    if attribItem[1] == "int":
                        internalBuilder.addAttribute(
                            attribItem[2],
                            FnAttribute.IntAttribute(int(attribItem[3])))
                    elif attribItem[1] == "string":
                        internalBuilder.addAttribute(
                            attribItem[2],
                            FnAttribute.StringAttribute(attribItem[3]))
                    elif attribItem[1] == "float":
                        internalBuilder.addAttribute(
                            attribItem[2],
                            FnAttribute.FloatAttribute(
                                float(attribItem[3].translate(None, 'f'))))
                    elif attribItem[1] == "double":
                        internalBuilder.addAttribute(
                            attribItem[2],
                            FnAttribute.DoubleAttribute(
                                float(attribItem[3].translate(None, 'f'))))
                elif attribItem[0] == 2:
                    # array item
                    itemDataType = attribItem[1]

                    if itemDataType == "int":
                        intArray = [
                            int(stringItem) for stringItem in attribItem[3]
                        ]
                        internalBuilder.addAttribute(
                            attribItem[2],
                            FnAttribute.IntAttribute(intArray, attribItem[4]))
                    elif itemDataType == "float" or itemDataType == "double":
                        floatArray = [
                            float(stringItem.translate(None, 'f'))
                            for stringItem in attribItem[3]
                        ]
                        # print floatArray
                        if itemDataType == "float":
                            internalBuilder.addAttribute(
                                attribItem[2],
                                FnAttribute.FloatAttribute(
                                    floatArray, attribItem[4]))
                        elif itemDataType == "double":
                            internalBuilder.addAttribute(
                                attribItem[2],
                                FnAttribute.DoubleAttribute(
                                    floatArray, attribItem[4]))

            interface.appendOp(internalBuilder.getOpName(),
                               internalBuilder.build())

    nodeTypeBuilder = Nodes3DAPI.NodeTypeBuilder('LocationDescribe')

    # build params
    gb = FnAttribute.GroupBuilder()
    gb.set('location',
           FnAttribute.StringAttribute('/root/world/geo/location1'))
    gb.set('mode', FnAttribute.StringAttribute('create'))
    gb.set('type', FnAttribute.StringAttribute('sphere'))
    gb.set('description',
           FnAttribute.StringAttribute('double geometry.radius = 1.0;'))

    nodeTypeBuilder.setParametersTemplateAttr(gb.build())
    nodeTypeBuilder.setHintsForParameter('mode', {
        'widget': 'popup',
        'options': 'create|edit'
    })
    nodeTypeBuilder.setHintsForParameter('description',
                                         {'widget': 'scriptEditor'})

    nodeTypeBuilder.setInputPortNames(('in', ))

    nodeTypeBuilder.setBuildOpChainFnc(buildLocationDescribeOpChain)

    nodeTypeBuilder.build()
예제 #29
0
requiredAttrs.set("material.resolveInViewer", FnAttribute.IntAttribute(1))
requiredAttrs.set("material.lightShader", FnAttribute.NullAttribute())
requiredAttrs.set("material.viewerSurfaceShader", FnAttribute.NullAttribute())
requiredAttrs.set("material.parameters", FnAttribute.NullAttribute())
requiredAttrs.set("material.reference", FnAttribute.NullAttribute())

# Get the names of all known renderer plug-ins for light shaders
rendererPluginNames = RenderingAPI.RenderPlugins.GetRendererPluginNames()
for rendererPluginName in rendererPluginNames:
    requiredAttrs.set("material.%sLightShader" % rendererPluginName,
                      FnAttribute.NullAttribute())

#-------------------------------------------------------------------------------
# Match by value - Specify attributes whose value must also match those provided
#-------------------------------------------------------------------------------
requiredAttrs.set("material.style", FnAttribute.StringAttribute("network"))
requiredAttrs.set("viewer.default.resolveMaterialInViewer",
                  FnAttribute.StringAttribute("always"))

#-------------------------------------------------------------------------------
# Generate Op args
#-------------------------------------------------------------------------------
opArgsBuilder = FnAttribute.GroupBuilder()
opArgsBuilder.set("locationPaths", FnAttribute.StringAttribute('/root/world'))
opArgsBuilder.set('setAttrs.i0.name',
                  FnAttribute.StringAttribute("viewer.materialResolveAttrs"))
opArgsBuilder.set('setAttrs.i0.attr', requiredAttrs.build())
opArgsBuilder.set('setAttrs.i0.inherit', FnAttribute.IntAttribute(0))

# Register this op with the viewer implicit resolvers
Nodes3DAPI.RegisterImplicitResolver(
예제 #30
0
nb.setNodeTypeVersion(2)
nb.setNodeTypeVersionUpdateFnc(2, pxrUsdInUpgradeToVersionTwo)

nb.build()

#-----------------------------------------------------------------------------

nb = Nodes3DAPI.NodeTypeBuilder('PxrUsdInVariantSelect')
nb.setInputPortNames(("in", ))

nb.setParametersTemplateAttr(FnAttribute.GroupBuilder().set(
    'location',
    '').set('args.variantSetName',
            '').set('args.variantSelection',
                    '').set('additionalLocations',
                            FnAttribute.StringAttribute([])).build())

nb.setHintsForParameter('location', {
    'widget': 'scenegraphLocation',
})

nb.setHintsForParameter('additionalLocations', {
    'widget': 'scenegraphLocationArray',
})

nb.setGenericAssignRoots('args', '__variantUI')


def buildOpChain(self, interface):
    interface.setExplicitInputRequestsEnabled(True)