Exemplo n.º 1
0
def make_dir_path():
    file = ""
    # are we being called interactively, by the user hitting Ctrl+F8?
    if nuke.thisNode() == nuke.root():
        sel = None
        try:
            sel = nuke.selectedNodes()[0]
        except:
            print "WARNING: No nodes selected."
            return
        file = nuke.filename(sel)
    else:
        # nuke.filename(nuke.thisNode()) occasionally throws a RuntimeError exception when ran from the addBeforeRender() callback.
        # catch the exception and do not proceed when the exception is thrown.
        # added by Ned, 2016-01-27
        try:
            file = nuke.filename(nuke.thisNode())
        except RuntimeError as re:
            return
        except ValueError as ve:
            return
    dir = os.path.dirname(file)
    osdir = nuke.callbacks.filenameFilter(dir)
    if not os.path.exists(osdir):
        print "INFO: Creating directory at: %s" % osdir
        try:
            os.makedirs(osdir)
        except OSError as e:
            print "ERROR: os.makedirs() threw exception: %d" % e.errno
            print "ERROR: Filename: %s" % e.filename
            print "ERROR: Error String: %s" % e.strerror
    def get_current_value(self, instance):

        current = ""
        if nuke.filename(instance[0]):
            current = nuke.filename(instance[0])

        return current
    def get_current_value(self, instance):
        import nuke

        current = ""
        if nuke.filename(instance[0]):
            current = nuke.filename(instance[0])

        return current
Exemplo n.º 4
0
def autoShuffleReads(nodes):
    import re
    import nuke

    nuke.Undo().name("organize and split")
    nuke.Undo().begin()
    readList = []
    yPosAvg = 0
    xPosAvg = 0
    count = 0
    try:
        nodes  # does a exist in the current namespace
    except NameError:
        nodes = nuke.selectedNodes()
    for curNode in nodes:
        if curNode.Class() == "Read":
            readList.append({"file": nuke.filename(curNode), "node": curNode})
            yPosAvg = yPosAvg + curNode["ypos"].value()
            xPosAvg = xPosAvg + curNode["xpos"].value()
            count += 1

    readListSorted = sorted(readList, key=lambda k: k["file"])
    xPosAvg = int(xPosAvg / count)
    yPosAvg = int(yPosAvg / count)

    count = 0
    for readNode in readListSorted:
        readNode["node"]["xpos"].setValue(xPosAvg - 110 * count)
        readNode["node"]["ypos"].setValue(yPosAvg)
        readNode["node"]["selected"].setValue(True)
        count += 1

    for n in nuke.selectedNodes():
        n.autoplace()

    prevNode = nuke.nodes.Dot()
    originalDot = prevNode

    for curNode in nuke.selectedNodes():
        if curNode.Class() == "Read":
            count += 1
            filename = nuke.filename(curNode)
            passName = filename.split(".")[1]
            if re.match(r"^[A-Za-z0-9_]+$", passName):
                newLayer = nuke.Layer(passName, [passName + ".red", passName + ".green", passName + ".blue"])
                shuffle = nuke.nodes.Shuffle(label=passName, inputs=[curNode])
                shuffle["out"].setValue(passName)
                dotNode = nuke.nodes.Dot(inputs=[shuffle])
                copyNode = nuke.nodes.Copy(inputs=[prevNode, dotNode], channels=passName, selected=True)
                prevNode = copyNode
            else:
                masterNode = curNode
            if count % 2 == 0:
                curNode["ypos"].setValue(curNode["ypos"].value() + 110)
    originalDot.setInput(0, masterNode)
    backdrop = nukescripts.autoBackdrop()
    backdrop.knob("tile_color").setValue(2139062271)
    nuke.Undo().end()
Exemplo n.º 5
0
def preview_on_rv(rv_player="/Applications/RV64.app/Contents/MacOS/RV64"):
    rv_arguments = []
    sequence_list = []

    # READ / WRITE NODES
    for node in (nuke.selectedNodes('Read') + nuke.selectedNodes('Write')):
        file_path = nuke.filename(node)
        if not file_path:
            continue

        file_path = nuke.callbacks.filenameFilter(file_path)
        first_frame = str(
            node.knob('first').value()) if node.Class() == 'Read' else str(
                node.firstFrame())
        last_frame = str(
            node.knob('last').value()) if node.Class() == 'Read' else str(
                node.firstFrame())

        sequence_list.append('[ ' + file_path + ' -in %s -out %s ]' %
                             (first_frame, last_frame))

    # FRAME RANGE NODES
    for node in nuke.selectedNodes('FrameRange'):
        input_node = node.input(0)
        if input_node.Class() in ['Read', 'Write']:
            file_path = nuke.filename(input_node)
            if not file_path:
                continue

            file_path = nuke.callbacks.filenameFilter(file_path)
            first_frame = node.knob('first_frame').value()
            last_frame = node.knob('last_frame').value()

            sequence_list.append('[ ' + file_path + ' -in %s -out %s ]' %
                                 (first_frame, last_frame))

    total_files = len(sequence_list)

    if total_files == 0:
        nuke.message("You must select a Read or a Write node.")
        return

    elif total_files == 2:
        panel = nuke.Panel("Rv Viewer")
        panel.addEnumerationPulldown('Operation',
                                     'Sequence Difference Wipe Tile')
        result = panel.show()
        if not result:
            return

        operation_type = panel.value("Operation")
        if operation_type != 'Sequence':
            rv_arguments.append('-' + operation_type.lower()[0:4])

    ## OPEN RV
    command_line = '"' + rv_player + '"' + ' ' + ' '.join(
        rv_arguments) + ' ' + ' '.join(sequence_list)
    subprocess.Popen(command_line, shell=True)
    def process(self, context):

        # Get remote nodes
        remote_nodes = []
        for node in nuke.allNodes():
            if node.Class() == "BackdropNode":
                if node.name().lower().startswith("remote"):
                    remote_nodes.extend(node.getNodes())

        remote_nodes = list(set(remote_nodes))

        # creating instances per write node
        for node in nuke.allNodes():
            if node.Class() != "Write":
                continue

            # Determine output type
            output_type = "img"
            if node["file_type"].value() == "mov":
                output_type = "mov"

            # Determine processing location from backdrops
            process_place = "local"
            if node in remote_nodes:
                process_place = "remote"

            # Create instance
            instance = context.create_instance(name=node.name())
            instance.data["families"] = ["write", process_place, output_type]
            instance.data["family"] = output_type
            instance.add(node)

            label = "{0} - write - {1}"
            instance.data["label"] = label.format(node.name(), process_place)

            instance.data["publish"] = not node["disable"].getValue()

            # Get frame range
            start_frame = int(nuke.root()["first_frame"].getValue())
            end_frame = int(nuke.root()["last_frame"].getValue())
            if node["use_limit"].getValue():
                start_frame = int(node["first"].getValue())
                end_frame = int(node["last"].getValue())

            # Add collection
            collection = None
            try:
                path = ""
                if nuke.filename(instance[0]):
                    path = nuke.filename(instance[0])
                path += " [{0}-{1}]".format(start_frame, end_frame)
                collection = clique.parse(path)
            except Exception as e:
                self.log.warning(e)

            instance.data["collection"] = collection
Exemplo n.º 7
0
    def process(self, context):
        import clique

        import nuke

        instances = []
        # creating instances per write node
        for node in nuke.allNodes():
            if node.Class() != "Write":
                continue

            # Determine output type
            output_type = "img"
            if node["file_type"].value() == "mov":
                output_type = "mov"

            # Create instance
            instance = api.Instance(node.name())
            instance.data["family"] = output_type
            instance.add(node)

            instance.data["label"] = node.name()

            instance.data["publish"] = False

            # Get frame range
            start_frame = int(nuke.root()["first_frame"].getValue())
            end_frame = int(nuke.root()["last_frame"].getValue())
            if node["use_limit"].getValue():
                start_frame = int(node["first"].getValue())
                end_frame = int(node["last"].getValue())

            # Add collection
            collection = None
            try:
                path = ""
                if nuke.filename(node):
                    path = nuke.filename(node)
                path += " [{0}-{1}]".format(start_frame, end_frame)
                collection = clique.parse(path)
            except ValueError:
                # Ignore the exception when the path does not match the
                # collection.
                pass

            instance.data["collection"] = collection

            instances.append(instance)

        context.data["write_instances"] = instances

        context.data["instances"] = (
            context.data.get("instances", []) + instances
        )
Exemplo n.º 8
0
def sendData():
    try:
        n = nuke.selectedNode()
    except :
        awNodes = nuke.allNodes('AutoWriter')
        n = awNodes[0]
        if len(awNodes) > 1 : 
            nuke.message('Error :\nYou have more than one AutoWrite.  Please select one.')
            return
    
    if n.Class() == 'AutoWriter':
        with n:
            nodes = nuke.allNodes('Write')
        for curNode in nodes:
            if 'exr' in nuke.filename(curNode).lower():
                exrPath = nuke.filename(curNode)
            if 'jpeg' in nuke.filename(curNode).lower() and '2048x1080' in nuke.filename(curNode).lower():
                outputFile = nuke.filename(curNode)
                frameFirst = int(nuke.root()['first_frame'].value())
                frameLast = int(nuke.root()['last_frame'].value())
                if os.path.exists(fxpipe.framePadReplace(outputFile, frameLast)) == False: 
                    nuke.message('Error : this output does not exist')
                    return
                #frameFirst = int(nuke.root()['first_frame'].getValue())-1
                #frameLast = int(nuke.root()['last_frame'].getValue())
                progressTask = nuke.ProgressTask("Sending to Review Room")
                progressTask.setMessage("Pushing file to Playback Machine")
                progressTask.setProgress(0)                
                fh = open('//svenplay/cache/%s.rv' % (os.path.basename(outputFile).split('.')[0]), 'w')
                fh.write('GTOa (3)\n\n')
                fh.write('sourceGroup0_source : RVFileSource(1)\n{\n media \n {\nstring movie = "%s" \n}\n}' % (outputFile))
                fh.close()
                progressTask.setProgress(50)
                #progressTask.setMessage('Pushing Shotgun Version')
                sgu = shotgunUtils.genericUtils()
                project = sgu.project(fxpipe.showName(outputFile))
                shot = sgu.shot(project,fxpipe.shotName(outputFile))
                try:
                    vData = sgu.versionCreate(project, shot, fxpipe.shotName(outputFile) + '_' + fxpipe.versionNumber(outputFile), 'Sent for Review', outputFile, frameFirst, frameLast,  task='Comp', makeThumb=True,)
                except:
                    vData = None
                progressTask.setProgress(100)
                
                if vData:
                    nuke.message('Created Version: %s' % vData['code'])
                else:
                    nuke.message('Error Creating Version')
    
    
    else:
        nuke.message ('You have not selected an AutoWrite node')
    def process(self, context):

        instances = []
        # creating instances per write node
        for node in nuke.allNodes():
            if node.Class() != "Write":
                continue

            # Determine output type
            output_type = "img"
            if node["file_type"].value() == "mov":
                output_type = "mov"

            # Create instance
            instance = pyblish.api.Instance(node.name())
            instance.data["family"] = output_type
            instance.add(node)

            instance.data["label"] = node.name()

            instance.data["publish"] = False

            # Get frame range
            start_frame = int(nuke.root()["first_frame"].getValue())
            end_frame = int(nuke.root()["last_frame"].getValue())
            if node["use_limit"].getValue():
                start_frame = int(node["first"].getValue())
                end_frame = int(node["last"].getValue())

            # Add collection
            collection = None
            try:
                path = ""
                if nuke.filename(node):
                    path = nuke.filename(node)
                path += " [{0}-{1}]".format(start_frame, end_frame)
                collection = clique.parse(path)
            except ValueError:
                # Ignore the exception when the path does not match the
                # collection.
                pass

            instance.data["collection"] = collection

            instances.append(instance)

        context.data["write_instances"] = instances

        context.data["instances"] = (context.data.get("instances", []) +
                                     instances)
Exemplo n.º 10
0
def readFromWrite():
    nodes = nuke.selectedNodes()
    for node in nodes:
        assert node.Class() == 'Write'
        filename = nuke.filename(node)

        while True:
            dir = os.path.dirname(filename)
            print("Looking for:", filename)

            try:
                fileset = nuke.getFileNameList(dir)[0]
                print("Found fileset on disk: ", fileset)
                break
            except:
                print("Version not found, searching for previous takes.")
                prefix, num = re.search(r'(v)(\d+)', filename,
                                        re.IGNORECASE).groups()
                new_ver = str(int(num) - 1).zfill(len(num))
                assert int(new_ver) > 0, "NO VERSIONS FOUND"
                filename = re.sub(r'v(\d+)', prefix + new_ver, filename)

        fileset = os.path.join(dir, fileset)
        read = nuke.createNode('Read')
        read['file'].fromUserText(fileset)
        read.setXYpos(node.xpos(), node.ypos() + 120)
Exemplo n.º 11
0
def versionChange(n, cur_ver, new_ver):
    '''change version, up/down/latest
	@n: node, obj
	@cur_ver: current version, int
	@new_ver: new version, int
	'''

    new_ver_str = '_v%03d' % new_ver
    path_ver = n['tx_dir'].value()
    path_lgt = os.path.dirname(n['tx_dir'].value())
    cur_ver_str = '_v%03d' % cur_ver
    new_path = path_ver.replace(cur_ver_str, new_ver_str)

    if os.path.isdir(new_path):
        with n:
            all_read = nuke.allNodes('Read')
            for r in all_read:
                thisFilename = nuke.filename(r)
                thisFilename = thisFilename.replace(cur_ver_str, new_ver_str)
                r['file'].setValue(thisFilename)
            n['tx_dir'].setValue(new_path)
            n['int_thisVersion'].setValue('%03d' % new_ver)

    else:
        print "No version %s found" % new_path
Exemplo n.º 12
0
def actualFilename(node):
    """
	Given a node that reads a file, returns a tuple where:
	[0] The parent/containing folder of the file
	[1] The file's name you see in nuke's panel
	[2] A real name for the file
	"""
    (dirPath, basename) = os.path.split(nuke.filename(node))

    def getFirstFrameOfSequence():
        first_frame = node["first"].value()
        if node.Class() == "Write" and (node["first"].value() == node["last"].value()):
            # For Write nodes without a render range set, assume the
            # first frame is the comp's first frame.
            first_frame = nuke.root().firstFrame()
        return first_frame

    if re.search("#+", basename):
        # NOTE: On Read nodes, for some fucky reason, if a node's file name
        # is file.%05d.jpg -- nuke.filename(node) gives you file.#####.jpg instead.
        # c = '%0' + str(len(re.findall('#',basename))) + 'd'
        # filename = re.sub('#+',c,basename) % getFirstFrameOfSequence()
        basename = nukescripts.replaceHashes(basename)
    if re.search(r"%\d+d", basename):  # Sequence files
        filename = basename % getFirstFrameOfSequence()
    else:  # Standalone/single non-sequence files
        filename = basename
    return dirPath, basename, filename
Exemplo n.º 13
0
def AutoQT():
    pan = nuke.Panel('AutoQT_by_ [email protected]')
    pan.addFilenameSearch('OUT PATH', 'output path here')
    pan.addEnumerationPulldown('Select Size', 'PAL HD 1K_Super_35(full-ap)')
    pan.show()

    Output_Path = pan.value('OUT PATH')
    QT_Size = pan.value('Select Size')

    sel = nuke.selectedNodes()

    for m in sel:

        fn = nuke.filename(m)
        fn = os.path.basename(fn)
        fn = os.path.splitext(fn)[0]
        firstFrame = m.knob('first').getValue()
        lastFrame = m.knob('last').getValue()
        print fn

        rf = nuke.createNode("Reformat")
        rf.setInput(0, m)
        rf['format'].setValue(QT_Size)
        rf['black_outside'].setValue('True')

        wr = nuke.createNode("Write")
        wr.setInput(0, rf)
        wr['file'].setValue(Output_Path + fn + ".mov")
        wr['file_type'].setValue('mov')
        wr['codec'].setValue('none')
        wr['use_limit'].setValue('True')
        wr['first'].setValue(firstFrame)
        wr['last'].setValue(lastFrame)
    return ()
Exemplo n.º 14
0
def _evaluate_path_expression(node, knob):
  knob_value = knob.value()
  # If the knob value has an open bracket, assume it's an expression.
  if '[' in knob_value:
    if node.Class() == 'Write':
      knob.setValue(nuke.filename(node))
    else:
      # Running knob.evaluate() will freeze not just expressions, but frame number as well. Use regex to search for
      # any frame number expressions, and replace them with a placeholder.
      to_eval = knob_value
      placeholders = {}
      regexs = [r'#+', r'%.*d']
      for regex in regexs:
        match = 1
        while match:
          match = re.search(regex, to_eval)
          if match:
            placeholder = '__frame%d' % (len(placeholders) + 1,)
            original = match.group()
            placeholders[placeholder] = original
            to_eval = to_eval[0:match.start()] + '{%s}' % (placeholder,) + to_eval[match.end():]
      # Set the knob value to our string with placeholders.
      knob.setValue(to_eval)
      # Now evaluate the knob to freeze the path.
      frozen_path = knob.evaluate()
      # Use our dictionary of placeholders to place the original frame number expressions back in.
      frozen_path = frozen_path.format(**placeholders)
      # Finally, set the frozen path back to the knob.
      knob.setValue(frozen_path)
Exemplo n.º 15
0
def w_create_dir():
    """ Automatically create write node directory.
	"""
    path = os.path.dirname(nuke.filename(nuke.thisNode()))
    if not os.path.isdir(path):
        os_wrapper.createDir(path)
    return path
Exemplo n.º 16
0
def st_writeFromeReadMeta(custom):
    # make sure custom param doesnt connect with values ahead of it
    if custom:
        custom = "_" + custom

    # get selected nodes
    writeNodes = nuke.selectedNodes()
    for wnode in writeNodes:
        if wnode.Class() == "Write":
            # Get top node in chain
            topnode_name = nuke.tcl("full_name [topnode %s]" % wnode.name()) 
            topnode = nuke.toNode(topnode_name) 
        
            # Path to read node
            fullPath = nuke.filename(topnode)
            pathOnly = os.path.dirname(topnode['file'].value())
            writePath = pathOnly + '/'
            
            # Focal Length
            fLength = topnode.metadata()['input/focal_length']
            focalSplit = fLength.split('/',1)
            focal = focalSplit[0]
            focal = focal + "MM"
        
            # Split up "File.jpg" to "File" and ".jpg"    
            fullPathSplit   = fullPath.split("/")
            fileName       = fullPathSplit[len(fullPathSplit)-1]
            fileNameSplit = fileName.split('.')
            
            # Define write path and assign to Write Node
            writePath = (writePath + fileNameSplit[0] + "_" + focal + custom + "." + fileNameSplit[1])
            wnode['file'].setValue(writePath)
            # Print the result
            print (wnode.name() + " : " + (wnode['file'].getValue()))
Exemplo n.º 17
0
def createWriteDir():
    '''
    This function creates a write directory automatically so the user does not have to do it.
    Supports stereo notation with %v and %V
    '''
    import nuke, os
    curnode = nuke.thisNode()
    originalFileName = nuke.filename(curnode)
    allViews = curnode.knob('views').value() # look for views in the write node
    allViews = allViews.split() # split them out
    outputFilename = []
    for view in allViews:
        fileName = originalFileName
        # check for the standard nuke view parameters
        if '%v' in fileName :
            outputFilename.append(fileName.replace('%v',view[:1]))
        if '%V' in fileName :
            outputFilename.append(fileName.replace('%V',view))
        print outputFilename
        if len(outputFilename) < 1:
            outputFilename.append(originalFileName)
        for fileName in outputFilename:
            dir = os.path.dirname( fileName )
            osdir = nuke.callbacks.filenameFilter( dir )
            if not os.path.exists( osdir ):
                os.makedirs( osdir )
                print 'Created : %s' % (osdir)
Exemplo n.º 18
0
def sendToAvconv(codec = 'dnxhd'):
	# Configuration
	renderSlug = False
	vcodec = {
		'x264' : 'libx264 -pre baseline',
		'dnxhd' : 'dnxhd -b 36M',
	}
	extension = '.mov'

	# set some variables
	fps = nuke.root().knob('fps').value()
	firstFrame = nuke.root().knob('first_frame').value()
	ss = 0 if renderSlug == True else secondsToStr(firstFrame/fps)

	# grabs the write node's file value and makes sure the path uses printf style filenames
	imgSeqPath = nukescripts.replaceHashes(nuke.filename(nuke.thisNode()))

	# generate mov path
	base, ext = os.path.splitext(os.path.basename(imgSeqPath))
	movPath =  os.path.dirname(os.path.dirname(imgSeqPath)) + '/' + re.sub('\.?%0\d+d$', '', base) + extension

	# make shell command
	enc = 'avconv -y -r %s -i \'%s\' -s \'hd1080\' -an -ss %s -vcodec %s -threads 0 \'%s\'' % (fps, imgSeqPath, ss, vcodec[codec], movPath)
	#print enc
	subprocess.Popen(shlex.split(enc), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Exemplo n.º 19
0
def launchRV():
    '''launch selected read nodes with RV'''
    path_read = [nuke.filename(n) for n in nuke.selectedNodes('Read')]

    if path_read:
        cmd = "rv -c -over %s &" % ' '.join(path_read)
        os.system(cmd)
Exemplo n.º 20
0
def remove_duplicated_read(is_show_result=True):
    """Remove duplicated read to save memory.  """

    nodes = nuke.allNodes('Read')
    nodes.sort(key=lambda n: n.ypos())
    distinct_read = []
    removed_nodes = []

    for n in nodes:
        same_node = _find_same(n, distinct_read)
        if same_node:
            dot = nuke.nodes.Dot(inputs=[same_node],
                                 label='代替: {}\n{}'.format(
                                     u(n.name()),
                                     u(nuke.filename(n))).encode('utf-8'),
                                 hide_input=True)
            dot.setXYpos(n.xpos() + 34, n.ypos() + 57)
            core.replace_node(n, dot)
            n_name = u(n.name())
            removed_nodes.append(n_name)
            u_print('用 {0} 代替 {1} , 删除 {1}。'.format(u(same_node.name()),
                                                    n_name))
            nuke.delete(n)
        else:
            distinct_read.append(n)

    if not is_show_result:
        return
    if removed_nodes:
        nuke.message('合并时删除了{}个节点: \n{}'.format(
            len(removed_nodes), ', '.join(removed_nodes)).encode('utf-8'))
    else:
        nuke.message('没有发现重复读取节点。'.encode('utf-8'))
Exemplo n.º 21
0
def freeze_node(node, view=None):
    """
    If the node has an expression, evaluate it so that the ZYNC can
    parse it. Also accounts for and retains frame number expressions.
    Should be idempotent.
    """
    knob_names = ['file', 'font']
    for knob_name in knob_names:
        file_knob = node.knob(knob_name)
        if file_knob == None:
            continue
        knob_value = file_knob.value()

        # if the file param has an open bracket, let's assume that it's an
        # expression:
        if '[' in knob_value:
            if node.Class() == 'Write':
                file_knob.setValue(nuke.filename(node))
            else:
                frozen_path = file_knob.evaluate()
                frozen_dir = os.path.split(frozen_path)[0]
                file_expr = os.path.split(knob_value)[-1]

                # sets the read node to be
                file_knob.setValue(os.path.join(frozen_dir, file_expr))

        if view:
            knob_value = knob_value.replace('%v', view.lower())
            knob_value = knob_value.replace('%V', view.upper())

            node.knob(knob_name).setValue(knob_value)
Exemplo n.º 22
0
def dpxNoAlpha():
	"""
	Do not allow DPX files to be written with alpha
	"""
	n = nuke.thisNode()
	if nuke.filename(n).endswith("dpx"):
		n['channels'].setValue("rgb")
Exemplo n.º 23
0
def createWriteDirs():
	""" Automatically create directories in Write path if path doesn't exists. """
	f = nuke.filename(nuke.thisNode())
	dirr = os.path.dirname(f)
	if not os.path.exists(dirr):
		osdir = nuke.callbacks.filenameFilter(dirr)
		os.makedirs(osdir)
Exemplo n.º 24
0
def output_to_h264(write_node=None):
    """an after render function which converts the input to h264
    """
    # get the file name
    if not write_node:
        write_node = nuke.thisNode()

    file_full_path = nuke.filename(write_node)

    # add the _h264 extension to the filename
    file_name = os.path.basename(file_full_path)
    path = file_full_path[:-len(file_name)]
    file_name_wo_ext, ext = os.path.splitext(file_name)

    # split any '.' (ex: a.%04d -> [a, %04d])
    file_name_wo_ext = file_name_wo_ext.split('.')[0]
    # add _h264
    output_file_name = file_name_wo_ext + '_h264.mov'
    output_full_path = os.path.join(path, output_file_name)

    # TODO: if it is a sequence of images rename them by creating temp soft
    #       links to each frame and then use the sequence format in ffmpeg

    # run ffmpeg in a separate thread
    t = threading.Timer(1.0,
                        convert_to_h264,
                        args=[file_full_path, output_full_path])
    t.start()
Exemplo n.º 25
0
def nk_rv(nodes=None):
	"""
	Send to RV
	SS Shift+r
	"""
	f_image = lambda node: os.path.join(nuke.actualFilename(n)[0],nuke.actualFilename(n)[-1])
	
	path = {}
	path['Write'] = f_image
	path['Read'] = f_image
	path['Precomp'] = lambda node: nuke.filename(node)
	
	inbox_rv = []
	inbox_nuke = []
	
	send_to = {}
	send_to['Read'] = inbox_rv
	send_to['Write'] = inbox_rv
	send_to['Precomp'] = inbox_nuke
	
	n = [send_to[n.Class()].append(path[n.Class()](n)) for n in nuke.selectedNodes() if n.Class() in path.keys()]

	[Popen("""nuke --nukex %s""" % p, stdout=PIPE, shell=True) for p in inbox_nuke]
	
	rv_cmd = {}
	rv_cmd[0] = lambda n: None
	rv_cmd[1] = lambda n: """%s -fullscreen "%s" """ % (os.environ['RVPATH'], n[0])
	rv_cmd[2] = lambda n: """%s -fullscreen -sessionType stack %s """ % ( os.environ['RVPATH']," ".join(n) )

	cmd = rv_cmd.get(len(inbox_rv), rv_cmd[2])(inbox_rv)
	if cmd: Popen(cmd, stdout=PIPE, shell=True)
Exemplo n.º 26
0
def _evaluate_path_expression(node, knob):
    knob_value = knob.value()
    # If the knob value has an open bracket, assume it's an expression.
    if '[' in knob_value:
        if node.Class() in WRITE_NODE_CLASSES:
            knob.setValue(nuke.filename(node))
        else:
            # Running knob.evaluate() will freeze not just expressions, but frame number as well. Use regex to search for
            # any frame number expressions, and replace them with a placeholder.
            to_eval = knob_value
            placeholders = {}
            regexs = [r'#+', r'%.*d']
            for regex in regexs:
                match = 1
                while match:
                    match = re.search(regex, to_eval)
                    if match:
                        placeholder = '__frame%d' % (len(placeholders) + 1, )
                        original = match.group()
                        placeholders[placeholder] = original
                        to_eval = to_eval[0:match.start()] + '{%s}' % (
                            placeholder, ) + to_eval[match.end():]
            # Set the knob value to our string with placeholders.
            knob.setValue(to_eval)
            # Now evaluate the knob to freeze the path.
            frozen_path = knob.evaluate()
            # Use our dictionary of placeholders to place the original frame number expressions back in.
            frozen_path = frozen_path.format(**placeholders)
            # Finally, set the frozen path back to the knob.
            knob.setValue(frozen_path)
Exemplo n.º 27
0
def rrSubmit_CreateSelectedJobs(node, jobList):
    if node['disable'].value():
        writeError("please enable the Write node")
        return

    newJob = rrJob()
    rrSubmit_fillGlobalSceneInfo(newJob)

    #if node.knob('renderUseful').value():
    #    newJob.sceneName = newJob.sceneName.replace('.nk', '_lite.nk')

    if (node['use_limit'].value()):
        newJob.seqStart = node['first'].value()
        newJob.seqEnd = node['last'].value()
    newJob.imageFileName = nuke.filename(node)
    if ((newJob.imageFileName.find("%V") >= 0)
            or (newJob.imageFileName.find("%v") >= 0)):
        newJob.maxChannels = newJob.maxChannels + 1
        newJob.channelFileName = list()
        newJob.channelFileName.append(
            string.replace(string.replace(newJob.imageFileName, "%v", "l"),
                           "%V", "left"))

        newJob.channelExtension.append("")
        newJob.imageFileName = string.replace(
            string.replace(newJob.imageFileName, "%v", "r"), "%V", "right")
        # newJob.imageDir=os.path.dirname(newJob.imageFileName)
    newJob.layer = node['name'].value()
    newJob.isActive = False
    jobList.append(newJob)
Exemplo n.º 28
0
def createWriteDir():
    '''
    This function creates a write directory automatically so the user does not have to do it.
    Supports stereo notation with %v and %V
    '''
    import nuke, os
    curnode = nuke.thisNode()
    originalFileName = nuke.filename(curnode)
    allViews = curnode.knob(
        'views').value()  # look for views in the write node
    allViews = allViews.split()  # split them out
    outputFilename = []
    for view in allViews:
        fileName = originalFileName
        # check for the standard nuke view parameters
        if '%v' in fileName:
            outputFilename.append(fileName.replace('%v', view[:1]))
        if '%V' in fileName:
            outputFilename.append(fileName.replace('%V', view))
        print outputFilename
        if len(outputFilename) < 1:
            outputFilename.append(originalFileName)
        for fileName in outputFilename:
            if fileName != '':
                dir = os.path.dirname(fileName)
                osdir = nuke.callbacks.filenameFilter(dir)
                if not os.path.exists(osdir):
                    os.makedirs(osdir)
                    print 'Created : %s' % (osdir)
Exemplo n.º 29
0
def output_to_h264(write_node=None):
    """an after render function which converts the input to h264
    """
    # get the file name
    if not write_node:
        write_node = nuke.thisNode()

    file_full_path = nuke.filename(write_node)

    # add the _h264 extension to the filename
    file_name = os.path.basename(file_full_path)
    path = file_full_path[:-len(file_name)]
    file_name_wo_ext, ext = os.path.splitext(file_name)

    # split any '.' (ex: a.%04d -> [a, %04d])
    file_name_wo_ext = file_name_wo_ext.split('.')[0]
    # add _h264
    output_file_name = file_name_wo_ext + '_h264.mov'
    output_full_path = os.path.join(path, output_file_name)

    # TODO: if it is a sequence of images rename them by creating temp soft
    #       links to each frame and then use the sequence format in ffmpeg

    # run ffmpeg in a seperate thread
    t = threading.Timer(
        1.0,
        convert_to_h264,
        args=[file_full_path, output_full_path]
    )
    t.start()
Exemplo n.º 30
0
    def process(self, context, plugin):
        import clique
        import nuke

        # Get the errored instances
        failed = []
        for result in context.data["results"]:
            if (result["error"] is not None and result["instance"] is not None
                    and result["instance"] not in failed):
                failed.append(result["instance"])

        # Apply pyblish.logic to get the instances for the plug-in
        instances = api.instances_by_plugin(failed, plugin)

        for instance in instances:
            collection = clique.assemble([nuke.filename(instance[0])],
                                         minimum_items=1,
                                         patterns=[clique.PATTERNS['frames']
                                                   ])[0][0]

            instance[0]["file"].setValue(
                collection.format("{head}{padding}{tail}"))
            instance[0]["first"].setValue(list(collection.indexes)[0])
            instance[0]["last"].setValue(list(collection.indexes)[0])
            instance[0]["origfirst"].setValue(list(collection.indexes)[0])
            instance[0]["origlast"].setValue(list(collection.indexes)[0])
def skippy():
    n = nuke.thisNode()
    currentFrame = nuke.filename(n, nuke.REPLACE)
    tmpFrame = currentFrame + ".tmp"
    try:
        n['autocrop'].value()
    except:
        autoCropOn = 0
    else:
        if n['autocrop'].value() is True:
            autoCropOn = 1
            n['autocrop'].setValue(False)
        else:
            autoCropOn = 0
    if os.path.exists(currentFrame) or os.path.exists(tmpFrame):
        #print "Frame exists: %s\t skipping..." %currentFrame
        nuke.cancel()
        if autoCropOn == 1:
            n['autocrop'].setValue(True)

    else:
        if autoCropOn == 1:
            n['autocrop'].setValue(True)
        else:
            pass
Exemplo n.º 32
0
def create_read_from_write():
    node_list = nuke.selectedNodes('Write')
    if len(node_list) == 0:
        nuke.message("You must select a WRITE node first.")
        return

    for node in node_list:
        file_knob = nuke.filename(node)
        if not file_knob:
            nuke.message(
                "No file output path on node '%s'. Add some path there and try again."
                % node.name())
            continue

        read_node = nuke.createNode("Read", inpanel=False)
        read_node.setXYpos(node.xpos(), node.ypos() + 80)
        read_node.knob("file").setValue(file_knob)

        first_frame = int(node.firstFrame())
        last_frame = int(node.lastFrame())

        read_node.knob("first").setValue(first_frame)
        read_node.knob("last").setValue(last_frame)

        read_node.knob("origfirst").setValue(first_frame)
        read_node.knob("origlast").setValue(last_frame)
Exemplo n.º 33
0
    def process(self, context, plugin):
        import clique
        import nuke

        # Get the errored instances
        failed = []
        for result in context.data["results"]:
            if (result["error"] is not None and result["instance"] is not None
               and result["instance"] not in failed):
                failed.append(result["instance"])

        # Apply pyblish.logic to get the instances for the plug-in
        instances = api.instances_by_plugin(failed, plugin)

        for instance in instances:
            collection = clique.assemble(
                [nuke.filename(instance[0])],
                minimum_items=1,
                patterns=[clique.PATTERNS['frames']]
            )[0][0]

            instance[0]["file"].setValue(
                collection.format("{head}{padding}{tail}")
            )
            instance[0]["first"].setValue(list(collection.indexes)[0])
            instance[0]["last"].setValue(list(collection.indexes)[0])
            instance[0]["origfirst"].setValue(list(collection.indexes)[0])
            instance[0]["origlast"].setValue(list(collection.indexes)[0])
Exemplo n.º 34
0
def freeze_node(node, view=None):
    """
    If the node has an expression, evaluate it so that the ZYNC can
    parse it. Also accounts for and retains frame number expressions.
    Should be idempotent.
    """
    knob_names = ['file', 'font']
    for knob_name in knob_names:
        file_knob = node.knob(knob_name)
        if file_knob == None:
            continue
        knob_value = file_knob.value()

        # if the file param has an open bracket, let's assume that it's an
        # expression:
        if '[' in knob_value:
            if node.Class() == 'Write':
                file_knob.setValue(nuke.filename(node))
            else:
                frozen_path = file_knob.evaluate()
                frozen_dir = os.path.split(frozen_path)[0]
                file_expr = os.path.split(knob_value)[-1]

                # sets the read node to be
                file_knob.setValue(os.path.join(frozen_dir, file_expr))

        if view:
            knob_value = knob_value.replace('%v', view.lower())
            knob_value = knob_value.replace('%V', view.upper())

            node.knob(knob_name).setValue(knob_value)
Exemplo n.º 35
0
def readFromWrite():

    nodes = nuke.selectedNodes()
    if len(nodes) < 1:
        print('No nodes selected')
    else :
        foundWrites = False
        writeNodes = []
        for node in nodes:
            if node.Class() == 'Write':
                writeNodes.append(node)
                foundWrites = True
        
        if foundWrites == True:  # we found some writes
            
            for node in writeNodes:
                nodeRead = nuke.nodes.Read() # create a read node
                nodeRead['file'].setValue(nuke.filename(node)) #set the filename
                if node['use_limit'].getValue() == 1: #check to see if there is a range and set the values in the read node
                    nodeRead['first'].setValue(int(node['first'].getValue()))
                    nodeRead['last'].setValue(int(node['last'].getValue()))
                else: # no range on the write?  take a stab at using the range from the script value
                    nodeRead['first'].setValue(int(nuke.root()['first_frame'].getValue()))
                    nodeRead['last'].setValue(int(nuke.root()['last_frame'].getValue()))       
                nodeRead.setXpos(node.xpos()) #let's set the position 
                nodeRead.setYpos(node.ypos()+50)
                nodeRead['premultiplied'].setValue(node['premultiplied'].getValue()) # use premult if checked
                nodeRead['raw'].setValue(node['raw'].getValue()) # use raw if checked
        else:
            
            print('No Writes Found in Node Selection')
Exemplo n.º 36
0
def rrSubmit_CreateSingleJobs_Node(jobList, noLocalSceneCopy, node):
    nViews = nuke.views()
    if node["disable"].value():
        return
    pathScripted = ""
    writeNode = node
    writeNodeName = writeNode["name"].value()
    if isGizmo(node):
        with node:
            gList = nuke.allNodes("Write") + nuke.allNodes("DeepWrite")
            for gnode in gList:
                if gnode["disable"].value():
                    continue
                pathScripted = gnode["file"].value()
                if (pathScripted == None) or (len(pathScripted) < 3):
                    continue
                writeNode = gnode
                if isScriptedOutput(pathScripted, True):
                    noLocalSceneCopy[0] = True
    else:
        pathScripted = writeNode["file"].value()
        if (pathScripted == None) or (len(pathScripted) < 3):
            return
    newJob = rrJob()
    rrSubmit_fillGlobalSceneInfo(newJob)
    useStereoFlag = False
    if len(nViews) == 2:
        useStereoFlag = True
        newJob.imageStereoR = nViews[0]
        newJob.imageStereoL = nViews[1]
    if writeNode["use_limit"].value():
        newJob.seqStart = writeNode["first"].value()
        newJob.seqEnd = writeNode["last"].value()
    newJob.imageFileName = nuke.filename(writeNode)
    if (newJob.imageFileName == None) or (len(newJob.imageFileName) < 3):
        return
    if newJob.seqStart == newJob.seqEnd and (newJob.imageFileName.find("#") < 0):
        newJob.imageSingleOutput = True

    if useStereoFlag:
        if newJob.imageFileName.find("%V") >= 0:
            newJob.imageFileName = string.replace(newJob.imageFileName, "%V", "<Stereo>")
        elif newJob.imageFileName.find("%v") >= 0:
            newJob.imageFileName = string.replace(newJob.imageFileName, "%v", "<Stereo>")
            newJob.imageStereoR = newJob.imageStereoR[0]
            newJob.imageStereoL = newJob.imageStereoL[0]
        else:
            useStereoFlag = False
    elif (newJob.imageFileName.find("%V") >= 0) or (newJob.imageFileName.find("%v") >= 0):
        for vn in range(1, len(nViews)):
            newJob.maxChannels = newJob.maxChannels + 1
            newJob.channelFileName.append(
                string.replace(string.replace(newJob.imageFileName, "%v", nViews[vn][0]), "%V", nViews[vn])
            )
            newJob.channelExtension.append("")
        newJob.imageFileName = string.replace(string.replace(newJob.imageFileName, "%v", nViews[0][0]), "%V", nViews[0])
    newJob.layer = writeNodeName
    newJob.isActive = False
    jobList.append(newJob)
Exemplo n.º 37
0
def open_with_djv():
    pattern_items = [
        "C:" + os.sep, "Program Files", "djv-[0-9].[0-9].[0-9]-Windows-64",
        "bin", "djv_view.exe"
    ]
    executables = get_regex_files(pattern_items)
    args = [executables[0], nuke.filename(nuke.selectedNode(), nuke.REPLACE)]
    subprocess.Popen(args)
Exemplo n.º 38
0
def createOutDirs():
    trgDir = os.path.dirname(nuke.filename(nuke.thisNode()))
    
    if not os.path.isdir(trgDir):
        try:
            os.makedirs(trgDir)
        except: 
            pass  
Exemplo n.º 39
0
def open_node_in_file_browser(node):
    """opens the node path in filebrowser
    """
    file_full_path = nuke.filename(node)
    # get the path
    file_name = os.path.basename(file_full_path)
    path = file_full_path[:-len(file_name)]
    open_in_file_browser(path)
Exemplo n.º 40
0
def writeNoOverwrite():
	""" Automatically create directories in Write path if path doesn't exists. """
	if nuke.thisNode()['no_overwrite'].value():
		file_to_be_rendered = nuke.filename(nuke.thisNode(), nuke.REPLACE)
		if os.path.exists(file_to_be_rendered):
			msg = "File already exists: %s" % file_to_be_rendered
			try: raise RuntimeError(msg)
			except RuntimeError as e: print e
Exemplo n.º 41
0
    def process(self, context):
        import os

        import nuke

        instances = []
        # creating instances per write node
        for node in nuke.allNodes():
            if node.Class() != "WriteGeo":
                continue

            # Create cache instance
            instance = api.Instance(node.name())
            instance.data["family"] = "cache"
            instance.data["families"] = ["writegeo"]
            instance.add(node)
            instance.data["label"] = node.name()
            instance.data["publish"] = False
            instance.data["output_path"] = nuke.filename(node)
            instances.append(instance)

            # Create camera instance
            instance = api.Instance(node.name())
            instance.data["family"] = "camera"
            instance.data["families"] = ["writegeo"]
            instance.add(node)
            instance.data["label"] = node.name()
            instance.data["publish"] = False
            path, ext = os.path.splitext(nuke.filename(node))
            instance.data["output_path"] = "{0}_camera{1}".format(path, ext)
            instances.append(instance)

            # Create geometry instance
            instance = api.Instance(node.name())
            instance.data["family"] = "geometry"
            instance.data["families"] = ["writegeo"]
            instance.add(node)
            instance.data["label"] = node.name()
            instance.data["publish"] = False
            path, ext = os.path.splitext(nuke.filename(node))
            instance.data["output_path"] = "{0}_geometry{1}".format(path, ext)
            instances.append(instance)

        context.data["instances"] = (
            context.data.get("instances", []) + instances
        )
Exemplo n.º 42
0
def createWriteDir():
	file = nuke.filename(nuke.thisNode())
	dir = os.path.dirname( file )
	osdir = nuke.callbacks.filenameFilter( dir )
	try:
		os.makedirs(osdir)
	except OSError:
		pass
Exemplo n.º 43
0
def open_node_in_file_browser(node):
    """opens the node path in filebrowser
    """
    file_full_path = nuke.filename(node)
    # get the path
    file_name = os.path.basename(file_full_path)
    path = file_full_path[:-len(file_name)]
    open_in_file_browser(path)
Exemplo n.º 44
0
def djv_this(node, start, end, incr, view):
    '''
    Plays the selected node sequence in DJV.
    You can get DJV at:
        http://djv.sourceforge.net/
        
    Use:
        djv_this( <node_object>, <start_frame>, <end_frame>, <frame_increment>, <view_name> )
    '''

    global djv_path

    if not os.access(djv_path, os.X_OK):
        raise RuntimeError('DJV cannot be executed "%s".' % djv_path)

    if len(view) > 1:
        raise RuntimeError('DJV currently does not support stereo sequences')

    filename = nuke.filename(node)
    if filename is None or filename == '':
        raise RuntimeError(
            'DJV cannot be executed on "%s", expected to find a file and there was none.'
            % node.fullName())

    try:
        padding = re.findall('%[0-9]*d', filename).pop()
        range = (padding % start)
        filename = re.sub('%[0-9]*d', range, filename)
    except:
        raise RuntimeError(
            'djv_this.py was unable to form the necessary string with: %s' %
            filename)

    cmd = []

    cmd.append(os.path.normpath(djv_path))

    ### DJV Options Start ################################################
    cmd.append(os.path.normpath(filename))
    # cmd.append( '-file_layer (value)' ) #layer name
    cmd.append('-file_seq_auto True')
    cmd.append('-file_proxy 1/2')  #Proxy scale: 1/2, 1/4, 1/8
    cmd.append('-file_cache True')  # Cache: True, False.
    # cmd.append( '-window_fullscreen' ) #Start in full screen
    # cmd.append("-window_toolbar False") # Toolbar controls: False, True.
    # cmd.append("-window_playbar False") # Window controls: False, True.
    # cmd.append("-view_grid None") # Grid overlay: None, 1x1, 10x10, 100x100.
    # cmd.append("-view_hud True") # Heads up display: True, False.
    cmd.append("-playback Forward")  # Playback: Stop, Forward, Reverse.
    # cmd.append("-playback_frame (value)") # Frame.
    cmd.append("-playback_speed " + str(int(nuke.root().knob('fps').value())))
    # cmd.append("-playback_timer (value)") # Timer: Sleep, Timeout. Value: Sleep.
    # cmd.append("-playback_timer_resolution (value)") # Timer resolution (seconds): 0.001.
    cmd.append("-time_units Frames")  # Time units: Timecode, Frames.
    ### DJV Options End ##################################################

    print ' '.join(cmd)
    subprocess.Popen(' '.join(cmd), shell=True)
Exemplo n.º 45
0
    def process(self, context):
        import os

        import nuke

        instances = []
        # creating instances per write node
        for node in nuke.allNodes():
            if node.Class() != "WriteGeo":
                continue

            # Create cache instance
            instance = api.Instance(node.name())
            instance.data["family"] = "cache"
            instance.data["families"] = ["writegeo"]
            instance.add(node)
            instance.data["label"] = node.name()
            instance.data["publish"] = False
            instance.data["output_path"] = nuke.filename(node)
            instances.append(instance)

            # Create camera instance
            instance = api.Instance(node.name())
            instance.data["family"] = "camera"
            instance.data["families"] = ["writegeo"]
            instance.add(node)
            instance.data["label"] = node.name()
            instance.data["publish"] = False
            path, ext = os.path.splitext(nuke.filename(node))
            instance.data["output_path"] = "{0}_camera{1}".format(path, ext)
            instances.append(instance)

            # Create geometry instance
            instance = api.Instance(node.name())
            instance.data["family"] = "geometry"
            instance.data["families"] = ["writegeo"]
            instance.add(node)
            instance.data["label"] = node.name()
            instance.data["publish"] = False
            path, ext = os.path.splitext(nuke.filename(node))
            instance.data["output_path"] = "{0}_geometry{1}".format(path, ext)
            instances.append(instance)

        context.data["instances"] = (context.data.get("instances", []) +
                                     instances)
Exemplo n.º 46
0
def CheckOutputPath():
    import nuke
    file = nuke.filename(nuke.thisNode())
    dir = os.path.dirname(file)
    osdir = nuke.callbacks.filenameFilter(dir)
    try:
        os.makedirs(osdir)
    except OSError:
        pass
Exemplo n.º 47
0
 def __createRenderDirectory(cls, writeNode):
     """
     Create the render directory for a write node.
     """
     renderFilePath = nuke.filename(writeNode)
     if renderFilePath:
         renderFolder = os.path.dirname(renderFilePath)
         if not os.path.exists(renderFolder):
             os.makedirs(renderFolder)
Exemplo n.º 48
0
def makeCurrent():
    file = nuke.filename(nuke.thisNode(), nuke.REPLACE)
    scriptFilePath = nuke.root().name()

    if '/increments' in scriptFilePath:
        regex = re.compile("_[0-9]{3}[.]")
        incr = regex.findall(scriptFilePath)[0]
        scriptFilePath = scriptFilePath.replace('/increments',
                                                '').replace(incr, '.')

    fileName = file.split('/')[-1]
    outName = fileName.split("_")[1]
    outExt = fileName.split(".")[-1]
    if outExt == 'jpg':
        outExt = 'jpeg'
    scriptName = scriptFilePath.split('/')[-1]
    newFile = scriptFilePath.split(
        'nuke')[0] + '_renders/nuke/' + scriptName.replace(
            '.nk', '') + '/' + outName + '/' + outExt + '/' + fileName

    print 'fileName', fileName
    print 'outName', outName
    print 'outExt', outExt
    print 'scriptName', scriptName

    regex = re.compile("_v[0-9]{2,9}")
    vers = regex.findall(file)
    for ver in vers:
        ver = ver.replace("_", "")
        newFile = newFile.replace(ver, 'current')

    print 'newFile', newFile

    thumbFile = file.replace('/exr/', '/exr/.thumbs/').replace('.exr', '.jpeg')
    newThumbFile = newFile.replace('/exr/',
                                   '/exr/.thumbs/').replace('.exr', '.jpeg')

    newDir = os.path.dirname(newFile)
    newThumbDir = os.path.dirname(newThumbFile)
    try:
        os.makedirs(newDir)
    except:
        pass
    try:
        os.makedirs(newThumbDir)
    except:
        pass
    try:
        shutil.copyfile(file, newFile)
    except:
        print 'noCopy file'
        pass
    try:
        shutil.copyfile(thumbFile, newThumbFile)
    except:
        print 'noCopy file'
        pass
Exemplo n.º 49
0
def main():
    file = nuke.filename(nuke.thisNode())
    dir = os.path.dirname(file)
    osdir = nuke.callbacks.filenameFilter(dir)
    if not os.path.isdir(osdir):
        try:
            os.makedirs(osdir)
        except:
            pass
Exemplo n.º 50
0
def findTopNode(n=nuke.selectedNode()):
    '''
    Returns a string of the top node
    '''

    topnode_name = nuke.tcl("full_name [topnode %s]" % n.name())
    topnode_file = nuke.filename(nuke.toNode(topnode_name))

    return topnode_name
Exemplo n.º 51
0
def showReadWrite ():
    """
    This panel gives you the number of reads that are either selected or in the entire script.
    Additionally, it tells you the path of either selected nodes or all read/write nodes.
    """
    reads = []
    readfiles = []
    writes = []
    writefiles = []
    nodes = nuke.selectedNodes('Read')
    wnodes = nuke.selectedNodes('Write')
    if len(nodes) < 1:
        nodes = nuke.allNodes('Read')
    if len(wnodes) < 1:
        wnodes = nuke.allNodes('Write')
    
    for node in nodes:
        if nuke.filename(node) not in readfiles:
            reads.append ({'file':nuke.filename(node),'start':node['first'].value(),'end':node['last'].value()})
            readfiles.append (nuke.filename(node))
    for node in wnodes:
        if nuke.filename(node) not in writefiles:
            writes.append(nuke.filename(node))
    
    read = ''
    output = ''
    writeOutput = ''
    x = 0
    for read in reads:
        x = x + 1
        output = '%s%s %d-%d\n' % (output, read['file'], int(read['start']), int(read['end']))
    if len(writes) > 0:
        for write in writes:
            writeOutput =  '%s%s\n' % (writeOutput, write)

    p = nuke.Panel('Read Paths', setWidth=650)
    
    p.addSingleLineInput('Script Name:',  nuke.root()['name'].value())
    p.addMultilineTextInput ('Read Paths:',output)
    p.addMultilineTextInput ('Write Paths:',writeOutput)
    p.addSingleLineInput ('Total Selected:', x)

    p.setWidth(1000)
    p.show()
Exemplo n.º 52
0
def djv_this( node, start, end, incr, view ):
    
    '''
    Plays the selected node sequence in DJV.
    You can get DJV at:
        http://djv.sourceforge.net/
        
    Use:
        djv_this( <node_object>, <start_frame>, <end_frame>, <frame_increment>, <view_name> )
    '''
    
    
    global djv_path

    if not os.access( djv_path, os.X_OK ):
        raise RuntimeError( 'DJV cannot be executed "%s".' % djv_path )
        
    if len( view ) > 1:
        raise RuntimeError( 'DJV currently does not support stereo sequences' )
        
    filename = nuke.filename( node )
    if filename is None or filename == '':
        raise RuntimeError( 'DJV cannot be executed on "%s", expected to find a file and there was none.' % node.fullName() )
        
    try:
        padding = re.findall( '%[0-9]*d', filename ).pop()
        range = ( padding % start )
        filename = re.sub( '%[0-9]*d', range, filename )
    except:
        raise RuntimeError( 'djv_this.py was unable to form the necessary string with: %s' % filename )
        
    cmd = []
    
    cmd.append( os.path.normpath( djv_path ) )

    ### DJV Options Start ################################################
    cmd.append( os.path.normpath( filename ) )
    # cmd.append( '-file_layer (value)' ) #layer name
    cmd.append( '-file_seq_auto True' )
    cmd.append( '-file_proxy 1/2' ) #Proxy scale: 1/2, 1/4, 1/8
    cmd.append( '-file_cache True' ) # Cache: True, False.
    # cmd.append( '-window_fullscreen' ) #Start in full screen
    # cmd.append("-window_toolbar False") # Toolbar controls: False, True.
    # cmd.append("-window_playbar False") # Window controls: False, True.
    # cmd.append("-view_grid None") # Grid overlay: None, 1x1, 10x10, 100x100.
    # cmd.append("-view_hud True") # Heads up display: True, False.
    cmd.append("-playback Forward") # Playback: Stop, Forward, Reverse.
    # cmd.append("-playback_frame (value)") # Frame.
    cmd.append("-playback_speed " + str( int( nuke.root().knob( 'fps' ).value() ) ) )
    # cmd.append("-playback_timer (value)") # Timer: Sleep, Timeout. Value: Sleep.
    # cmd.append("-playback_timer_resolution (value)") # Timer resolution (seconds): 0.001.
    cmd.append("-time_units Frames") # Time units: Timecode, Frames.
    ### DJV Options End ##################################################
    
    print ' '.join(cmd)
    subprocess.Popen( ' '.join( cmd ), shell=True )
Exemplo n.º 53
0
def createWriteDir(): 
    import nuke, os 
    file = nuke.filename(nuke.thisNode()) 
    dir = os.path.dirname( file ) 
    osdir = nuke.callbacks.filenameFilter( dir ) 
    try: 
        os.makedirs( osdir ) 
        return 
    except: 
        return 
Exemplo n.º 54
0
def exrCompressionTest():
        compressList = ['None', 'RLE', 'ZIP', 'ZIP 16 lines', 'PIZ', 'PXR24', 'B44', 'B44A']
        try:
                n = nuke.selectedNode()
                if nuke.selectedNode().Class()!='Read' or nuke.selectedNode() == "" :
                        nuke.message('No Read node selected.')
                elif os.path.splitext(nuke.filename(nuke.selectedNode()))[-1]!=".exr" :
                        nuke.message('Selected Read is not an EXR')
                else:
                        file = nuke.filename(n, nuke.REPLACE)
                        fd = open(file, 'rb')
                        header = fd.read(4096)
                        index = header.find('compression')
                        comp =ord(header[(index+28):(index+29)])
                        compressMethod = compressList[comp]
                        print compressMethod
                        nuke.message('EXR compression is %s' %(compressMethod))

        except ValueError:
                nuke.message('Please select a Read node...')
Exemplo n.º 55
0
def collect():
    path =  change_path(nuke.filename(nuke.thisNode(), nuke.REPLACE))
    dir, file = os.path.split( path )
    dir_list = dir.split('/')
    for i in range(len(dir_list)):
        if dir_list[i] and dir_list[i][0].lower() == 's' and dir_list[i][1:4].isdigit():
            #print i, dir_list[i]
            string =  '%s' % '/'.join(dir_list[0:i+1])
            print string
    if os.path.exists(path):
        print '...'
Exemplo n.º 56
0
def createWriteDir():
  import nuke, os, errno
  file = nuke.filename(nuke.thisNode())
  dir = os.path.dirname( file )
  osdir = nuke.callbacks.filenameFilter( dir )
  # cope with the directory existing already by ignoring that exception
  try:
    os.makedirs( osdir )
  except OSError, e:
    if e.errno != errno.EEXIST:
      raise
Exemplo n.º 57
0
def do():
	"""main"""
	sns =  nuke.selectedNodes()
	for sn in sns:
		filepath = nuke.filename(sn)
		if filepath is not None:
			filepath = 'file:' + os.path.dirname(filepath)
			currentView = nuke.activeViewer().view()
			filepath = filepath.replace(r'%v', currentView[0])
			filepath = filepath.replace(r'%V', currentView)
			print filepath
			openurl.start(filepath)
Exemplo n.º 58
0
def pathExplorer():
	'''
	Open filename's path on explorer from Read or Write selected nodes
	'''
	import os, subprocess
	
	sel = nuke.selectedNodes()
	for node in sel:
		if node.Class() == 'Read' or node.Class() == 'Write':
			File = nuke.filename(node)
			path = os.path.dirname(File)
			subprocess.Popen('explorer "%s"' % path.replace('/', '\\'))