Example #1
0
def BatScriptRenderFull():
    # Save Script
    nuke.scriptSave()
    # Variables of Script
    nukescript = nuke.value("root.name")
    start = nuke.knob("first_frame")
    end = nuke.knob("last_frame")
    path = nukescript + ".bat"
    # Cmd Message
    nuke.tprint("\nBatScriptRender\nSave Script " + nukescript)
    # Bat File Panel
    swt = ['-x', '-X']
    nfr = ['""', ',2', ',5', ',10', ',15', ',20']
    myPanel = nuke.Panel("BatScriptRender - Parameters", 338)
    myPanel.addSingleLineInput("nuke version: ", "nuke5.1")
    myPanel.addEnumerationPulldown("switches: ", ' '.join(swt))
    myPanel.addSingleLineInput("node: ", "")
    myPanel.addSingleLineInput("script: ", nukescript)
    myPanel.addSingleLineInput("start frame: ", start)
    myPanel.addSingleLineInput("end frame: ", end)
    myPanel.addEnumerationPulldown("every n frame: ", ' '.join(nfr))
    myPanel.addSingleLineInput("file path: ", path)
    myPanel.addButton("Quit")
    myPanel.addButton("Create")
    myPanel.addButton("Execute")
    result = myPanel.show()
    # Add Button's action & Cmd Message
    if result == 0:
        nuke.tprint("Bat File don't Create")
    elif result == 1:
        # Create Bat File
        curVersion = myPanel.value("nuke version: ")
        curSwitches = myPanel.value("switches: ")
        curNode = myPanel.value("node: ")
        curScript = myPanel.value("script: ")
        curStart = myPanel.value("start frame: ")
        curEnd = myPanel.value("end frame: ")
        curEvery = myPanel.value("every n frame: ")
        cmdLine = curVersion + " " + curSwitches + " " + curNode + " " + '"' + curScript + '"' + " " + curStart + "," + curEnd + curEvery
        cmdFile = myPanel.value("file path: ")
        file = open(cmdFile, 'w')
        file.write(cmdLine)
        file.close()
        nuke.tprint("Create Bat File " + cmdFile)
    elif result == 2:
        # Execute Bat File
        curVersion = myPanel.value("nuke version: ")
        curSwitches = myPanel.value("switches: ")
        curNode = myPanel.value("node: ")
        curScript = myPanel.value("script: ")
        curStart = myPanel.value("start frame: ")
        curEnd = myPanel.value("end frame: ")
        curEvery = myPanel.value("every n frame: ")
        cmdLine = curVersion + " " + curSwitches + " " + curNode + " " + '"' + curScript + '"' + " " + curStart + "," + curEnd + curEvery
        cmdFile = myPanel.value("file path: ")
        file = open(cmdFile, 'w')
        file.write(cmdLine)
        file.close()
        os.startfile(cmdFile)
        nuke.tprint("Execute Bat File " + cmdFile)
Example #2
0
    def test_use_relative_path(self):
        from edit import use_relative_path

        nuke.knob('root.project_directory', 'A:/test/')
        n = nuke.nodes.Read(file=b'A:/test/sc01/testfile测试.mov')
        use_relative_path(n)
        self.assertEqual(n['file'].value(), b'sc01/testfile测试.mov')
Example #3
0
def buildScene(): # Assemble NK scene
    dataShotDic = buildShotDic() 
    exrPath = dataShotDic['EXR']
    endFrame = dataShotDic['endFrame']
    
    # Define Pathes for  Write Nodes
    exrPathFull = '{0}{1}/{2}/SHOT_{3}/MASTER/{4}'.format(root3D, codePart, codeSequence, codeShot, exrPath)
    dpxPathFull = '{3}{4}/{0}/{1}/SHOT_{2}/v{5}/E{1}_S{2}_v{5}.%04d.dpx'.format(codePart, codeSequence, codeShot, rootRND, 'DPX', '[knob VERSION.label]')
    movPathFull = '{3}{4}/{0}/{1}/SHOT_{2}/E{1}_S{2}_v{5}.mov'.format(codePart, codeSequence, codeShot, rootRND, 'MOV','[knob VERSION.label]' )
    nameBase = 'E{0}_S{1}'.format(codeSequence, codeShot)
    reader = nuke.nodes.Read(name = 'REA_E{0}_S{1}'.format(codeSequence, codeShot), file = exrPathFull, first = 101, last = endFrame, xpos = 0, ypos = 0) #creating Reader Node

    dot_A = nuke.nodes.Dot(name = 'DOT', xpos = 34, ypos = 250)
    dot_A.setInput(0, reader)
    dot_B = nuke.nodes.Dot(name = 'DOT', xpos = 184, ypos = 250)
    dot_B.setInput(0, dot_A)

    verser = nuke.nodes.StickyNote(name = "VERSION", xpos = 0, ypos = 380) # Node to DRIVE VESIONS of Nuke renders
    verser['label'].setValue('001')
    # Create WRITE nodes
    writeDPX = nuke.nodes.Write( name ='DPX_E{0}_S{1}'.format(codeSequence, codeShot),file = dpxPathFull, file_type = 'dpx', colorspace='Cineon', first = 101, last = endFrame, xpos = 0, ypos = 300)
    writeDPX.setInput(0, dot_A)
    writeDPX['beforeRender'].setValue("if not os.path.isdir(os.path.dirname(nuke.thisNode()['file'].evaluate())):os.makedirs(os.path.dirname(nuke.thisNode()['file'].evaluate()))") # Create folder for writer output, if its not exists
    writeMOV = nuke.nodes.Write( name ='MOV_E{0}_S{1}'.format(codeSequence, codeShot),file = movPathFull, file_type = 'dpx', colorspace='sRGB', first = 101, last = endFrame, xpos = 150, ypos = 300)
    writeMOV.setInput(0, dot_B)
    writeMOV['beforeRender'].setValue("if not os.path.isdir(os.path.dirname(nuke.thisNode()['file'].evaluate())):os.makedirs(os.path.dirname(nuke.thisNode()['file'].evaluate()))") # Create folder for writer output, if its not exists
    # Setup NK scene
    view = nuke.toNode('Viewer1')
    view['xpos'].setValue( -140 )
    view['ypos'].setValue( 30 )
    nuke.knob('root.first_frame', str(frameStart) )
    nuke.knob('root.last_frame', endFrame)
    nuke.connectViewer(0, reader)
Example #4
0
    def setup(self):
        """Add tag knob to read nodes, then set project framerange."""

        if not nuke.value('root.project_directory'):
            nuke.knob(
                "root.project_directory", r"[python {os.path.join("
                r"nuke.value('root.name', ''), '../'"
                r").replace('\\', '/')}]")

        nodes = nuke.allNodes('Read')
        if not nodes:
            raise FootageError('没有读取节点')

        n = None
        root_format = None
        root = nuke.Root()
        first = None
        last = None
        formats = []

        for n in nodes:
            ReadNode(n)
            format_ = n.format()
            assert isinstance(format_, nuke.Format)
            if not n.hasError():
                formats.append((format_.width(), format_.height()))
            n_first, n_last = n.firstFrame(), n.lastFrame()

            # Ignore single frame.
            if n_first == n_last:
                continue

            # Expand frame range.
            if first is None:
                first = n_first
                last = n_last
            else:
                first = min(last, n.firstFrame())
                last = max(last, n.lastFrame())

        if first is None:
            first = last = 1

        root_format = root_format or n.format()

        root['first_frame'].setValue(first)
        root['last_frame'].setValue(last)
        nuke.frame((first + last) / 2)
        root['lock_range'].setValue(True)
        try:
            format_ = sorted([(formats.count(i), i)
                              for i in set(formats)])[-1][1]
            root['format'].setValue(nuke.addFormat('{} {}'.format(*format_)))
        except IndexError:
            root['format'].setValue('HD_1080')
            LOGGER.warning('不能获取工程格式, 使用默认值HD_1080')

        root['fps'].setValue(self.fps)
Example #5
0
    def _create_deep_read_node(self, path, sg_publish_data):
        """
        Create a read node representing the publish.

        :param path: Path to file.
        :param sg_publish_data: Shotgun data dictionary with all the standard publish fields.
        """
        import nuke

        (_, ext) = os.path.splitext(path)

        # deep files should only be EXRs
        valid_extensions = [".exr"]

        if ext.lower() not in valid_extensions:
            raise Exception("Unsupported file extension for '%s'!" % path)

        # `nuke.createNode()` will extract the format from the
        # file itself (if possible), whereas `nuke.nodes.Read()` won't. We'll
        # also check to see if there's a matching template and override the
        # frame range, but this should handle the zero config case. This will
        # also automatically extract the format and frame range for movie files.
        read_node = nuke.createNode("DeepRead")
        # this detects frame range automatically only if it is explicitly passed
        # (i.e. if the argument to fromUserText() is of the format
        # "<img_seq_path> <start>-<end>")
        read_node["file"].fromUserText(path)

        # find the sequence range if it has one:
        seq_range = self._find_sequence_range(path)

        # to fetch the nuke prefs from pipeline
        step = self._find_pipe_step(path, sg_publish_data)
        nuke_prefs = NukePreferences(step)

        for knob_name, knob_value in nuke_prefs.getKnobOverridesGenerator(
                step):
            if read_node.Class() in knob_name:
                knob_name = knob_name.replace(read_node.Class(),
                                              read_node.name())
                nuke.knob(knob_name, knob_value)

        if seq_range:
            # override the detected frame range.
            read_node["first"].setValue(seq_range[0])
            read_node["last"].setValue(seq_range[1])
        else:
            self.parent.logger.warning("{}: Not setting frame range.".format(
                read_node.name()))

        # try to fetch a proxy path using templates
        proxy_path = self._get_proxy_path(path)

        if proxy_path:
            read_node["proxy"].fromUserText(proxy_path)
        else:
            self.parent.logger.warning("{}: Not setting proxy path.".format(
                read_node.name()))
Example #6
0
def set_f_range():
    asset = asset_core.string_to_asset(os.environ[defaults._asset_var_])
    f_range = prefs.asset(asset).name.range
    for n in nuke.allNodes('Read'):
        n['first'].setValue(f_range[0])
        n['last'].setValue(f_range[1])
        n['origfirst'].setValue(f_range[0])
        n['origlast'].setValue(f_range[1])
    nuke.knob("root.first_frame", str(f_range[0]))
    nuke.knob("root.last_frame", str(f_range[1]))
Example #7
0
 def set_indicators(self):
     # this function is copied from Foundry's autolabel.py and
     # is copyright Foundry, all rights reserved
     # seemingly more or less need to use this TCL code, as there doesn't
     # seem to be python equivalents for these functions
     ind = nuke.expression(
         "(keys?1:0)+(has_expression?2:0)+(clones?8:0)+(viewsplit?32:0)")
     if int(nuke.numvalue("maskChannelInput", 0)):
         ind += 4
     if int(nuke.numvalue("this.mix", 1)) < 1:
         ind += 16
     nuke.knob("this.indicators", str(ind))
Example #8
0
    def _create_read_node(self, path, sg_publish_data):
        """
        Create a read node representing the publish.
        
        :param path: Path to file.
        :param sg_publish_data: Shotgun data dictionary with all the standard publish fields.        
        """
        import nuke

        (_, ext) = os.path.splitext(path)

        # If this is an Alembic cache, use a ReadGeo2 and we're done.
        if ext.lower() == '.abc' or ext.lower() == '.obj':
            read_geo = nuke.createNode('ReadGeo2')
            read_geo.knob('file').setValue(path)
            return

        valid_extensions = [
            ".png", ".jpg", ".jpeg", ".exr", ".cin", ".dpx", ".tiff", ".tif",
            ".mov", ".psd", ".tga", ".ari", ".gif", ".iff"
        ]

        if ext.lower() not in valid_extensions:
            raise Exception("Unsupported file extension for '%s'!" % path)

        # `nuke.createNode()` will extract the format and frame range from the
        # file itself (if possible), whereas `nuke.nodes.Read()` won't. We'll
        # also check to see if there's a matching template and override the
        # frame range, but this should handle the zero config case. This will
        # also automatically extract the format and frame range for movie files.
        read_node = nuke.createNode("Read")
        read_node["file"].fromUserText(path)

        # find the sequence range if it has one:

        seq_range = self._find_sequence_range(path, sg_publish_data)

        # to fetch the nuke prefs from pipeline
        nuke_prefs = NukePreferences()

        for knob_name, knob_value in nuke_prefs.getKnobOverridesGenerator(
                self._find_pipe_step(path, sg_publish_data)):
            if read_node.Class() in knob_name:
                knob_name = knob_name.replace(read_node.Class(),
                                              read_node.name())
                nuke.knob(knob_name, knob_value)

        if seq_range:
            # override the detected frame range.
            read_node["first"].setValue(seq_range[0])
            read_node["last"].setValue(seq_range[1])
Example #9
0
def nuke_viewerSnapshot(img_path=DEFAULT_PATH):
    LOG.info("nuke_viewerSnapshot")
    import nuke
    viewer = nuke.activeViewer()
    viewNode = nuke.activeViewer().node()

    actInput = nuke.ViewerWindow.activeInput(viewer)
    if actInput < 0: return False

    selInput = nuke.Node.input(viewNode, actInput)

    # look up filename based on top read node
    topName = "[file tail [knob [topnode].file]]"

    # create writes and define render format
    write1 = nuke.nodes.Write(
        file=img_path.replace("\\", "/"),
        name='writeNode1',
        file_type=Tank().data_project['EXTENSION']['thumnail'])
    write1.setInput(0, selInput)

    # look up current frame
    curFrame = int(nuke.knob("frame"))
    # start the render
    nuke.execute(write1.name(), curFrame, curFrame)
    # clean up
    for n in [write1]:
        nuke.delete(n)
Example #10
0
    def thumb_snap(self):
        self.check_for_tmp()

        #lets make sure were snapping for the current shot
        shot = self.shotcombo.currentText()
        if os.getenv('SHOT') == shot:
            viewer = nuke.activeViewer()
            actInput = nuke.ViewerWindow.activeInput(viewer)
            viewNode = nuke.activeViewer().node()
            selInput = nuke.Node.input(viewNode, actInput)
            
            reformatNode = nuke.nodes.Reformat( type = "to format", format = "240 135 eight_scaled", resize = 'fill') 
            reformatNode.setInput(0, selInput) 
            
            self.shot_thumb = os.path.join(jeeves_core.jobsRoot, self.job, 'vfx', 'nuke', self.shot, 'plates', '.tmp', '%s.jpg' % self.shot).replace('\\', '/')

            writeNode = nuke.nodes.Write( file = self.shot_thumb, name = 'tmpWrite2' , file_type = 'jpg')
            writeNode.setInput(0,reformatNode)
            curFrame = int(nuke.knob("frame"))
        
            nuke.execute(writeNode.name(), curFrame, curFrame)
            nuke.delete(writeNode)
            nuke.delete(reformatNode)
            
            self.update_thumb()
        else:
            #print 'not snapping for current shot'
            nuke.message('not snapping for current shot')
Example #11
0
    def createThumbNail(nodeObject):
        try:
            #test creating thumbnail
            reformatNode = nuke.nodes.Reformat()
            reformatNode['type'].setValue("to box")
            reformatNode['box_width'].setValue(200.0)

            reformatNode.setInput(0, nodeObject)

            w2 = nuke.nodes.Write()
            w2.setInput(0, reformatNode)
            thumbNailFilename = 'thumbnail_' + HelpFunctions.getUniqueNumber() + '.png'
            thumbnailDestination = os.path.join(tempfile.gettempdir(), thumbNailFilename)
            w2['file'].setValue(Connector.windowsFixPath(thumbnailDestination))
            w2['file_type'].setValue('png')

            curFrame = int(nuke.knob("frame"))
            nuke.execute(w2, curFrame, curFrame)

            nuke.delete(reformatNode)
            nuke.delete(w2)

            return thumbnailDestination
        except:
            import traceback
            traceback.print_exc(file=sys.stdout)
            return None
Example #12
0
    def __init__(self):
        """
        """
        rvmon = initRvMon()

        panel = RvRenderPanel()
        panel.setMinimumSize(450, 100)
        if not panel.showModalDialog():
            return

        panel.saveToRoot()

        node = nuke.toNode(panel.outputNode.value())

        if (not node):
            nuke.message("No such node as '%s'." % panel.outputNode.value())
            return

        if node.Class() == "Viewer":
            node = node.input(int(nuke.knob(node.name() + ".input_number")))
        """
        self.views = panel.views.value().split()
        self.output = panel.output.value()
        self.proxy = panel.proxy.value()
        """

        dateStr = rvmon.prepForRender(node, "current")

        start = panel.firstFrame.value()
        end = panel.lastFrame.value()
        log("    start %d end %d" % (start, end))
        """
	log ("    has_key %s" % str(node.knobs().has_key("use_limit")))
        log ("    firstFrame %d lastFrame %d" % (node.firstFrame(), node.lastFrame()))
	if ((not node.knobs().has_key("use_limit")) or node["use_limit"].value()) :
	    start = max (start, node.firstFrame())
	    end   = min (end,   node.lastFrame())
        log ("    start %d end %d" % (start, end))
	"""

        incr = 1

        audioFile = ""
        audioOffset = 0.0
        checkpointFrame = int((start + end) / 2)
        rvmon.initializeRvSide()

        if (nuke.views() == ['left', 'right']):
            stereo = "stereo"
        else:
            stereo = "mono"

        rvmon.queueCommand(
            "self.initRenderRun('%s', %d, %d, %d, \"%s\", %g, %d, '%s', '%s', '%s', '%s')"
            % (node.name(), start, end, incr, audioFile, audioOffset,
               checkpointFrame, encodeNL(
                   node["label"].value()), dateStr, "current", stereo))
Example #13
0
def _check_project():
    project_directory = nuke.value('root.project_directory')
    if not project_directory:
        _name = nuke.value('root.name', '')
        if _name:
            _dir = os.path.dirname(_name)
            nuke.knob('root.project_directory', _dir)
            nuke.message(b'工程目录未设置, 已自动设为: {}'.format(_dir))
        else:
            nuke.message(b'工程目录未设置')
    # avoid ValueError of script_directory() when no root.name.
    elif project_directory == r"[python {os.path.abspath(os.path.join("\
        r"'D:/temp', nuke.value('root.name', ''), '../'"\
            r")).replace('\\', '/')}]":
        nuke.knob('root.project_directory',
                  r"[python {os.path.join("
                  r"nuke.value('root.name', ''), '../'"
                  r").replace('\\', '/')}]")
Example #14
0
    def __init__( self):
        """
        """
        rvmon = initRvMon()

        panel = RvRenderPanel()
        panel.setMinimumSize (450, 100)
        if not panel.showModalDialog():
            return

        panel.saveToRoot()

        node = nuke.toNode(panel.outputNode.value())

        if (not node) :
            nuke.message ("No such node as '%s'." % panel.outputNode.value())
            return;

        if node.Class() == "Viewer":
            node = node.input (int(nuke.knob (node.name() + ".input_number")))

        """
        self.views = panel.views.value().split()
        self.output = panel.output.value()
        self.proxy = panel.proxy.value()
        """

        dateStr = rvmon.prepForRender (node, "current")

	start = panel.firstFrame.value()
	end   = panel.lastFrame.value()
        log ("    start %d end %d" % (start, end))
	"""
	log ("    has_key %s" % str(node.knobs().has_key("use_limit")))
        log ("    firstFrame %d lastFrame %d" % (node.firstFrame(), node.lastFrame()))
	if ((not node.knobs().has_key("use_limit")) or node["use_limit"].value()) :
	    start = max (start, node.firstFrame())
	    end   = min (end,   node.lastFrame())
        log ("    start %d end %d" % (start, end))
	"""

        incr = 1

        audioFile = ""
        audioOffset = 0.0
        checkpointFrame = int((start + end) / 2)
        rvmon.initializeRvSide()

        if (nuke.views() == ['left', 'right']) :
            stereo = "stereo"
        else :
            stereo = "mono"

        rvmon.queueCommand("self.initRenderRun('%s', %d, %d, %d, \"%s\", %g, %d, '%s', '%s', '%s', '%s')" % (
                node.name(), start, end, incr, audioFile, audioOffset, 
                checkpointFrame, encodeNL(node["label"].value()), dateStr, "current", stereo))
Example #15
0
def _add_root_info():
    """add info to root.  """

    artist = nuke.value('preferences.wlf_artist', '')
    if not artist:
        return
    if not nuke.exists('root.wlf'):
        n = nuke.Root()
        k = nuke.Tab_Knob('wlf', b'吾立方')
        k.setFlag(nuke.STARTLINE)
        n.addKnob(k)

        k = nuke.String_Knob('wlf_artist', b'制作人')
        k.setFlag(nuke.STARTLINE)
        k.setValue(artist)
        n.addKnob(k)
    else:
        if nuke.exists('root.wlf_artist') and not nuke.value('root.wlf_artist', ''):
            nuke.knob('root.wlf_artist', artist)
def GradeLabel():

    # keep node indicators
    ind = nuke.expression(
        "(keys?1:0)+(has_expression?2:0)+(clones?8:0)+(viewsplit?32:0)")
    if int(nuke.numvalue("maskChannelInput", 0)):
        ind += 4
    if int(nuke.numvalue("this.mix", 1)) < 1:
        ind += 16
    nuke.knob("this.indicators", str(ind))
    ###

    # get the node
    node = nuke.thisNode()

    if node.Class() == "Grade":

        # sets autolabel to node name
        autoLabel = node.name()

        # check if values are zero'ed or not
        BP = ('BP' if node['blackpoint'].value() != 0 else None)
        WP = ('WP' if node['whitepoint'].value() != 1 else None)
        Lift = ('Lift' if node['black'].value() != 0 else None)
        Gain = ('Gain' if node['white'].value() != 1 else None)
        Multiply = ('Multiply' if node['multiply'].value() != 1 else None)
        Offset = ('Offset' if node['add'].value() != 0 else None)
        Gamma = ('Gamma' if node['gamma'].value() != 1 else None)

        # creates list
        knobs = [BP, WP, Lift, Gain, Multiply, Offset, Gamma]

        # if value inside list != None, add to autoLabel
        for knob in knobs:
            if knob != None:
                autoLabel = autoLabel + '\n' + knob

        # adds custom user label if exists
        if node['label'].value():
            autoLabel = autoLabel + '\n' + node['label'].value()

        return autoLabel
 def takeScreenshot(self, fileName):
     fileName = fileName.replace('\\', '/')
     viewer = nuke.activeViewer()
     actInput = nuke.ViewerWindow.activeInput(viewer)
     viewNode = nuke.activeViewer().node()
     selInput = nuke.Node.input(viewNode, actInput)
     write = nuke.nodes.Write(file=fileName, name='tmpWrite', file_type='jpg')
     write.setInput(0, selInput)
     curFrame = int(nuke.knob("frame"))
     nuke.execute(write.name(), curFrame, curFrame)
     nuke.delete(write)
Example #18
0
def BatScriptRenderLight():
    # Save Script
    nuke.scriptSave()
    # Variables of Script
    nukescript = nuke.value("root.name")
    start = nuke.knob("first_frame")
    end = nuke.knob("last_frame")
    cmdLineVar = "nuke5.1" + " " + "-x" + " " + '"' + nukescript + '"' + " " + start + "," + end
    path = nukescript + ".bat"
    # Cmd Message
    nuke.tprint("\nBatScriptRender\nSave Script " + nukescript)
    # Bat File Panel
    myPanel = nuke.Panel("BatScriptRenderLight - Parameters", 338)
    myPanel.addSingleLineInput("Line: ", cmdLineVar)
    myPanel.addSingleLineInput("File: ", path)
    myPanel.addButton("Quit")
    myPanel.addButton("Create")
    myPanel.addButton("Execute")
    result = myPanel.show()
    # Add Button's action & Cmd Message
    if result == 0:
        nuke.tprint("Bat File don't Create")
    elif result == 1:
        # Create Bat File
        cmdLine = myPanel.value("Line: ")
        cmdFile = myPanel.value("File: ")
        file = open(cmdFile, 'w')
        file.write(cmdLine)
        file.close()
        nuke.tprint("Create Bat File " + cmdFile)
    elif result == 2:
        # Execute Bat File
        cmdLine = myPanel.value("Line: ")
        cmdFile = myPanel.value("File: ")
        file = open(cmdFile, 'w')
        file.write(cmdLine)
        file.close()
        os.startfile(cmdFile)
        nuke.tprint("Execute Bat File " + cmdFile)
Example #19
0
def sendObjMesh(target_clientID, sender, tabTarget, alembic=False, frames=[0,0]):
    
    try:
        selectedNode = nuke.selectedNode()
    except ValueError:
        return False
    
    meshOut = {}
    
    geoType = ".obj"
    if alembic:
        geoType = ".abc"
    
    curFrame = int(nuke.knob("frame"))
    tmpfilePath = tempfile.gettempdir() + "\\hcom_tmp_" + ''.join([random.choice("abcdef0123456789") for n in xrange(5)]) + geoType
    tmpWriterName = "tmp_geoWriter_" + ''.join([random.choice("abcdef0123456789") for n in xrange(5)])
    
    result = nuke.executeInMainThreadWithResult(_createObjWriter, args=(tmpWriterName, tmpfilePath, selectedNode, curFrame, alembic, frames))
    
    if not result:
        return False
    
    
    with open(tmpfilePath, 'rb') as f:
        data = f.read()
        
    
    try:   
        os.remove(tmpfilePath)
    except:
        pass
    
    meshOut["MESH_TYPE"] = geoType
    meshOut["MESH_NAME"] = selectedNode.name()
    meshOut["MESH_DATA"] = data
    
    w = nuke.toNode(tmpWriterName)
    if w:
        nuke.delete(w)
    
    outType = "mesh"
    if alembic:
        outType = "alembic"
        meshOut["NAME"]= selectedNode.name()
        meshOut["FRAME_RANGE"] = frames
        meshOut["DATA"]= data
        
    result = _sendData(target_clientID, sender, meshOut, outType, tabTarget)
    
    return result
Example #20
0
def read(node):
    """Return user-defined knobs from given `node`

    Args:
        node (nuke.Node): Nuke node object

    Returns:
        list: A list of nuke.Knob object

    """
    def compat_prefixed(knob_name):
        if knob_name.startswith("avalon:"):
            return knob_name[len("avalon:"):]
        elif knob_name.startswith("ak:"):
            return knob_name[len("ak:"):]
        else:
            return knob_name

    data = dict()

    pattern = (
        "(?<=addUserKnob {)"
        "([0-9]*) (\\S*)"  # Matching knob type and knob name
        "(?=[ |}])")
    tcl_script = node.writeKnobs(nuke.WRITE_USER_KNOB_DEFS)
    result = re.search(pattern, tcl_script)

    if result:
        first_user_knob = result.group(2)
        # Collect user knobs from the end of the knob list
        for knob in reversed(node.allKnobs()):
            knob_name = knob.name()
            if not knob_name:
                # Ignore unnamed knob
                continue

            knob_type = nuke.knob(knob.fullyQualifiedName(), type=True)
            value = knob.value()

            if (knob_type not in EXCLUDED_KNOB_TYPE_ON_READ or
                    # For compating read-only string data that imprinted
                    # by `nuke.Text_Knob`.
                (knob_type == 26 and value)):
                key = compat_prefixed(knob_name)
                data[key] = value

            if knob_name == first_user_knob:
                break

    return data
Example #21
0
def saveFrame(thumbnailPath):
    viewer = nuke.activeViewer()
    inputNode = nuke.ViewerWindow.activeInput(viewer)
    viewNode = nuke.activeViewer().node()
    filetype = 'png'

    try:

        if inputNode != None:
            selInput = nuke.Node.input(viewNode, inputNode)

            if thumbnailPath != None:

                if not os.path.exists(os.path.dirname(thumbnailPath)):
                    os.makedirs(os.path.dirname(thumbnailPath))

                input_w = selInput.width()
                input_h = selInput.height()
                factor = input_h / 448

                w = int(input_w / factor)
                h = int(input_h / factor)

                reformat = nuke.nodes.Reformat(format="%s %s" % (w, h),
                                               resize="width")
                reformat.setInput(0, selInput)
                write = nuke.nodes.Write(file=thumbnailPath,
                                         name='WriteSaveThisFrame',
                                         file_type=filetype)
                write.setInput(0, reformat)

                curFrame = int(nuke.knob("frame"))
                nuke.execute(write.name(), curFrame, curFrame)

                # Clear
                nuke.delete(write)
                nuke.delete(reformat)

                # Succcess
                # nuke.tprint("Save thumbnail : " + thumbnailPath)
                return thumbnailPath
        else:
            nuke.message("This viewer don't have any input connected!")

    except Exception as e:
        nuke.tprint(str(e))
def setFrameRange(hInHead=48, hInTail=48, hOutHead=8, hOutTail=8, headOffset=1):
    plate = nuke.selectedNode()
    # starts plate at frame 1000
    plate["frame_mode"].setValue(1)
    plate["frame"].setValue(str(headOffset))
    # calculates frame range
    firstFrame = str(headOffset + hInHead - hOutHead)
    lastFrame = str(headOffset + plate["last"].getValue() - plate["first"].getValue() - hInTail + hOutTail)
    # sets project frame range
    nuke.knob("root.first_frame", firstFrame)
    nuke.knob("root.last_frame", lastFrame)
    nuke.knob("root.lock_range", "1")
Example #23
0
def createCheckpoint():

    nodes = nuke.selectedNodes()

    if (len(nodes) != 1):
        nuke.message("Please select a node to checkpoint.")
        return

    node = nodes[0]

    if (type(node).__name__ != "Node" and type(node).__name__ != "Viewer"):
        nuke.message(
            "Node '%s' is not renderable, pleases select a node that can be rendered."
            % node.name())
        return

    if (node.Class() == "Read" or node.Class() == "Write"):
        nuke.message(
            "There's no need to checkpoint Read or Write nodes, since they can be viewed directly in RV."
        )
        return

    log("createCheckpoint %s" % node.name())
    rvmon = initRvMon()
    rvmon.initializeRvSide()

    if node.Class() == "Viewer":
        node = node.input(int(nuke.knob(node.name() + ".input_number")))

    dateStr = rvmon.prepForRender(node, "checkpoint")

    f = nuke.frame()

    if (nuke.views() == ['left', 'right']):
        stereo = "stereo"
    else:
        stereo = "mono"

    rvmon.queueCommand(
        "self.initRenderRun('%s', %d, %d, %d, \"%s\", %g, %d, '%s', '%s', '%s', '%s')"
        % (node.name(), f, f, 1, "", 0.0, f, encodeNL(
            node["label"].value()), dateStr, "checkpoint", stereo))
    """
Example #24
0
    def updateAndSyncSelection (self, force=False) :

        nodes = nuke.selectedNodes()

        if (len(nodes) == 1) :

            node = nodes[0]

            if (node.Class() == "Viewer") :
                node = node.input (int(nuke.knob (node.name() + ".input_number")))

            if (not node) :
                return

            log ("updateAndSyncSelection old %s new %s" % (self.selectedNode, node.name()))
            if (force or node.name() != self.selectedNode) :
                self.selectedNode = node.name()
                self.queueCommand ("self.selectCurrentByNodeName()")
                self.queueCommand ("self.changeFrame(%d)" % nuke.frame())
        else :
            self.selectedNode = None
Example #25
0
def read(node, filter=None):
    """Return user-defined knobs from given `node`

    Args:
        node (nuke.Node): Nuke node object
        filter (func, optional): Function for filtering knobs by
            knob name prefix and remove prefix as data entry name.
            If not provided, all user-defined knobs will be read.

    Returns:
        dict

    """
    data = dict()
    filter = filter or (lambda name: name)

    first_user_knob = _parse_first_user_knob(node)
    if first_user_knob is not None:
        # Collect user knobs from the end of the knob list
        for knob in reversed(node.allKnobs()):
            knob_name = knob.name()
            if not knob_name:
                # Ignore unnamed knob
                continue

            knob_type = nuke.knob(knob.fullyQualifiedName(), type=True)
            value = knob.value()

            if (knob_type not in EXCLUDED_KNOB_TYPE_ON_READ or
                    # For compating read-only string data that imprinted
                    # by `nuke.Text_Knob`.
                (knob_type == 26 and value)):
                key = filter(knob_name)
                if key:
                    data[key] = value

            if knob_name == first_user_knob:
                break

    return data
Example #26
0
def createCheckpoint () :

    nodes = nuke.selectedNodes()

    if (len(nodes) != 1) :
        nuke.message ("Please select a node to checkpoint.")
        return

    node = nodes[0]

    if (type(node).__name__ != "Node" and type(node).__name__ != "Viewer") :
        nuke.message ("Node '%s' is not renderable, pleases select a node that can be rendered." % node.name())
        return

    if (node.Class() == "Read" or node.Class() == "Write") :
        nuke.message ("There's no need to checkpoint Read or Write nodes, since they can be viewed directly in RV.")
        return

    log ("createCheckpoint %s" % node.name())
    rvmon = initRvMon()
    rvmon.initializeRvSide()

    if node.Class() == "Viewer":
        node = node.input (int (nuke.knob (node.name() + ".input_number")))

    dateStr = rvmon.prepForRender (node, "checkpoint")

    f = nuke.frame()

    if (nuke.views() == ['left', 'right']) :
        stereo = "stereo"
    else :
        stereo = "mono"

    rvmon.queueCommand("self.initRenderRun('%s', %d, %d, %d, \"%s\", %g, %d, '%s', '%s', '%s', '%s')" % (
            node.name(), f, f, 1, "", 0.0, f, encodeNL (node["label"].value()), dateStr, "checkpoint", stereo)) 

    """
Example #27
0
    def updateAndSyncSelection(self, force=False):

        nodes = nuke.selectedNodes()

        if (len(nodes) == 1):

            node = nodes[0]

            if (node.Class() == "Viewer"):
                node = node.input(int(nuke.knob(node.name() +
                                                ".input_number")))

            if (not node):
                return

            log("updateAndSyncSelection old %s new %s" %
                (self.selectedNode, node.name()))
            if (force or node.name() != self.selectedNode):
                self.selectedNode = node.name()
                self.queueCommand("self.selectCurrentByNodeName()")
                self.queueCommand("self.changeFrame(%d)" % nuke.frame())
        else:
            self.selectedNode = None
Example #28
0
def sendNodeOuput(target_clientID, sender, tabTarget):
    
    fileType = HComNukeUtils.readIni()["OUTPUT_IMAGE_FORMAT"]
    
    try:
        selectedNode = nuke.selectedNode()
    except ValueError:
        return False
    
    curFrame = int(nuke.knob("frame"))
    tmpfilePath = tempfile.gettempdir() + "\\hcom_tmp_" + ''.join([random.choice("abcdef0123456789") for n in xrange(5)]) + "." + fileType
    tmpWriterName = "tmp_writer_" + ''.join([random.choice("abcdef0123456789") for n in xrange(5)])
    
    result = nuke.executeInMainThreadWithResult(_createWriter, args=(tmpWriterName, tmpfilePath, selectedNode, curFrame))
    
    if not result:
        return False
    
    with open(tmpfilePath, 'rb') as f:
        data = f.read()
        
    outImdageData = {}
    outImdageData["IMAGE_NAME"] = os.path.basename(selectedNode.name()) + "." + fileType
    outImdageData["BINARY_DATA"] = data
    
    try:   
        os.remove(tmpfilePath)
    except:
        pass
    
    w = nuke.toNode(tmpWriterName)
    if w:
        nuke.delete(w)
    
    result = _sendData(target_clientID, sender, outImdageData, "pic", tabTarget)
    
    return result
Example #29
0
	def setFPS(self, origin, fps):
		return nuke.knob("root.fps", str(fps))
Example #30
0
def launch_nukes(): 
    a = nuke.knob("first_frame")
    b = nuke.knob("last_frame")
    start = int(a)
    end = int(b)
    incr = 1
    instances = 1
    _range = a+","+b
    p = nuke.Panel("Launch Nukes")
    p.addSingleLineInput("Frames to execute:", _range)
    p.addSingleLineInput("Number of background procs:", instances)
    p.addButton("Cancel")
    p.addButton("OK")
    result = p.show()
    
    r = p.value("Frames to execute:")
    s = p.value("Number of background procs:")
    if r is None: 
        return
    if s is None: 
        return
    # this is the requested frame range
    frames = r
    # this is the number of instances to launch
    inst = int(s)

    (scriptpath, scriptname) = os.path.split(nuke.value("root.name"))
    flags = "-ixfm 1"
    
    print ">>> launching %s nuke instances" % inst
    
    # create a frame range string for each renderer
    for i in range(inst):
        print ">>> generating range for instance %d" % i
        instRange = ""
    
        # separate ranges at spaces
        f = frames.split(" ")
        
        # separate individual start, end, and increment values
        for p in f:
            c = p.split(",")
            incr = 1
            if len(c) > 0:
                start = int(c[0])
                end = start
            if len(c) > 1: end = int(c[1])
            if len(c) > 2: incr = int(c[2])
            
            # re-jigger this range for this instance of the renderer
            st = start + ( i * incr )
            en = end
            inc = incr * inst
            new = "%d,%d,%d" % (st, en, inc)
            if inc == 1:
                new = "%d,%d" % (st, en)
            if en == st:
                new = "%d" % st
            if st > en:
                new = ""
            else:
                # add the re-jiggered range to the instances range string
                instRange = instRange + " " + new
                
        print ">>> range for instance %d is: %s" % (i, instRange)
        
        logFile = "%s/%s_log%02d.log" % (scriptpath, scriptname, i)
        
        cmd = "%s %s %s/%s %s > %s &" % (nuke.EXE_PATH, flags, scriptpath, scriptname, instRange, logFile)
        print ">>> starting instance %d" % (i, )
        print "command: " + cmd
        os.system(cmd)
    def _createIntermediateNode(self):
        """Create a write node to render out the current node so that output may be used for flipbooking."""
        flipbooktmp = self._getIntermediatePath()

        fieldname = "file"
        if self._useProxy.value():
            fieldname = "proxy"

        fixup = nuke.createNode("Group",
                                "tile_color 0xff000000",
                                inpanel=False)
        with fixup:
            fixup.setName("Flipbook")
            inputNode = nuke.createNode("Input", inpanel=False)
            shuffle = nuke.createNode("Shuffle", inpanel=False)
            shuffle.knob("in").setValue(self._channels.value())
            write = nuke.createNode("Write",
                                    fieldname + " {" + flipbooktmp + "}",
                                    inpanel=False)
            write.knob('file_type').setValue(self._getIntermediateFileType())
            write.knob('views').fromScript(" ".join(self._selectedViews()))

            if self._getIntermediateFileType() == "exr":
                write.knob('compression').setValue("B44")
            if self._burnInLUT.value():
                lut = self._getLUT()
                if lut != "None":
                    write.knob('colorspace').setValue(lut)
            outputNode = nuke.createNode("Output", inpanel=False)
        #If called on a Viewer connect fixup node to the one immediately above if exists.
        if self._node.Class() == "Viewer":
            fixup.setInput(
                0,
                self._node.input(
                    int(nuke.knob(self._node.fullName() + ".input_number"))))
        else:
            fixup.setInput(0, self._node)

        try:
            # Throws exception on render failure
            if (self.isBackgrounded()):
                nuke.executeBackgroundNuke(
                    nuke.EXE_PATH, [write],
                    nuke.FrameRanges(self._frameRange.value().split(',')),
                    self._selectedViews(), self._getBackgroundLimits(),
                    self._continueOnError.value(), self._flipbookEnum.value(),
                    self._getOptions(write))
            else:
                nuke.executeMultiple(
                    (write, ),
                    nuke.FrameRanges(self._frameRange.value().split(',')),
                    self._selectedViews(), self._continueOnError.value())
        except RuntimeError, msg:
            if msg.args[0][0:9] == "Cancelled":
                splitMsg = string.split(msg.args[0])

                msg = """Render did not complete, do you want to show the completed range?
Frame range %s contains %s frames but only %s finished.""" % (
                    self._frameRange.value(), splitMsg[3], splitMsg[1])
                if nuke.ask(msg) == False:
                    nuke.delete(fixup)
                    fixup = None
            else:
                nuke.delete(fixup)
                fixup = None
                nuke.message("Flipbook render failed:\n%s" % (msg.args[0], ))
Example #32
0
    if (start) < 0 or (end < 0):
        raise RuntimeError(
            "Flipbook cannot be executed, negative frame range not supported(%s)."
            % (str(f), ))

    proxy = nuke.toNode("root").knob("proxy").value()

    if (node.Class() == "Read" or node.Class() == "Write") and not proxy:
        try:
            command(node, start, end, incr, views_input)
        except Exception, msg:
            nuke.message("Error running flipbook:\n%s" % (msg, ))
        return

    if node.Class() == "Viewer":
        input_num = int(nuke.knob(node.name() + ".input_number"))
        input = node.input(input_num)
        if input is None: return

        if (input.Class() == "Read" or input.Class() == "Write") and not proxy:
            try:
                command(input, start, end, incr, views_input)
            except Exception, msg:
                nuke.message("Error running flipbook:\n%s" % (msg, ))
            return

    # okay now we must execute it...
    flipbooktmp = ""
    if flipbooktmp == "":
        try:
            flipbooktmp = os.environ["FC_DISK_CACHE"]
Example #33
0
    def _create_read_node(self, path, sg_publish_data):
        """
        Create a read node representing the publish.
        
        :param path: Path to file.
        :param sg_publish_data: Shotgun data dictionary with all the standard publish fields.        
        """        
        import nuke
        
        (_, ext) = os.path.splitext(path)

        valid_geo_extensions = [".abc", ".obj", ".fbx"]

        # If this is an Alembic cache, use a ReadGeo2 and we're done.
        if ext.lower() in valid_geo_extensions:
            read_geo = nuke.createNode('ReadGeo2')
            # TODO: check issue of alembic with multiple nodes
            # http://community.foundry.com/discuss/topic/103204
            read_geo.knob('file').setValue(path)
            # add the SGTK metadata on the node
            self._add_node_metadata(read_geo, path, sg_publish_data)
            return

        valid_extensions = [".png", 
                            ".jpg", 
                            ".jpeg", 
                            ".exr", 
                            ".cin", 
                            ".dpx", 
                            ".tiff", 
                            ".tif", 
                            ".mov", 
                            ".psd",
                            ".tga",
                            ".ari",
                            ".gif",
                            ".iff"]

        if ext.lower() not in valid_extensions:
            raise Exception("Unsupported file extension for '%s'!" % path)

        # `nuke.createNode()` will extract the format from the
        # file itself (if possible), whereas `nuke.nodes.Read()` won't. We'll
        # also check to see if there's a matching template and override the
        # frame range, but this should handle the zero config case. This will
        # also automatically extract the format and frame range for movie files.
        read_node = nuke.createNode("Read")
        # this detects frame range automatically only if it is explicitly passed
        # (i.e. if the argument to fromUserText() is of the format
        # "<img_seq_path> <start>-<end>")
        read_node["file"].fromUserText(path)

        # find the sequence range if it has one:
        seq_range = self.parent.utils.find_sequence_range(self.sgtk, path)

        # to fetch the nuke prefs from pipeline
        step = self._find_pipe_step(path, sg_publish_data)
        nuke_prefs = NukePreferences(step)

        for knob_name, knob_value in nuke_prefs.getKnobOverridesGenerator(step):
            if read_node.Class() in knob_name:
                knob_name = knob_name.replace(read_node.Class(), read_node.name())
                nuke.knob(knob_name, knob_value)

        if seq_range:
            # override the detected frame range.
            read_node["first"].setValue(seq_range[0])
            read_node["last"].setValue(seq_range[1])
        else:
            self.parent.logger.warning("{}: Not setting frame range.".format(read_node.name()))

        # try to fetch a proxy path using templates
        proxy_path = self._get_proxy_path(path)

        if proxy_path:
            read_node["proxy"].fromUserText(proxy_path)
        else:
            self.parent.logger.warning("{}: Not setting proxy path.".format(read_node.name()))

        # add the SGTK metadata on the node
        self._add_node_metadata(read_node, path, sg_publish_data)
Example #34
0
    def populate_ftrack(self):

        import nuke
        import legacy
        from nukescripts import panels

        from ftrack_connect_nuke.connector import Connector

        # Check if QtWebKit or QWebEngine is avaliable.
        from FnAssetAPI.ui.toolkit import is_webwidget_supported
        has_webwidgets = is_webwidget_supported()

        Connector.registerAssets()

        # wrappers for initializing the widgets with
        # the correct connector object
        def wrapImportAssetDialog(*args, **kwargs):
            from ftrack_connect.ui.widget.import_asset import FtrackImportAssetDialog
            return FtrackImportAssetDialog(connector=Connector())

        def wrapAssetManagerDialog(*args, **kwargs):
            from ftrack_connect.ui.widget.asset_manager import FtrackAssetManagerDialog
            return FtrackAssetManagerDialog(connector=Connector())

        # Populate the ui
        nukeMenu = nuke.menu("Nuke")
        ftrackMenu = nukeMenu.addMenu("&ftrack")

        ftrackMenu.addSeparator()

        # add ftrack publish node to the menu
        ftrackMenu.addCommand('Create Publish Node',
                              lambda: legacy.createFtrackPublish())

        ftrackMenu.addSeparator()

        globals()['ftrackImportAssetClass'] = wrapImportAssetDialog

        panels.registerWidgetAsPanel(
            '{0}.{1}'.format(__name__, 'ftrackImportAssetClass'),
            'ftrackImportAsset', 'ftrackDialogs.ftrackImportAssetDialog')

        ftrackMenu.addSeparator()

        ftrackMenu.addCommand(
            'Import Asset', 'pane = nuke.getPaneFor("Properties.1");'
            'panel = nukescripts.restorePanel("ftrackDialogs.ftrackImportAssetDialog");'
            'panel.addToPane(pane)')

        globals()['ftrackAssetManagerDialogClass'] = wrapAssetManagerDialog

        # Create the asset manager dialog entry in the menu
        panels.registerWidgetAsPanel(
            '{0}.{1}'.format(__name__, 'ftrackAssetManagerDialogClass'),
            'ftrackAssetManager', 'ftrackDialogs.ftrackAssetManagerDialog')
        ftrackMenu.addCommand(
            'Asset Manager', 'pane = nuke.getPaneFor("Properties.1");'
            'panel = nukescripts.restorePanel("ftrackDialogs.ftrackAssetManagerDialog");'
            'panel.addToPane(pane)')

        if has_webwidgets:

            def wrapAssetInfoDialog(*args, **kwargs):
                from ftrack_connect_nuke.ui.widget.info_view import AssetInfoView
                return AssetInfoView(bridge=self._bridge)

            globals()['ftrackAssetInfoDialogClass'] = wrapAssetInfoDialog

            # Create the crew dialog entry in the menu
            panels.registerWidgetAsPanel(
                '{0}.{1}'.format(__name__, 'ftrackAssetInfoDialogClass'),
                'ftrackAssetInfo', 'ftrackDialogs.ftrackAssetInfoDialog')

            ftrackMenu.addCommand(
                'Asset Info', 'pane = nuke.getPaneFor("Properties.1");'
                'panel = nukescripts.restorePanel("ftrackDialogs.ftrackAssetInfoDialog");'
                'panel.addToPane(pane)')

        ftrackMenu.addSeparator()

        if has_webwidgets:
            from ftrack_connect_foundry.ui.info_view import WorkingTaskInfoView as _WorkingTaskInfoView
            from ftrack_connect_foundry.ui.tasks_view import TasksView as _TasksView

            # Add Web Views located in the ftrack_connect_foundry package to the
            # menu for easier access.
            for widget in [_TasksView, _WorkingTaskInfoView]:
                ftrackMenu.addCommand(
                    widget.getDisplayName(),
                    'pane = nuke.getPaneFor("Properties.1");'
                    'panel = nukescripts.restorePanel("{identifier}");'
                    'panel.addToPane(pane)'.format(
                        identifier=widget.getIdentifier()))

        ftrackMenu.addSeparator()

        # Add new entries in the ftrack menu.
        ftrackMenu.addSeparator()

        if has_webwidgets:
            from ftrack_connect_nuke.ui.widget.publish_gizmo import GizmoPublisherDialog
            ftrackMenu.addCommand('Publish gizmo', GizmoPublisherDialog)

        # Add ftrack publish node
        toolbar = nuke.toolbar("Nodes")
        ftrackNodesMenu = toolbar.addMenu("ftrack", icon="ftrack_logo.png")
        ftrackNodesMenu.addCommand('ftrackPublish',
                                   lambda: legacy.createFtrackPublish())

        # Set calbacks

        def asset_info_menu_switch():
            '''Enable and disable asset info depending on selection.'''

            this_node = nuke.thisNode()

            # Do not continue if selection is not node.
            if not isinstance(this_node, nuke.Node):
                return

            try:
                is_ftrack = this_node.knob('assetVersionId')
            except ValueError:
                is_ftrack = False

            nuke_menu = nuke.menu('Nuke')
            menu_item = nuke_menu.findItem('&ftrack')
            asset_info_menu = menu_item.findItem('Asset Info')

            if has_webwidgets and asset_info_menu:
                if is_ftrack:
                    asset_info_menu.setEnabled(True)
                else:
                    asset_info_menu.setEnabled(False)

        nuke.addKnobChanged(asset_info_menu_switch)

        # other callbacks
        nuke.addOnScriptLoad(legacy.refAssetManager)
        nuke.addOnScriptLoad(legacy.scan_for_new_assets)
        nuke.addOnUserCreate(legacy.addFtrackComponentField, nodeClass='Write')
        nuke.addOnUserCreate(legacy.addFtrackComponentField,
                             nodeClass='WriteGeo')
        nuke.addOnUserCreate(legacy.addFtrackComponentField, nodeClass='Read')
        nuke.addKnobChanged(legacy.ftrackPublishKnobChanged, nodeClass="Group")
        nuke.addOnCreate(legacy.ftrackPublishHieroInit)

        # Set default values from environments.
        start_frame = os.environ.get('FS', 0)
        end_frame = os.environ.get('FE', 100)

        FnAssetAPI.logging.debug(
            'Setting start frame : {}'.format(start_frame))
        nuke.knob('root.first_frame', str(start_frame))
        FnAssetAPI.logging.debug('Setting end frame : {}'.format(end_frame))
        nuke.knob('root.last_frame', str(end_frame))
Example #35
0
def launch_nukes(nodes=[]):
    """
    Launch single-core command-line Nuke renderers from inside the Nuke UI.
    """

    if nuke.root().knob('name').value() == '':
        nuke.message('This script is not named. Please save it and try again.')
        return
    
    # Select Write nodes.
    nodelist = ''
    if nodes != []:
        nodelist = ','.join([n.name() for n in nodes if "Write" in n.Class()])
    
    start = int(nuke.knob("first_frame"))
    end = int(nuke.knob("last_frame"))
    instances = nuke.env['numCPUs']
    framerange = str(start) + "-" + str(end)
    p = nuke.Panel("Launch Nukes")
    p.addSingleLineInput("Frames to execute:", framerange)
    p.addSingleLineInput("Node(s) to execute:", nodelist)
    p.addSingleLineInput("Number of background procs:", instances)
    p.addButton("Cancel")
    p.addButton("OK")
    result = p.show()
    
    if not result: return
    framerange = p.value("Frames to execute:")
    nodelist = p.value("Node(s) to execute:").replace(' ', '')
    inst = int(p.value("Number of background procs:"))
    if framerange is None: 
        return
    if inst is None: 
        return

    (scriptpath, scriptname) = os.path.split(nuke.value("root.name"))
    flags = "-ixm 1"
    if nodelist != '': flags += " -X " + nodelist
    
    r = nuke.FrameRanges()
    r.add(framerange)
    r.compact()
    frame_list = r.toFrameList()
    print frame_list
    
    # Create lists of frames to render for each instance.
    inst_frame_list = []
    for i in range(inst): inst_frame_list.append([])
    print inst_frame_list
    cnt = 0
    for frame in frame_list:
        inst_frame_list[cnt].append(str(frame))
        cnt += 1
        if cnt == inst: cnt = 0
    print inst_frame_list
    
    print ">>> launching", inst, "nuke instances"
    
    # Launch each renderer
    logs = []
    for i in range(inst):
        instRange = ' '.join(inst_frame_list[i])

        print ">>> frame list for instance", i, "is:", instRange
        
        logFile = "%s/%s_log%02d.log" % (scriptpath, scriptname, i)
        logs.append(logFile)
        
        cmd = " ".join([nuke.env['ExecutablePath'], flags, '-F', '"' + instRange + '"', nuke.value("root.name"), '&>', logFile])
        print ">>> starting instance %d" % (i, )
        print "command: " + cmd
        subprocess.Popen(cmd, shell=True)
    
    nuke.message(str(inst) + ' renderers launched in the background.\nLog files: ' + ', '.join(logs))
Example #36
0
		
		
		if filePath != None:
=======
        if filePath != None:

            #Check Path
            path, ext = os.path.split(filePath)
            if not os.path.isdir(path):
                os.makedirs(path)          

>>>>>>> bed50f88abdec1936e64c57eccc98bf40a6253f5

            write = nuke.nodes.Write(file = filePath, name = 'WriteSaveThisFrame', file_type=ext)
            write.setInput(0,selInput)
            curFrame = int(nuke.knob("frame"))
            nuke.execute(write.name(), curFrame, curFrame)
            nuke.delete(write)
            print "saved: " + filePath

    else:
        nuke.message("This viewer don't have any input connected!")

def getSeqName():
    res = ""    
    scriptpath = str.split(nuke.root().knob('name').value() , "/")    
    res = scriptpath[len(scriptpath)-3]
    return res


<<<<<<< HEAD
Example #37
0
def nuke_ui():
    allWriteNodes = [
        node for node in nuke.allNodes()
        if node.Class() == 'Write' or node.Class() == 'DeepWrite'
    ]

    panel = nuke.Panel('GS Render Submit')
    panel.addSingleLineInput('Project', PROJ_NAME)
    panel.addSingleLineInput(
        'Job Name',
        os.path.splitext(os.path.split(nuke.value('root.name'))[1])[0])
    if gsstartup.properties['location'] == 'NYC':
        panel.addBooleanCheckBox('Use LA Render Farm', 0)
    panel.addSingleLineInput(
        'Frame Range',
        '%s-%s' % (nuke.knob('first_frame'), nuke.knob('last_frame')))
    panel.addSingleLineInput('Packet Size', 5)
    panel.addSingleLineInput('Priority (1-100)', 50)
    for n in allWriteNodes:
        k = panel.addBooleanCheckBox(n.name(), n.isSelected())
    panel.setWidth(300)
    panel.addButton('Cancel')
    panel.addButton('Submit')
    result = panel.show()

    selected_write_nodes = [n for n in allWriteNodes if panel.value(n.name())]
    selected_write_nodes_string = ','.join(
        [n.name() for n in selected_write_nodes])

    if result and check_saved() == 1 and check_write_selected(
            selected_write_nodes_string) == 1:
        newfile = save_render_file()
        framerange = [
            int(value) for value in re.sub(
                '[^0-9]', ',', panel.value('Frame Range')).split(',')
        ]

        musterflags = {}
        musterflags['-add'] = '--major %s  --job %s -X \"%s\"' % (
            nuke.NUKE_VERSION_STRING, panel.value('Project'),
            selected_write_nodes_string)
        musterflags['-e'] = '1105'
        musterflags['-n'] = panel.value('Job Name')
        musterflags['-parent'] = '33409'
        musterflags['-group'] = gsstartup.get_project_from_path(newfile)
        try:
            if panel.value('Use LA Render Farm'
                           ) or gsstartup.properties['location'] == 'LAX':
                musterflags['-pool'] = 'NUKE'
            else:
                musterflags['-pool'] = 'WKSTN-NY'
        except:
            musterflags['-pool'] = 'NUKE'
        musterflags['-sf'] = str(framerange[0])
        musterflags['-ef'] = str(framerange[1])
        musterflags['-bf'] = len(framerange) > 2 and str(framerange[2]) or '1'
        musterflags['-pr'] = panel.value('Priority (1-100)')
        musterflags['-f'] = newfile

        for n in selected_write_nodes:
            if n.knob('file_type').value() in ['mov']:
                musterflags['-pk'] = '999999'
                break
            else:
                musterflags['-pk'] = panel.value('Packet Size')

        if gsstartup.properties[
                'location'] == 'NYC' and musterflags['-pool'] != 'WKSTN-NY':
            newfileup = newfile.replace("\\",
                                        "/").replace(" ",
                                                     "\ ").replace("//", "/")
            newfiledest = os.path.split(newfileup)[0].replace(
                "\\", "/").replace(" ", "\ ").replace("//", "/")
            ascpupcmd = 'ascpgs render@nycbossman:%s %s;' % (newfileup,
                                                             newfiledest)

            ascpupflags = {}
            ascpupflags['-e'] = '43'
            ascpupflags['-n'] = '%s Asset Upload' % (panel.value('Job Name'))
            ascpupflags['-parent'] = '33409'
            ascpupflags['-group'] = gsstartup.get_project_from_path(newfile)
            ascpupflags['-pool'] = 'ASPERA'

            for r in get_read_nodes():
                #src = re.sub('%\d+d','*', r).replace("\\", "/").replace(" ", "\ ").replace("//","/")
                src = os.path.split(r)[0].replace("\\", "/").replace(
                    " ", "\ ").replace("//", "/")
                dest = os.path.split(src)[0].replace("\\", "/").replace(
                    " ", "\ ").replace("//", "/")
                ascpupcmd = ascpupcmd + 'ascpgs render@nycbossman:%s %s;' % (
                    src, dest)

            for w in selected_write_nodes:
                f = w.knob('file').value()
                dest = os.path.split(f)[0].replace("\\", "/").replace(
                    " ", "\ ").replace("//", "/")
                ascpupcmd = ascpupcmd + 'mkdir -p %s;' % (dest)

            ascpupflags[
                '-add'] = '-c \"script -q -c \'%s\' /tmp/last_aspera_xfer.log\"' % (
                    ascpupcmd)
            ascpupsubmit = muster.submit(ascpupflags)

            if ascpupsubmit:
                musterflags['-wait'] = ascpupsubmit
                rendersubmit = muster.submit(musterflags)
                if rendersubmit:
                    ascpdownflags = {}
                    ascpdownflags['-e'] = '43'
                    ascpdownflags['-n'] = '%s Render Download' % (
                        panel.value('Job Name'))
                    ascpdownflags['-parent'] = '33409'
                    ascpdownflags['-group'] = gsstartup.get_project_from_path(
                        newfile)
                    ascpdownflags['-pool'] = 'ASPERA'
                    ascpdownflags['-wait'] = rendersubmit

                    ascpdowncmd = ''
                    for w in selected_write_nodes:
                        f = w.knob('file').value()
                        src = re.sub('%\d+d',
                                     '*', f).replace("\\", "/").replace(
                                         " ", "\ ").replace("//", "/")
                        dest = os.path.split(f)[0].replace("\\", "/").replace(
                            " ", "\ ").replace("//", "/")
                        #ascpdowncmd = ascpdowncmd + 'ascp -p -d -v -k 1 --remove-after-transfer -i ~/.ssh/id_rsa -l 1G %s render@nycbossman:%s;' %(src, dest)
                        ascpdowncmd = ascpdowncmd + 'ascpgs %s render@nycbossman:%s;' % (
                            src, dest)
                    ascpdownflags[
                        '-add'] = '-c \"script -q -c \'%s\' /tmp/last_aspera_xfer.log\"' % (
                            ascpdowncmd)
                    ascpdownsubmit = muster.submit(ascpdownflags)

                    if ascpdownsubmit:
                        nuke.message('Jobs successfully submitted to Muster!')
                    else:
                        print 'There was an error submitting download job to Muster'
                else:
                    print 'There was an error submitting render job to Muster.'
            else:
                print 'There was an error submitting upload job to Muster.'
        else:
            rendersubmit = muster.submit(musterflags)
            if rendersubmit:
                nuke.message('Job ID#%s successfully submitted to Muster!' %
                             (rendersubmit))
            else:
                print 'There was an error submitting render job to Muster.'
    else:
        print 'Cancelled Muster Render'
Example #38
0
def _eval_proj_dir():
    if nuke.numvalue('preferences.wlf_eval_proj_dir', 0.0):
        attr = 'root.project_directory'
        nuke.knob(attr, os.path.abspath(nuke.value(attr)).replace('\\', '/'))
Example #39
0
def CLrender(nodes=[]):
    """
    Creates command-line Nuke batch file with different control parameters (frame by frame, skip existing frame, Stereo)
    """

    if nuke.root().knob('name').value() == '':
        nuke.message('This script is not named. Please save it and try again.')
        return
    nodelist = ''
    if nodes != []:
        nodelist = ','.join([n.name() for n in nodes if n.Class() == "Write"])
    else:
        Writes = nuke.allNodes("Write")
        if len(Writes) == 1:
            nodelist = Writes[0].name()
    if nodelist == "":
        nuke.message("Please select Write node(s) !")
        return

    class CLrenderDialog(nukescripts.PythonPanel):
        def __init__(self):
            nukescripts.PythonPanel.__init__(
                self,
                'Create rendering command line batch file(s) -- (philhub 2011)'
            )
            self.setMinimumSize(600, 300)
            self.nodesKnob = nuke.String_Knob('nodesExec',
                                              'Node(s) to execute:', nodelist)
            self.addKnob(self.nodesKnob)
            self.startKnob = nuke.Int_Knob('startFrame', 'Start frame :')
            self.addKnob(self.startKnob)
            self.endKnob = nuke.Int_Knob('endFrame', ' End frame :')
            self.addKnob(self.endKnob)
            self.endKnob.clearFlag(nuke.STARTLINE)
            self.spaceKnob = nuke.Text_Knob('space', '')
            self.addKnob(self.spaceKnob)
            self.spaceKnob.setFlag(nuke.STARTLINE)

            self.limitKnob = nuke.Boolean_Knob('limit', 'Limit Memory to (Go)')
            self.addKnob(self.limitKnob)
            self.limitKnob.setFlag(nuke.STARTLINE)
            self.memKnob = nuke.Int_Knob('mem', '')
            self.addKnob(self.memKnob)
            self.memKnob.clearFlag(nuke.STARTLINE)
            # self.unitKnob = nuke.Text_Knob('unit', 'Go')
            # self.addKnob(self.unitKnob)
            # self.unitKnob.clearFlag(nuke.STARTLINE)

            self.limitcpuKnob = nuke.Boolean_Knob('limitcpu', 'Limit Cores to')
            self.addKnob(self.limitcpuKnob)
            self.limitcpuKnob.clearFlag(nuke.STARTLINE)
            self.cpuKnob = nuke.Int_Knob('cpu', '')
            self.addKnob(self.cpuKnob)
            self.cpuKnob.clearFlag(nuke.STARTLINE)

            self.spaceKnob2 = nuke.Text_Knob('space2', '')
            self.addKnob(self.spaceKnob2)
            self.spaceKnob2.setFlag(nuke.STARTLINE)

            self.threadsKnob = nuke.Int_Knob('threads',
                                             'Number of BAT files :')
            self.addKnob(self.threadsKnob)
            self.threadsKnob.setFlag(nuke.STARTLINE)
            self.threadWhyKnob = nuke.Text_Knob(
                'threadWhy', '(to distrib on multiple cores/boxes)')
            self.addKnob(self.threadWhyKnob)
            self.threadWhyKnob.clearFlag(nuke.STARTLINE)
            self.fbfKnob = nuke.Boolean_Knob(
                'fbf',
                'Frame by Frame ?  (to avoid some insanes increasing render time)'
            )
            self.addKnob(self.fbfKnob)
            self.fbfKnob.setFlag(nuke.STARTLINE)
            self.skipKnob = nuke.Boolean_Knob('skip', 'Skip existing Frames ?')
            self.addKnob(self.skipKnob)
            self.skipKnob.setFlag(nuke.STARTLINE)
            self.stereoKnob = nuke.Boolean_Knob('stereo', 'Stereo ?')
            self.addKnob(self.stereoKnob)
            self.stereoKnob.setFlag(nuke.STARTLINE)
            self.backupKnob = nuke.Boolean_Knob(
                'backup', "Create a comp's backup ? (and renders from it)")
            self.addKnob(self.backupKnob)
            self.openFolderKnob = nuke.Boolean_Knob('openFolder',
                                                    "open folder ?")
            self.addKnob(self.openFolderKnob)
            self.openFolderKnob.setFlag(nuke.STARTLINE)
            self.spaceKnob2 = nuke.Text_Knob('space', '')
            self.addKnob(self.spaceKnob2)
            self.spaceKnob2.setFlag(nuke.STARTLINE)
            self.backupKnob.setFlag(nuke.STARTLINE)
            self.okButton = nuke.Script_Knob("OK")
            self.addKnob(self.okButton)
            self.okButton.setFlag(nuke.STARTLINE)
            self.cancelButton = nuke.Script_Knob("Cancel")
            self.addKnob(self.cancelButton)
            self.infosKnob = nuke.PyScript_Knob('infos', "infos")
            self.infosKnob.setCommand(
                '''import webbrowserwebbrowser.open("http://www.nukepedia.com/python/render/cmdlinerender/")'''
            )
            self.addKnob(self.infosKnob)

    p = CLrenderDialog()

    p.startKnob.setValue(int(nuke.knob("first_frame")))
    p.endKnob.setValue(int(nuke.knob("last_frame")))
    p.memKnob.setValue(8)
    p.cpuKnob.setValue(2)
    p.threadsKnob.setValue(1)
    p.fbfKnob.setValue(1)
    p.skipKnob.setValue(0)
    p.stereoKnob.setValue(0)
    p.backupKnob.setValue(1)
    p.openFolderKnob.setValue(1)

    result = p.showModalDialog()

    if not result: return
    nuke.scriptSave('')
    start = p.startKnob.value()
    end = p.endKnob.value()
    threads = p.threadsKnob.value()
    mem = p.memKnob.value()
    cpu = p.cpuKnob.value()
    fbf = p.fbfKnob.value()
    skip = p.skipKnob.value()
    stereo = p.stereoKnob.value()
    if threads < 1:
        return
    flags = " -x -i "
    if stereo:
        views = ','.join(nuke.views())
    else:
        views = nuke.views()[0]
    flags += " -view " + views

    if nodelist != '':
        flags += " -X " + nodelist
        if p.limitKnob.value():
            flags += " -c " + str(mem) + "G"
        if p.limitcpuKnob.value():
            flags += " -m " + str(cpu)
    comp_dirpath = nuke.value("root.name")
    exe = '"' + nuke.env[
        'ExecutablePath'] + '"'  # for BAT file, " avoid error with names with spaces

    if p.backupKnob.value():
        bkp_dirpath = os.path.dirname(comp_dirpath) + '/backup_from_CLrender/'
        if not os.path.exists(bkp_dirpath):
            os.makedirs(bkp_dirpath)
        bkp_filepath = bkp_dirpath + os.path.basename(comp_dirpath)
        shutil.copy(comp_dirpath, bkp_filepath)
        comp_dirpath = '"' + bkp_filepath + '"'  # for BAT file, " avoid error with names with spaces
    else:
        comp_dirpath = '"' + comp_dirpath + '"'  # for BAT file, " avoid error with names with spaces

    for thread in range(threads):

        bat_name = nuke.value("root.name").replace(
            '.nk', '_' + nodelist.replace(",", "-") + "_x" + str(threads) +
            "x" + str(start + thread) + "-" + str(end) + '.bat')
        if fbf and not (skip):
            cmd = r"FOR /l %%I IN (" + ",".join(
                [str(start + thread),
                 str(threads), str(end)]) + r") DO (" + " ".join(
                     [exe, flags, r"-F %%I-%%I", comp_dirpath]) + ")"
            bat_name = bat_name.replace('.bat', '_FrameByFrame.bat')
        elif skip:
            cmd = r"FOR /l %%I IN (" + ",".join(
                [str(start + thread),
                 str(threads), str(end)]) + r") DO (" + " ".join([
                     exe, "-t",
                     os.path.realpath(__file__), comp_dirpath, nodelist, "%%I",
                     views
                 ]) + ")"
            bat_name = bat_name.replace('.bat', '_SkipExisting.bat')
        else:
            cmd = " ".join([
                exe, flags, '-F', '"' + str(start + thread) + "-" + str(end) +
                'x' + str(threads) + '"', comp_dirpath
            ])

        if stereo:
            bat_name = bat_name.replace('.bat', '_STEREO.bat')

        print "command : " + cmd
        print "saved to : " + bat_name

        try:
            file = open(bat_name, 'w')
            #file.write("mode con cols=500 lines=500")
            file.write("\nCOLOR 4f\n")
            file.write("\n")
            file.write(cmd)
            file.write("\n\nCOLOR 2f\n")
            file.write("pause")
        finally:
            file.close()
    if p.openFolderKnob.value():
        openCompFolder()
Example #40
0
def autolabel():
  """This function is run automatically by Nuke during idle, and the return
  text is drawn on the box of the node. It can also have side effects by
  setting knobs. Currently two knobs are provided that are useful:

  indicators = integer bit flags to turn icons on/off. The icons
  named indicator1, indicator2, indicator4, indicator8, etc are
  drawn if the corresponding bit is on. By default these are loaded
  from the path as indicator1.xpm, etc, but you can use the load_icon
  command to load other files.

  icon = name of a whole extra image you can draw, but it replaces
  any previous one."""

  # do the icons:
  ind = nuke.expression("(keys?1:0)+(has_expression?2:0)+(clones?8:0)+(viewsplit?32:0)")

  if int(nuke.numvalue("maskChannelInput", 0)) :
    ind += 4
  if int(nuke.numvalue("this.mix", 1)) < 1:
    ind += 16
  nuke.knob("this.indicators", str(ind))

  this = nuke.toNode("this")

  # do stuff that works even if autolabel is turned off:
  name = nuke.value("name")
  _class = this.Class()

  label = nuke.value("label")
  if not label:
    label = ""
  else:
    try:
      label = nuke.tcl("subst", label)
    except:
      pass

  if _class == "Dot" or _class == "BackdropNode" or _class == "StickyNote":
    return label
  elif _class.startswith("Read") or _class.startswith("Write") or _class.startswith( "Precomp" ):
    reading = int(nuke.numvalue("this.reading", 0 ))

    if reading and _class.startswith( "Precomp" ):
      filename = nuke.filename( node = this.output().input(0), replace = nuke.REPLACE )
    else:
      filename = nuke.filename(replace = nuke.REPLACE)
    if filename is not None:
      name = __concat_result_string(name, os.path.basename(filename))

    if reading:
      checkHashOnRead = False
      if _class.startswith( "Precomp" ):
        if this.output() != None and this.output().input(0) != None:
          checkHashOnReadKnob = this.output().input(0).knob( "checkHashOnRead" )
          if checkHashOnReadKnob:
            checkHashOnRead = checkHashOnReadKnob.value()
      else:
        checkHashOnRead = this.knob("checkHashOnRead").value()

      if checkHashOnRead == True and ( this.proxy() != True ):
        name = name + "\n(Read)"
      else:
        name = name + "\n(Read - unchecked)"
  elif _class == 'DeepRead':
    filename = nuke.filename(replace = nuke.REPLACE)
    if filename is not None:
      name =  __concat_result_string(name, os.path.basename(filename))
  elif _class.startswith("ParticleCache" ):
    rendering = int(nuke.numvalue("this.particle_cache_render_in_progress", 0 ))
    if rendering:
      name = name + "\n(Rendering)"
    else:
      reading = int(nuke.numvalue("this.particle_cache_read_from_file", 0 ))
      if reading:
        name = name + "\n(Read)"

  if nuke.numvalue("preferences.autolabel") == 0 or _class.find("OFX", 0) != -1:
    return __concat_result_string(name, label)

  # build the autolabel:
  operation = nuke.value('this.operation', '')
  if operation != '' and _class != 'ChannelMerge' and _class != 'Precomp':
    name = name + ' (' + operation + ')'

  layer = nuke.value("this.output", nuke.value("this.channels", "-"))
  mask = nuke.value("this.maskChannelInput", "none")
  unpremult = nuke.value("this.unpremult", "none")

  if _class.startswith("Read") or _class.startswith("Write"):
    # do colorspace labeling for reads and writes
    if int(nuke.numvalue("this.raw", 0)):
      layer = "RAW"
    else:
      colorspace = _getAutoLableColorspace()

      # additional to NUKE-mode default colorspaces not being shown, if the
      # colorspace is set to "custom" (aka unintialised) in the UI the name
      # comes through as empty, so ignore it.
      if colorspace:
        layer = colorspace

    if _class.startswith("Write"):
      order = nuke.numvalue("this.render_order", 1)
      mask = str(order)
      if int(order) == 1:
        mask = "none"
  elif _class == "Reformat":
    if nuke.expression("!type"):
      format = nuke.value("format")
      rootformat = nuke.value("root.format")
      if format is not None and format != rootformat:
        format_list = format.split()
        layer = " ".join(format_list[7:])
  elif _class == "ChannelMerge":
    if operation == "union":
      operation = "U"
    elif operation == "intersect":
      operation = "I"
    elif operation == "stencil":
      operation = "S"
    elif operation == "absminus":
      operation = "abs-"
    elif operation == "plus":
      operation = "+"
    elif operation == "minus":
      operation = "-"
    elif operation == "multiply":
      operation = "*"
    layer = nuke.value("A") + " " + operation + " " + nuke.value("B") + " =\n" + nuke.value("output")
  elif _class == "Premult" or _class == "Unpremult":
    unpremult = nuke.value("alpha")
    if unpremult == "alpha":
      unpremult = "none"
  elif _class == "Copy":
    layer = ""
    if nuke.value("to0") != "none":
      layer += nuke.value("from0") + " -> " + nuke.value("to0")
    if nuke.value("to1") != "none":
      layer += "\n" + nuke.value("from1") + " -> " + nuke.value("to1")
    if nuke.value("to2") != "none":
      layer += "\n" + nuke.value("from2") + " -> " + nuke.value("to2")
    if nuke.value("to3") != "none":
      layer += "\n" + nuke.value("from3") + " -> " + nuke.value("to3")
    if nuke.value("channels") != "none":
      layer += ("\n" + nuke.value("channels") + "->" + nuke.value("channels"))
  elif _class == "FrameHold":
    value_inc = nuke.value("increment")
    if int(value_inc):
      layer = "frame "+nuke.value("knob.first_frame")+"+n*"+value_inc
    else:
      layer = "frame "+nuke.value("knob.first_frame")
  elif _class == "Precomp":
    layer = '-'

  if mask != "none":
    if int(nuke.numvalue("invert_mask", 0)):
      layer += (" / ~" + mask)
    else:
      layer += (" / " + mask)

  if unpremult != "none" and unpremult != mask and _class.find("Deep", 0) == -1:
    layer += ( " / " + unpremult)

  if layer != "rgba" and layer != "rgb" and layer != "-":
    result = __concat_result_string(name, "(" + layer + ")" + "\n" + str(label))
  else:
    result = __concat_result_string(name, label)

  return result