Example #1
0
    def testLensDistortAgainstLensDistortOp(self):
        """Test that the output of the Cortex LensDistortOp and the LensDistort node are the same.\n"""

        paths = self.__paths()
        for p in paths.keys():
            self.assertTrue(os.path.exists(paths[p]))

        outputPath = self.__outputPath()
        if os.path.exists(outputPath):
            os.remove(outputPath)

            # Set the default format to be something fun.
        nuke.root()["format"].fromScript("1144 862 0 0 1144 862 2 CortexTestAlexaProxyAnamorphic(2.66)")

        r = nuke.createNode("Read")

        # Create a LensDistort node.
        l = nuke.createNode("ieLensDistort")
        l["mode"].setValue(IECore.LensModel.Undistort)
        l.setInput(0, r)

        # Set the parameters of the lens distort node.
        l["lensFileSequence"].fromScript(os.path.abspath("test/IECore/data/StandardRadialLens.cob"))

        # Create a write node.
        w = nuke.createNode("Write")
        w.setInput(0, l)
        w["file"].setText(outputPath)

        # Create the op that we will compare the result of the nuke LensDistort node with.
        lensDistortOp = IECore.LensDistortOp()
        lensDistortOp["mode"].setValue(IECore.LensModel.Undistort)
        lensDistortOp["lensModel"].setValue(self.__testLens())

        for path in paths.keys():
            # Update the read node.
            r["file"].setText(paths[path])

            if path == "path":
                # When the format is the same as the data window, nuke doesn't create a black border around the image.
                # As a result, we shouldn't create one using our LensDistortOp either.
                lensDistortOp["boundMode"].setValue(IECore.WarpOp.BoundMode.Clamp)
            else:
                lensDistortOp["boundMode"].setValue(IECore.WarpOp.BoundMode.SetToBlack)

                # Write out the result of the LensDistort so that we can compare it to the output of the cortex op.
            nuke.execute(w, 1, 1)

            img = IECore.Reader.create(paths[path]).read()
            lensDistortOp["input"].setValue(img)

            cortexImg = lensDistortOp()
            nukeImg = IECore.Reader.create(outputPath).read()

            # Assert that the two images are almost identical.
            # We expect a little bit of error as the cortex op uses a different sampling filter to the nuke node.
            imageDiffOp = IECore.ImageDiffOp()
            imageDiffOp["alignDisplayWindows"].setValue(True)
            res = imageDiffOp(imageA=cortexImg, imageB=nukeImg)
            self.assertFalse(res.value)
Example #2
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 #3
0
def _createObjWriter(tmpWriterName, tmpfilePath, selectedNode, curFrame, alembic, frames):
    
    w = nuke.createNode('WriteGeo', inpanel=False)
    w.setName(tmpWriterName)
    w["file"].setValue(tmpfilePath.replace("\\", "/"))
    w.setInput(0, selectedNode)
    
    try:
        
        if alembic:
            w["use_limit"].setValue(True)
            w["first"].setValue(int(frames[0]))
            w["last"].setValue(int(frames[1]))
            w["file_type"].setValue(1)
            nuke.execute(tmpWriterName, int(frames[0]), int(frames[1]), 1)
        else:
            w["file_type"].setValue(3)
            nuke.execute(tmpWriterName, curFrame, curFrame, 1)
            
    except RuntimeError as e:
        
        print str(e)
        return False
    
    return True
Example #4
0
def newFlixPanelFromCurrentViewerImage(nukeStudioViewer = True):
    print "Adding a new FLIX panel from current Viewer"
    uniquePath = getFlixTempFolder()+"flix_"+getUniqueString()+"_"

    lastTempNumber = "1"
    filePath = uniquePath+lastTempNumber+".xml";
    fileRef_out = open(filePath, 'w');
    dialogue = "I do not believe in fairies" #getDialogue(psdDocument);
    fileRef_out.write("<flixImport waitForSource='1' multipleSetups='1'>\n");

    # Depending on the action, we can grab the active Nuke (comp) or NukeStudio Viewer image
    if nukeStudioViewer:
        currentImage = currentViewer().image()
        tempFilePath = uniquePath+lastTempNumber+"_.FLIXTEMP.png"
        currentImage.save(tempFilePath)
    else:
        # It's the Nuke Comp image
        vn = nuke.activeViewer().node()
        frame = vn['frame'].value()
        tempFilePath = uniquePath+lastTempNumber+"_.FLIXTEMP.png"
        vn['file'].setValue(tempFilePath)
        nuke.execute(vn, frame, frame)

    fileRef_out.write("<image originalFile='"+getActiveDocumentFilename()+"' dialogue='I do not believe in Fairies' imageFile='"+tempFilePath+"'/>\n");
    fileRef_out.write("</flixImport>\n");
    fileRef_out.close()
    sendFileToFlix(filePath)
Example #5
0
 def exportObj(self, filePy, objects, filePath, objPath):
     objPathList = []        
     filePy.write("# importing obj files...\n\n")        
     for node in objects:
         
         for i in nuke.allNodes():
             i['selected'].setValue(0)
     
         print "processing "+node.name()+" ..."
         node['selected'].setValue(1)
         writeObj = nuke.createNode('WriteGeo', inpanel=False)
         writeObj['name'].setValue(node.name()+"_export")
         writeObj['file'].setValue(objPath+node.name()+".obj")
         writeObj['file_type'].setValue('obj')
         # writeObj['views'].setValue('main')
         
         objPathList.append(objPath+node.name()+".obj")
         nuke.execute(writeObj, int(nuke.root()['first_frame'].getValue()), int(nuke.root()['first_frame'].getValue()))
         for i in nuke.allNodes():
             i['selected'].setValue(0)
         writeObj['selected'].setValue(1)
         nukescripts.node_delete()
             
     for object in objPathList:
         filePy.write("cmds.file('"+object+"', i = True, type = 'OBJ', ra = True)\n")
         
     filePy.write("\n")
     filePy.write("# make group of all the *_Mesh nodes ...\n\n")
     filePy.write("cmds.select('*_Mesh')\n")
     filePy.write("cmds.group(name = 'geo_GRP')\n\n")
     filePy.write("# renaming the files without '_Mesh' ...\n\n")
     filePy.write("meshes = cmds.ls('*_Mesh')\n")
     filePy.write("for node in meshes:\n")
     filePy.write("	cmds.rename(node, node[-0:-5])\n\n")
Example #6
0
	def testExecuteWithImageInput( self ) :
	
		fnOH = IECoreNuke.FnOpHolder.create( "test", "imagePrimitiveInOut", 1 )
		
		self.assertEqual( fnOH.node().minimumInputs(), 1 )
		self.assertEqual( fnOH.node().maximumInputs(), 1 )
		
		check = nuke.nodes.CheckerBoard()
		
		fnOH.node().setInput( 0, check )
		
		# get the image as output by the op
		image = fnOH.execute()

		# write the same image direct to disk without using the op
		write = nuke.nodes.Write()
		write.setInput( 0, check )
		write.knob( "file" ).setValue( "test/IECoreNuke/check.exr" )
		write.knob( "channels" ).setValue( "rgba" )
		nuke.execute( write, 1, 1 )
		
		# check that they are the same in terms of size and channel data.
		# allow a slight difference due to one having been saved as half float and reloaded.
		
		image2 = IECore.EXRImageReader( "test/IECoreNuke/check.exr" ).read()
		self.assertEqual( IECore.ImageDiffOp()( imageA = image, imageB = image2, maxError = 0.001 ).value, False )
Example #7
0
 def createTimelineFromDroppedClip(self, clipPath):
     nuke.scriptClear()
     nuke.scriptReadFile('/Users/ant/.nuke/Python/Startup/cut_detection/cutDetector.nk')
     self.inputNode = nuke.toNode('InputClip')
     self.cutDetector = nuke.toNode('CutDetector')
     self.inputNode['file'].fromUserText(clipPath)
     self.first = self.inputNode['first'].value()
     self.last = self.inputNode['last'].value()
     nuke.execute("CutDetector.CurveTool1", self.first, self.last)
Example #8
0
    def setUp(self):

        paths = self.__paths()
        for p in paths.keys():
            if os.path.exists(p):
                os.remove(p)

                # Set the default format to be something fun.
        nuke.root()["format"].fromScript("1144 862 0 0 1144 862 2 CortexTestAlexaProxyAnamorphic(2.66)")

        # Create a colourful test image that we will distort.
        n1 = nuke.createNode("ColorWheel")
        n2 = nuke.createNode("ColorBars")
        n3 = nuke.createNode("CheckerBoard2")
        m1 = nuke.createNode("Merge2")
        m2 = nuke.createNode("Merge2")
        m1.setInput(0, n1)
        m1.setInput(1, n2)
        m2.setInput(0, m1)
        m2.setInput(1, n3)
        m2["operation"].setValue(1)

        # Create a write node so that we can save the image to disk.
        w = nuke.createNode("Write")
        w.setInput(0, m2)
        w["file"].setText(paths["path"])

        # Crop the image and generate another test image.
        c = nuke.createNode("Crop")
        c["box"].setValue((29, -74, 374, 448))
        c.setInput(0, m2)

        w2 = nuke.createNode("Write")
        w2.setInput(0, c)
        w2["file"].setText(paths["croppedPath"])

        # Create the test files.
        nuke.execute(w, 1, 1)
        nuke.execute(w2, 1, 1)

        # Finally, read back the images and offset their display windows to make the
        # tests even more interesting...
        offsetImg = IECore.Reader.create(paths["path"]).read()
        offsetDisplayWindow = IECore.Box2i(
            offsetImg.displayWindow.min + IECore.V2i(-261, 172), offsetImg.displayWindow.max + IECore.V2i(-261, 172)
        )
        offsetImg.displayWindow = offsetDisplayWindow
        IECore.Writer.create(offsetImg, paths["offsetPath"]).write()

        croppedOffsetImg = IECore.Reader.create(paths["croppedPath"]).read()
        offsetDisplayWindow = IECore.Box2i(
            croppedOffsetImg.displayWindow.min + IECore.V2i(120, -100),
            croppedOffsetImg.displayWindow.max + IECore.V2i(120, -100),
        )
        croppedOffsetImg.displayWindow = offsetDisplayWindow
        IECore.Writer.create(croppedOffsetImg, paths["croppedOffsetPath"]).write()
 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 #10
0
def _createWriter(name, filePath, selectedNode, curFrame):
    
    n = nuke.createNode('Write', inpanel=False)
    n.setName(name)
    n["file"].setValue(filePath.replace("\\", "/"))
    n.setInput(0, selectedNode)
    
    try:
        nuke.execute(name, curFrame, curFrame, 1)
    except RuntimeError as e:
        print str(e)
        return False
    
    return True
Example #11
0
def executeSelection(firstFrame=nuke.frame(), lastFrame=nuke.frame()):
    nodes = nuke.selectedNodes()
    if nodes:
        try:
            for node in nodes:
                nuke.frame(firstFrame)
                print "executing", node.name(), nuke.frame()
                print 'writing', node['file'].getValue()
                nuke.execute(node, firstFrame, lastFrame)
        except:
            print 'cannot execute', node.name(), '...'
        print 'all done.'
    else:
        nuke.message("Please select some write nodes!")
    def execute(self, instance):
        import nuke

        # Get frame range
        node = instance[0]
        first_frame = nuke.root()["first_frame"].value()
        last_frame = nuke.root()["last_frame"].value()

        if node["use_limit"].value():
            first_frame = node["first"].value()
            last_frame = node["last"].value()

        # Render frames
        nuke.execute(node.name(), int(first_frame), int(last_frame))
Example #13
0
def animatedSnapFunc(nodeToSnap, vertexSelection, knobsToAnimate, knobsToVerify, minVertices = 1, snapFunc = s3d.translateToPointsVerified):
  '''A wrapper to call the relevant snap functions within a framerange loop'''
  temp = None
  try:
    s3d.verifyNodeToSnap(nodeToSnap, knobsToVerify)
    
    # verify vertex selection once before the loop
    s3d.verifyVertexSelection(vertexSelection, minVertices)
    
    # now ask for a framerange
    frames = getFrameRange()
   
    if not frames:  return  # Exit eary if cancelled or empty framerange
    
    # Add a CurveTool for the forced-evaluation hack
    temp = nuke.nodes.CurveTool()
    
    # Set the anim flag on knobs
    for knob in [nodeToSnap[x] for x in knobsToAnimate]:
      # reset animated status
      if knob.isAnimated():
        knob.clearAnimated()
      knob.setAnimated()  

    # Set up Progress Task  
    task = nuke.ProgressTask("animatedSnap3D")
    task.setMessage("Matching position of %s to selected vertices" % nodeToSnap.name())
    
    # Loop through the framerange
    for frame in frames:    
      if task.isCancelled():
        break
      
      # Execute the CurveTool node to force evaluation of the tree
      nuke.execute(temp, frame, frame)
      
      # this is repetitive, but the vertex selection needs to be computed again
      # in order to get the vertices at the right context (time)
      vertexSelection = s3d.getSelection()
      
      # this is also repetitive. Selection should be already verified
      # but checking again in case topology has changed between frames
      s3d.verifyVertexSelection(vertexSelection, minVertices)
      
      # Call the passed snap function from the nukescripts.snap3d module
      snapFunc(nodeToSnap, vertexSelection)
    
  except ValueError, e:
    nuke.message(str(e))
Example #14
0
def main():
    readNodes = nuke.allNodes('Read')

    readNodePair = readPair(readNodes)

    lrPairs = gernerateLRPair(readNodePair)
        
    for lrPair in lrPairs:
        output = stereoVerticalCombineOutput(lrPair)
        startframe = lrPair[0]['first'].getValue()
        endframe = lrPair[0]['last'].getValue()

        nuke.execute( output, int(startframe), int(endframe) )
    
    os.startfile("e:/nuke")
Example #15
0
def saveImage(sel, renderTo, filetype):

	w = nuke.nodes.Write()
	w.setInput(0,sel[0])
	w.setXpos(sel[0].xpos())
	w.setYpos(sel[0].ypos()+150)
	w.knob("name").setValue("capture")
	w.knob("use_limit").setValue(True)
	w.knob("first").setValue(nuke.frame())
	w.knob("last").setValue(nuke.frame())
	w.knob("file_type").setValue(filetype)
	w.knob("file").setValue(renderTo+"capture_{time}.{ext}".format(time=getTime(), ext=filetype))
	nuke.execute(w,nuke.frame(),nuke.frame())
	nuke.delete(w)

	openFolder(renderTo)
Example #16
0
def BreakDowner(listNodes = nuke.selectedNodes()):

    if listNodes is None or listNodes == []:
        raise TypeError, 'You have not selected any nodes !'

    listWriteNode = []
    for node in listNodes:
        nodeName = node['name'].value()
        wName = 'Write_'+nodeName
        w = nuke.nodes.Write()
        w['name'].setValue(wName)
        w.setInput(0, node)
        listWriteNode.append(w)

    project = h.currentProject(filePath)
    print project
    print h.PROJECTS
    shotNumber = h.currentShot(filePath)#.split('/')[-2]
    print shotNumber
    pathBKD = os.path.join(h.PROJECTS, project, h.SHOTS, h.RENDER, shotNumber)#, 'Breakdown')
    if not os.path.exists(pathBKD):
        try:
            os.mkdir(pathBKD)
        except IOError:
            print 'Error IO'
    pathBKD = os.path.join(pathBKD, 'Breakdown')
    try:
        if not os.path.exists(pathBKD):
            os.mkdir(pathBKD)
        else:
            print 'Already Created'
    except IOError:
        print 'An error occured whil creating the dir'
        return -1

    #We set the correct path for the write nodes
    renderOrder = 1
    for w in listWriteNode:
        fileKnob = os.path.join(pathBKD, w['name'].value())
        fileKnob += '.'+str(nuke.frame())+'.exr'

        w['file_type'].setValue('exr')

        w['file'].setValue(fileKnob)

        #write
        nuke.execute(w['name'].value(), int(nuke.frame()), int(nuke.frame()))
Example #17
0
def exr_split():




    #Path for source and where to
    path_for_jpg = "H://Image Test//Nuke Test"
    path_sequence_to_read = "H://Image Test//testEtienne.exr"

    layers = []
    write_number = 1


    #Creation du read node et attribution du path
    read_node = nuke.createNode('Read')
    read_node.knob("file").setValue(path_sequence_to_read)

    #Query pour le first et last frame
    first_frame = read_node.knob("first").value()
    last_frame = read_node.knob("last").value()


    channels = read_node.channels()

    for c in channels:      #Pour tout les channel dans le node
        layers.append(c.split('.')[0])  #Separer les channels  I.E.: RGBA.Red devient [RGBA,Red] et on prend RGBA
    layers = list(set(layers))      #Eliminer les doubles dans la liste


    for lay in layers:
        if lay == "rgba" or lay == "depth":     #Pour layers qui ne sont pas les layers de base RGBA et Depth
            pass
        else:
            #Creer le shuffle et le write
            shuffle_node = nuke.nodes.Shuffle( label= str(lay), inputs= [read_node])
            write_node = nuke.nodes.Write(inputs= [shuffle_node])

            #Linker le shuffle au channel
            shuffle_node['in'].setValue( lay )

            #Changer le filepath du write et executer le rendu
            write_node.knob("file").setValue(path_for_jpg + "/" + lay + ".jpg")
            nuke.execute("Write" + str(write_number), first_frame, last_frame)

            #Iterer le numero du node write
            write_number = write_number + 1
Example #18
0
	def testCreationOfZBack( self ) :

		if not IECore.withDeepEXR :
			return
		
		## This test is disabled because Nuke is seg faulting when executing
		## a DeepWrite from command line mode. The same test in an interactive
		## Nuke session works as expected. Last tested in Nuke8.0v3.
		## \todo: Re-enable this test when the Nuke bug is fixed.
		return
		
		# Create a DeepReader to read the deep EXR.
		reader = nuke.createNode( "DeepRead" )
		reader["file"].setText( DeepImageReaderTest.__smokeWithoutZBack )

		# Write it back out. We do this because nuke's DeepSample node is un
		writer = nuke.createNode( "DeepWrite" )
		writer["file"].setText( DeepImageReaderTest.__output )
		nuke.execute( writer, 1, 1 )
		
		# Read the image back in and check the values of it's ZBack channel.
		reader = IECore.EXRDeepImageReader( DeepImageReaderTest.__output )
		header = reader.readHeader()
		resolution = reader['dataWindow'].size() + IECore.V2i( 1 )
			
		self.assertEqual( set( header['channelNames'] ), set( [ 'R', 'G', 'B', 'A', 'ZBack' ] ) )

		for y in range( 0, resolution[0] ) :
			for x in range( 0, resolution[1] ) :
				
				p = reader.readPixel( x, y )
				n = p.numSamples()
				zBackIndex = p.channelIndex( 'ZBack' )

				if n >= 1 :
					n = n - 1

				for s in range( 0, n ) : 
					front = p.getDepth( s )
					back = p.getDepth( s+1 )
					actualBack = p.channelData( s )[ zBackIndex ]
					self.assertEqual( back, actualBack )
Example #19
0
def getMinMax( srcNode, channel='depth.Z' ):
    '''
    Return the min and max values of a given node's image as a tuple
    args:
       srcNode  - node to analyse
       channels  - channels to analyse. This can either be a channel or layer name
    '''
    MinColor = nuke.nodes.MinColor( channels=channel, target=0, inputs=[srcNode] )
    Inv = nuke.nodes.Invert( channels=channel, inputs=[srcNode])
    MaxColor = nuke.nodes.MinColor( channels=channel, target=0, inputs=[Inv] )
    
    curFrame = nuke.frame()
    nuke.execute( MinColor, curFrame, curFrame )
    minV = -MinColor['pixeldelta'].value()
    
    nuke.execute( MaxColor, curFrame, curFrame )
    maxV = MaxColor['pixeldelta'].value() + 1
    
    for n in ( MinColor, MaxColor, Inv ):
        nuke.delete( n )
    return minV, maxV
Example #20
0
def outputmov(src,out):
    #global log
    try:
        
        readNode = nuke.createNode('Read')
        writeNode = nuke.createNode('Write')
        readNode.knob('file').setValue(src)
        filePath = nukescripts.replaceHashes(readNode.knob('file').getValue()).replace('%d', '%01d')
        padRe = re.compile('%0(\d+)d')
        padMatch = padRe.search(filePath)
        padSize = int(padMatch.group(1)) 
   
        if padMatch:
            frameList = sorted(glob.iglob(padRe.sub('[0-9]' * padSize, filePath)))
            if frameList:
                missing = 0
                firstVal = os.path.splitext(frameList[0])[0][-padSize:] 
                lastVal = os.path.splitext(frameList[-1])[0][-padSize:] 
                readNode.knob('first').setValue(int(firstVal))
                readNode.knob('last').setValue(int(lastVal))
                readNode.knob('origfirst').setValue(int(firstVal))
                readNode.knob('origlast').setValue(int(lastVal))
            else:
                missing = 1
                errFlg = 1
    
        readNode.knob('colorspace').setValue("rec709")
        #readNode.knob("reload").execute()
        writeNode.knob('file_type').setValue("mov")
        writeNode.knob('file').setValue(out)
        writeNode.knob('colorspace').setValue("rec709")
        writeNode.knob('meta_codec').setValue("png")
        writeNode.knob('mov64_fps').setValue(25)
        nuke.execute('Write1', int(firstVal),int(lastVal))
        nuke.delete(writeNode)
        nuke.delete(readNode)
    except:
        print 'Error'
        nuke.delete(writeNode)
        nuke.delete(readNode)
Example #21
0
def custom_execute_panel(_list, exceptOnError = True):
	"""
	Override the default way Nuke executes multiple Write nodes to allow
	each Write node's addBeforeRender and addBeforeFrameRender to execute
	code *specific to that node* before they are rendered.
	"""
	_list = nuke.allNodes("Write") if _list[0]	== nuke.root() else _list
	_list = [n for n in _list if not (n['disable'].value() or n['reading'].value())]
	if len(_list) == 0:
		nuke.message("No renderable Write nodes!")
		return
	else:
		_list = sorted(_list,key=lambda x: x['render_order'].value())
		nuke.scriptSave("")
		for n in _list:
			if n['use_limit'].value():
				first,last = n['first'].value(),n['last'].value()
			else:
				first,last = nuke.root().firstFrame(),nuke.root().lastFrame()
			print "Render started: %s" % n.name()
			nuke.execute(n.name(),int(first),int(last))
			print "Render completed: %s" % n.name()
Example #22
0
def renderQTS(node=nuke.thisNode()):
    verCheck(node)
    if verCheck(node) == "pass" and dpxPath(node) != 'break':
        # Assign Variables
        renderNode = node
        qtPath = outputPath()
        node.begin()
        switch = nuke.toNode("Controller")['which']
        origSwitchValue = switch.animation(0).expression()
        editRender = nuke.toNode("Editorial_RenderNode")
        vfxRender = nuke.toNode("VFX_RenderNode")
        # If QTs already exist, remove them
        for the_file in os.listdir(qtPath):
            file_path = os.path.join(qtPath, the_file)
            if os.path.isfile(file_path) and shotName(node) in the_file:
                os.remove(file_path)
        # Begin rendering
        switch.setExpression(str(0))
        # Sets off specific write nodes depending on the user input
        """ This part needs a callback to stop the function if the render is canceled """
        warning = "In order to render a Quicktime file you must have the DPX input connected to an input."
        if node.input(1):
            try:
                if numQTS == 1:
                    nuke.execute(editRender, (nuke.root().firstFrame()-startFrame), (nuke.root().lastFrame()))
                else:
                    nuke.execute(vfxRender, (nuke.root().firstFrame()-startFrame), (nuke.root().lastFrame()))
                    nuke.execute(editRender, (nuke.root().firstFrame()-startFrame), (nuke.root().lastFrame()))
            except RuntimeError:
                switch.setExpression(origSwitchValue)
                node.end()
                nuke.message(warning)
        else:
            nuke.message(warning)
        switch.setExpression(origSwitchValue)
        node.end()
    else:
        pass
Example #23
0
	def execute( self ) :

		nuke.execute( self.node(), nuke.frame(), nuke.frame() )
		return _IECoreNuke._opHolderExecuteResult()
Example #24
0
    else:
        parser.error("can't find matching resolution for " + options.resolution)
else:
    parser.error("can't parse resolution: " + options.resolution)
    
output_movie = nuke.toNode("output_movie")
output_movie["file"].fromUserText(os.path.abspath(options.outputPath))

ext = os.path.splitext(options.outputPath)[1][1:]
if ext == "mov":
    output_movie["format"].setValue("QuickTime / MOV (mov)")
else:
    parser.error("Unsupported output file type: " + ext)

if output_format.width() == 1920 and output_format.height() == 1080 and options.fps in (23.976, 24) and options.codec == "DNxHD 115":
    output_movie["file_type"].setValue("ffmpeg")
    output_movie["fps"].setValue(options.fps)
    output_movie["codec"].setValue("VC3/DNxHD")
    output_movie["bitrate"].setValue(120586240)
else:
    parser.error("Unsupported resolution/codec/fps combination: {width}x{height}/{codec}/{fps}".format(
                           width=output_format.width(),
                           height=output_format.height(),
                           codec=options.codec,
                           fps=options.fps))

if options.onlyDump:
    nuke.scriptSaveAs("/usr/tmp/dump.nk");
else:
    nuke.execute(output_movie, options.frameStart-1, options.frameEnd)
     except Exception, e:
         errors.append("Submit to Screening Room failed - %s" % e)
 
 #render local---
 elif output_name == 'render_local':
     
     #rendering---
     #getting write node
     write_node = item.get("other_params", dict()).get("node")
     
     #getting frame range
     firstframe=nuke.toNode( "root" )['first_frame'].value()
     lastframe=nuke.toNode( "root" )['last_frame'].value()
     
     #render write node
     nuke.execute(write_node,int(firstframe),int(lastframe),1)
     
     #not validating renders atm, might be a problem?---
     
     #publishing files---
     # publish write-node rendered sequence                
     try:
         (sg_publish, thumbnail_path) = self._publish_write_node_render(task, 
                                                                        write_node, 
                                                                        write_node_app, 
                                                                        primary_publish_path, 
                                                                        sg_task, 
                                                                        comment, 
                                                                        progress_cb)
         
         # keep track of our publish data so that we can pick it up later in review
Example #26
0
def corn3D():
    import nuke
    u = nuke.selectedNodes()
    x = 0
    for u in u:
        x=x+1
    
    if x == 3:  
        # here are basic stuff i will use later frame range and a table    
        frame = nuke.frame()
        panel = nuke.Panel("Card to track")
        first = nuke.Root().knob('first_frame').getValue()
        first = int(first)
        first = str(first)
        last = nuke.Root().knob('last_frame').getValue()
        last = int(last)
        last = str(last)
        basicRange = first+"-"+last
        panel.addSingleLineInput("Range:", basicRange)
        panel.addEnumerationPulldown("Output:", "Tracker CornerPin CornerPin(matrix) All ")
        panel.addSingleLineInput("Ref frame:", frame)
        panel.addBooleanCheckBox('Translate Only', False)
        panel.show()
    
        basicRange = panel.value("Range:")
        refFrame = panel.value("Ref frame:")
        Output = panel.value("Output:")
        Axis = panel.value("Translate Only")
    
    
        refFrame = float(refFrame)
        rangeA = basicRange.split("-")[0]
        rangeA=int(rangeA)
        rangeB = basicRange.split("-")[1]
        rangeB=int(rangeB)
        rangeA=int(rangeA)
        rangeB=int(rangeB)
        
        #here coming the main part where tracker and corner pin are created 
        if Axis == False:
            n = nuke.selectedNodes("Card2")
            for n in n:

                dep = n.dependencies(nuke.INPUTS)[0]
                name = dep['name'].value()
                w = '[value ' + name + '.bbox.w]'
                h = '[value ' + name + '.bbox.h]'
                width = nuke.expression(w)
                heght = nuke.expression(h)
                aspect =  heght/width

                x = n['xpos'].value()
                y = n['ypos'].value()
                unifscale = n['uniform_scale'].value()
                scalingx = n['scaling'].value(0)
                scalingy = n['scaling'].value(1)
                trans = n['translate'].value()
                rot = n['rotate'].value()

                traA = n['translate'].isAnimated()
                rotA = n['rotate'].isAnimated()

                labelC = n['label'].value()
                mainA = nuke.nodes.Axis()

                #mainA['translate'].setValue(trans)
                #mainA['rotate'].setValue(rot)
                mainA['xform_order'].setValue(1)
                if traA is True:
                    mainA['translate'].copyAnimations(n['translate'].animations())
                else:
                    mainA['translate'].setValue(trans)
                
                if rotA is True:
                    mainA['rotate'].copyAnimations(n['rotate'].animations())
                else:
                    mainA['rotate'].setValue(rot)



                mainA['name'].setValue("mainA")
                mainA['xpos'].setValue(x)
                mainA['ypos'].setValue(y)
                
                LU = nuke.nodes.Axis()
                LU['xform_order'].setValue(1)
                LU['translate'].setValue([-0.5*unifscale*scalingx,aspect*0.5*unifscale*scalingy,0])
                LU.setInput(0,mainA)
                LU['name'].setValue('LU')
                LU['xpos'].setValue(x)
                LU['ypos'].setValue(y)        
                
                RU = nuke.nodes.Axis()
                RU['xform_order'].setValue(1)

                RU['translate'].setValue([0.5*unifscale*scalingx,aspect*0.5*unifscale*scalingy,0])
                RU.setInput(0,mainA)
                RU['name'].setValue('RU')
                RU['xpos'].setValue(x)
                RU['ypos'].setValue(y)
                
                LL = nuke.nodes.Axis()
                LL['translate'].setValue([-0.5*unifscale*scalingx,aspect*-0.5*unifscale*scalingy,0])
                LL.setInput(0,mainA)
                LL['name'].setValue('LL')
                LL['xpos'].setValue(x)
                LL['ypos'].setValue(y)
                
                
                RL= nuke.nodes.Axis()
                RL['translate'].setValue([0.5*unifscale*scalingx,aspect*-0.5*unifscale*scalingy,0])
                RL.setInput(0,mainA)
                RL['name'].setValue('RL')
                RL['xpos'].setValue(x)
                RL['ypos'].setValue(y)
            
            n = nuke.selectedNodes()
            for n in n:
                if 'fstop' in n.knobs():
                    Cam = n
                elif 'orientation' in n.knobs():
                    print "."
                else:
                    BG = n 
            
            LUP = nuke.nodes.Reconcile3D()
            LUP.setInput(2,LU)
            LUP.setInput(1,Cam)
            LUP.setInput(0,BG)
            LUP['name'].setValue("P4")
            LUP['xpos'].setValue(x)
            LUP['ypos'].setValue(y)
            
            RUP = nuke.nodes.Reconcile3D()
            RUP.setInput(2,RU)
            RUP.setInput(1,Cam)
            RUP.setInput(0,BG)
            RUP['name'].setValue("P3")
            RUP['xpos'].setValue(x)
            RUP['ypos'].setValue(y)
            
            LLP = nuke.nodes.Reconcile3D()
            LLP.setInput(2,LL)
            LLP.setInput(1,Cam)
            LLP.setInput(0,BG)
            LLP['name'].setValue("P1")
            LLP['xpos'].setValue(x)
            LLP['ypos'].setValue(y)    
            
            RLP = nuke.nodes.Reconcile3D()
            RLP.setInput(2,RL)
            RLP.setInput(1,Cam)
            RLP.setInput(0,BG)
            RLP['name'].setValue("P2")
            RLP['xpos'].setValue(x)
            RLP['ypos'].setValue(y)
        
        
            n = nuke.nodes.Tracker3()
            n['enable1'].setValue(1)
            n['enable2'].setValue(1)
            n['enable3'].setValue(1)
            n['enable4'].setValue(1)
            
            P1 = nuke.toNode("P1")
            nuke.execute(P1,rangeA,rangeB)
            P1p = P1['output'].value()
            
            P2 = nuke.toNode("P2")
            nuke.execute(P2,rangeA,rangeB)
            P2p = P2['output'].value()
            
            P3 = nuke.toNode("P3")
            nuke.execute(P3,rangeA,rangeB)
            P3p = P3['output'].value()
            
            P4 = nuke.toNode("P4")
            nuke.execute(P4,rangeA,rangeB)
            P4p = P4['output'].value()
            
            n['track1'].copyAnimations(P1['output'].animations())
            n['track2'].copyAnimations(P2['output'].animations())
            n['track3'].copyAnimations(P3['output'].animations())
            n['track4'].copyAnimations(P4['output'].animations())
            n['use_for1'].setValue(7)
            n['use_for2'].setValue(7)
            n['use_for3'].setValue(7)
            n['use_for4'].setValue(7)
        
            n['xpos'].setValue(x+100)
            n['ypos'].setValue(y)
            n['label'].setValue(labelC)
        
            # corner pin 
            corner = nuke.nodes.CornerPin2D()  
            corner['to1'].copyAnimations(P1['output'].animations())
            corner['to2'].copyAnimations(P2['output'].animations())
            corner['to3'].copyAnimations(P3['output'].animations())
            corner['to4'].copyAnimations(P4['output'].animations())
            P1val = P1['output'].getValueAt(refFrame)
            P2val = P2['output'].getValueAt(refFrame)
            P3val = P3['output'].getValueAt(refFrame)
            P4val = P4['output'].getValueAt(refFrame)
            corner['from1'].setValue(P1val)
            corner['from2'].setValue(P2val)
            corner['from3'].setValue(P3val)
            corner['from4'].setValue(P4val)
            corner['xpos'].setValue(x+200)
            corner['ypos'].setValue(y)
            refFrame = int(refFrame)
            refFrame = str(refFrame)
            corner["label"].setValue("ref frame: " + refFrame)
        
           
            # cleanup    
            mainA = nuke.toNode("mainA")
            LU = nuke.toNode("LU")
            RU = nuke.toNode("RU")
            LL = nuke.toNode("LL")
            RL = nuke.toNode("RL")
        
            nuke.delete(mainA)
            nuke.delete(LU)
            nuke.delete(RU)
            nuke.delete(LL)
            nuke.delete(RL)
            nuke.delete(P1)
            nuke.delete(P2)
            nuke.delete(P3)
            nuke.delete(P4)
            if Output == "Tracker":
                nuke.delete(corner)
            if Output == "CornerPin":
                nuke.delete(n)
            if Output == "CornerPin(matrix)" or Output == "All":
                print "fdsfdsfsdf"
                projectionMatrixTo = nuke.math.Matrix4()
                projectionMatrixFrom = nuke.math.Matrix4()

                #dir(projectionMatrix)
                theCornerpinNode = corner
                theNewCornerpinNode = nuke.nodes.CornerPin2D()
                theNewCornerpinNode['transform_matrix'].setAnimated()

                imageWidth = float(theCornerpinNode.width())
                imageHeight = float(theCornerpinNode.height())

                first = rangeA                                
                last = rangeB
                frame = first
                while frame<last+1:
                    to1x = theCornerpinNode['to1'].valueAt(frame)[0]
                    to1y = theCornerpinNode['to1'].valueAt(frame)[1]
                    to2x = theCornerpinNode['to2'].valueAt(frame)[0]
                    to2y = theCornerpinNode['to2'].valueAt(frame)[1]
                    to3x = theCornerpinNode['to3'].valueAt(frame)[0]
                    to3y = theCornerpinNode['to3'].valueAt(frame)[1]
                    to4x = theCornerpinNode['to4'].valueAt(frame)[0]
                    to4y = theCornerpinNode['to4'].valueAt(frame)[1] 
                    
                   
                    from1x = theCornerpinNode['from1'].valueAt(frame)[0]
                    from1y = theCornerpinNode['from1'].valueAt(frame)[1]
                    from2x = theCornerpinNode['from2'].valueAt(frame)[0]
                    from2y = theCornerpinNode['from2'].valueAt(frame)[1]
                    from3x = theCornerpinNode['from3'].valueAt(frame)[0]
                    from3y = theCornerpinNode['from3'].valueAt(frame)[1]
                    from4x = theCornerpinNode['from4'].valueAt(frame)[0]
                    from4y = theCornerpinNode['from4'].valueAt(frame)[1]

                    projectionMatrixTo.mapUnitSquareToQuad(to1x,to1y,to2x,to2y,to3x,to3y,to4x,to4y)
                    projectionMatrixFrom.mapUnitSquareToQuad(from1x,from1y,from2x,from2y,from3x,from3y,from4x,from4y)
                    theCornerpinAsMatrix = projectionMatrixTo*projectionMatrixFrom.inverse()
                    theCornerpinAsMatrix.transpose()
                    
                    a0 = theCornerpinAsMatrix[0]
                    a1 = theCornerpinAsMatrix[1]
                    a2 = theCornerpinAsMatrix[2]
                    a3 = theCornerpinAsMatrix[3]    
                    a4 = theCornerpinAsMatrix[4]
                    a5 = theCornerpinAsMatrix[5]
                    a6 = theCornerpinAsMatrix[6]
                    a7 = theCornerpinAsMatrix[7]   
                    a8 = theCornerpinAsMatrix[8]
                    a9 = theCornerpinAsMatrix[9]
                    a10 = theCornerpinAsMatrix[10]
                    a11 = theCornerpinAsMatrix[11]    
                    a12 = theCornerpinAsMatrix[12]
                    a13 = theCornerpinAsMatrix[13]
                    a14 = theCornerpinAsMatrix[14]
                    a15 = theCornerpinAsMatrix[15]

                    theNewCornerpinNode['transform_matrix'].setValueAt(a0,frame,0)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a1,frame,1)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a2,frame,2)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a3,frame,3)    
                    theNewCornerpinNode['transform_matrix'].setValueAt(a4,frame,4)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a5,frame,5)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a6,frame,6)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a7,frame,7)    
                    theNewCornerpinNode['transform_matrix'].setValueAt(a8,frame,8)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a9,frame,9)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a10,frame,10)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a11,frame,11)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a12,frame,12)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a13,frame,13)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a14,frame,14)
                    theNewCornerpinNode['transform_matrix'].setValueAt(a15,frame,15)
                    

                    theNewCornerpinNode['xpos'].setValue(x+300)
                    theNewCornerpinNode['ypos'].setValue(y)
                    theNewCornerpinNode['label'].setValue("matrix")
                    
                    frame = frame + 1
            if Output == "CornerPin(matrix)":
                nuke.delete(corner)
                nuke.delete(n)
       # here is a code for Reconcile only
        else:
            n = nuke.selectedNodes("Card2")
            for n in n:
                x = n['xpos'].value()
                y = n['ypos'].value()        
                trans = n['translate'].value()
                rot = n['rotate'].value()
                scalex = n['scaling'].value(0)
                scaley = n['scaling'].value(1)
                labelC = n['label'].value()
                mainA = nuke.nodes.Axis()
                mainA['translate'].setValue(trans)
                mainA['rotate'].setValue(rot)
                mainA['name'].setValue("mainA")
                mainA['xpos'].setValue(x)
                mainA['ypos'].setValue(y)
            
            n = nuke.selectedNodes()
            for n in n:
                if 'fstop' in n.knobs():
                    Cam = n
                elif 'orientation' in n.knobs():
                    print "."
                else:
                    BG = n 
            
            LUP = nuke.nodes.Reconcile3D()
            LUP.setInput(2,mainA)
            LUP.setInput(1,Cam)
            LUP.setInput(0,BG)
            LUP['name'].setValue("rec")
            LUP['xpos'].setValue(x)
            LUP['ypos'].setValue(y)
                
            n = nuke.nodes.Tracker3()
            n['enable1'].setValue(1)
            
            P1 = nuke.toNode("rec")
            nuke.execute(LUP,rangeA,rangeB)
            P1p = P1['output'].value()
    
            n['track1'].copyAnimations(LUP['output'].animations())
            n['xpos'].setValue(x+100)
            n['ypos'].setValue(y)
            n['label'].setValue(labelC)
                   
            # cleanup    
            mainA = nuke.toNode("mainA")
            rec = nuke.toNode("rec")     
            nuke.delete(mainA)
            nuke.delete(rec)

    else:
        nuke.message("upps... I think you forgot to select Camera+BG+Card") 
Example #27
0
def smartRender():

    sel = nuke.selectedNodes()

    if len(sel) > 0:

        # create and show panel
        p = createPanel()

        # getting and setting the path
        r = nuke.root()["name"].value()  # root
        if r != "":

            # save script
            nuke.scriptSave()

            p.show()

            renderChannels = p.value("channels")
            renderFiletype = p.value("filetype")
            renderFromFrame = float(p.value("render from:"))
            renderToFrame = float(p.value("render to:"))
            importRender = p.value("import render when finished")

            rArray = r.split("/")
            rootLast = rArray[len(rArray) - 1]
            rArray.pop()
            renderpath = "/".join(rArray)
            nameArray = rootLast.split(".")
            nameAndFolder = nameArray[0]
            renderTo = renderpath + "/" + nameAndFolder

            print renderpath

            # split up to new location
            renderToArr = renderTo.split("%s" % scriptPath)
            # keep only project path
            renderTo = renderToArr[0]

            # append renderpath and artist
            renderToFromArtist = renderTo + renderPath + "/" + artist
            # renderTo apend folder with name of the script
            renderTo = renderToFromArtist + "/" + nameAndFolder
            renderProjectDirTemp = renderToFromArtist + "/" + nameAndFolder
            renderProjectDirArr = renderProjectDirTemp.split("@")
            renderProjectDir = renderProjectDirArr[0]

            projectNameArr = renderProjectDir.split("/")
            projectName = projectNameArr.pop()

            time = "@" + renderProjectDirArr[1]

            # set render up if not canceled
            if renderChannels is not None:

                # create folder if not exist
                if not os.path.isdir(renderProjectDir + "/" + projectName + time):
                    os.makedirs(str(renderProjectDir + "/" + projectName + time))

                # create write node
                wr = nuke.nodes.Write(name="smart Render", inputs=sel, postage_stamp=True)
                wr.knob("file").setValue(
                    renderProjectDir + "/" + projectName + time + "/" + nameAndFolder + "_%04d." + renderFiletype
                )
                wr.knob("channels").setValue(renderChannels)
                wr.knob("file_type").setValue(renderFiletype)
                wr.knob("use_limit").setValue(True)
                wr.knob("first").setValue(renderFromFrame)
                wr.knob("last").setValue(renderToFrame)

                # write note
                if p.value("note") != "":
                    fobj_out = open(renderProjectDir + "/" + projectName + time + "/_rendernote.txt", "w")
                    fobj_out.write(p.value("note"))
                    fobj_out.close()

                # autoexecute
                autoexecute = p.value("autoexecute")
                if autoexecute == True:
                    nuke.execute(wr, renderFromFrame, renderToFrame)
                    nuke.delete(wr)
                    nuke.message("smart Render finished")

                    # auto import
                    if importRender == True:
                        r = nuke.nodes.Read()
                        r.knob("name").setValue("smart rendered %s" % nameAndFolder)
                        r.knob("file").setValue(
                            renderProjectDir
                            + "/"
                            + projectName
                            + time
                            + "/"
                            + nameAndFolder
                            + "_%04d."
                            + renderFiletype
                        )
                        r.knob("first").setValue(renderFromFrame)
                        r.knob("last").setValue(renderToFrame)
                    else:
                        pass

                else:
                    pass
            else:
                pass

            # save, create new script so the script of the rendered version won't get changed from here
            smartSaver()
        else:
            nuke.message(
                "You haven't safed your nuke project. Please make sure to save your project first in order to proceed."
            )

    else:
        nuke.message("Please select a node from where you want to render from")
Example #28
0
    errorExit("Scene open error:\n" + str(sys.exc_info()[1]))

# Try to process read nodes:
readnodes = options.rnode.split(",")
for nodename in readnodes:
    readnode = nuke.toNode(nodename)
    if readnode is None:
        errorExit('Read "%s" not found.' % nodename)

    if readnode.Class() != "Read":
        errorExit('Node "%s" class is not "Read".' % nodename)

    readnode["file"].setValue(sequence)
    readnode["first"].setValue(frame_first)
    readnode["last"].setValue(frame_last)

    if options.colorspace != "":
        readnode["colorspace"].setValue(options.colorspace)

# Try to process write nodes:
writenode = nuke.toNode(options.xnode)
if writenode is None:
    errorExit('Node "%s" not found.' % options.xnode)
if writenode.Class() != "Write":
    errorExit('Node "%s" class is not "Write".' % options.xnode)
writenode["file"].setValue(output)
writenode["fps"].setValue(options.fps)

# Execute process:
nuke.execute(writenode, frame_first, frame_last)
def MultiChannelSplitSgtk():
    '''
    main function
    split the selected read node in separate channel layers
    if set create separate folders and write nodes 
    '''
    selectedNodes = nuke.selectedNodes()
    lenSelectedNodes= len(selectedNodes)
    shuffles=[]
    renderTo=""
    p_renderLoc=None

    if len(selectedNodes)>0:
        
        p=createPanel()
        if p.show():
            if p.value("prepare for output?") == True:
                p_renderLoc = createPanel_renderloc()
                p_renderLoc.show()
            
            
            
            #main procedure
            #create shuffle, shuffle channel in, curvetool crop, create cropnode and paste that information in, delete crop node
            for readNode in selectedNodes:
                if readNode.Class()=="SgtkRead":
                    uniqueLayers = getUniqueChannelLayerList(readNode)
            
                    for channelLayer in uniqueLayers:
                        shuffleNode = nuke.nodes.Shuffle(name="Shuffle_"+channelLayer)        
                        shuffles.append(shuffleNode.name())
                        shuffleNode.knob("in").setValue(channelLayer)
                        shuffleNode.setInput(0,readNode)
                        
                        #auto crop if selected
                        if p.value("auto crop?")==True:
                            curveNode = nuke.nodes.CurveTool(name="Autocrop_"+channelLayer, inputs = [shuffleNode], operation="Auto Crop")
                            curveNode.knob("ROI").setValue([0,0,readNode.width(),readNode.height()])
                            nuke.execute(curveNode, readNode.knob("first").value(), readNode.knob("last").value())
                            cropNode = nuke.nodes.Crop(name="Crop_"+channelLayer, inputs = [curveNode])
                            cropNode.knob("hide_input").setValue(True)
                            cropNode.knob("box").copyAnimations(curveNode.knob("autocropdata").animations())
                            nuke.delete(curveNode)
                            cropNode.knob("postage_stamp").setValue(True)
                    
                        #create folders for all layer and create write node for every shuffle                       
                        if p_renderLoc!=None:
							renderTo = p_renderLoc.value("render to: ")
							#createFolder
							createFolders(renderTo+"/"+channelLayer)            
                            
							#create write node
							write = nuke.nodes.Write()
							write.knob("file_type").setValue("exr")
							write.knob("file").setValue(renderTo+channelLayer+"/"+channelLayer+"_%04d.exr")
							write.knob("compression").setValue("Zip (16 scanlines)")
							write.knob("channels").setValue("rgba")
 
							if p.value("auto crop?")==True:       
								write.setInput(0,cropNode) 
							else:
								write.setInput(0,shuffleNode) 
                    
                else:
                    nuke.message("No read node selected")
            
            #hide all created shuffle inputs
            for shuffleNode in shuffles:
                if p.value("auto crop?")==False:
                	temp = nuke.toNode(shuffleNode)
                	temp.knob("hide_input").setValue(True)
                	temp.knob("postage_stamp").setValue(True)

            
            nuke.message("Finished shuffling channels and autocropping them")
    else:
            nuke.message("Please select a read node first")
Example #30
0
def createNodesAndWrite():
    print "Preparing nuke to start converting... please wait"
    count = 1
    total = (len(pairs))

    #create read and write for each pair of file paths
    #this can result in a massive script with hundreds of nodes,
    #but as there's no GUI, nuke doesn't care

    for pair in pairs:
        r = nuke.nodes.Read(file = pair[0])
        w = nuke.nodes.Write()

        w['file'].fromUserText(pair[1])#ensures other knobs are activated
        w.setInput(0, r)   

        #set up ideal settings for certain formats
        if format == "jpg" or format == "jpeg":
            w['_jpeg_quality'].setValue(1)
        elif format == "exr":
            w['compression'].setValue('Zip (1 scanline)')
            w['datatype'].setValue('16 bit half')

        #set amount of channels to match input
        if len(r.channels()) > 3:
            w['channels'].setValue('rgba')
        else:
            w['channels'].setValue('rgb')

    #execute all write nodes
    start_time = time.time()

    for w in nuke.allNodes('Write'):

        #clear the terminal of previous output
        os.system('cls' if os.name=='nt' else 'clear')

        #print info about this file and time estimation
        print "---------------------------------"
        print "Image %s of %s" %(count,total)
        print w.input(0)['file'].value().split(inputPath).pop()
        print w['file'].value().split(outputPath).pop()
   
        elapsedTime = time.time() - start_time        
        timeRemaining = ((elapsedTime / count) * (total - count))

        if timeRemaining >=0:
            m, s = divmod(timeRemaining, 60)
            h, m = divmod(m, 60)
            
            print "Est. time remaining: %d:%02d:%02d" % (h, m, s)
            print "---------------------------------"

        #create the output folder/subfolder if not there
        thisPath = os.path.dirname(w['file'].value())
        if not (os.path.exists(thisPath)):
            try:
                os.makedirs(thisPath)
            except:
                print "Problem creating output folder: %s" %(thisPath)
                break

        #execute node
        nuke.execute(w.name(),1,1)

        #delete the read and write to clear some memory
        try:
            r = w.input(0)
            nuke.delete(r)
            nuke.delete(w)
        except:
            print "Couldn't delete nodes"

        count+=1

    #all files converted, clear terminal and present results
    os.system('cls' if os.name=='nt' else 'clear')
    m, s = divmod(elapsedTime, 60)
    h, m = divmod(m, 60)
    print "-----------FINISHED!----------"
    print "%s image(s) converted" %(total)
    print "Total time taken: %d:%02d:%02d" % (h, m, s)
    print "------------------------------"