def get_nodes(filter_type=None, selected=False):
    """
    Return list of all write nodes in DAG.
    """

    # selected
    if (selected):
        # all nodes (also group content)
        node_list = nuke.allNodes(recurseGroups=True)
        # selected_nodes
        node_list = [node for node in node_list if (node.isSelected())]
    # all
    else:
        node_list = nuke.allNodes(recurseGroups=True)

    # filter_type
    if (filter_type):
        node_list = [node for node in node_list if (node.Class() == filter_type)]

    # check
    if not (node_list):
        # log
        logger.debug('node_list empty or None. Returning empty list.')
        return []

    return node_list
Example #2
0
	def inputHide(self):
		self.edit(1)
		for n in nuke.allNodes():
			name = n.name()
			if n.knob('hide_input'):
				if n.Class() != 'Viewer':
					x = n.knob('hide_input')
					value = x.value()
					if value == 0:
						self.dicModif[name] = self.darkColor
					else:
						self.dicModif[name] = self.goodColor
						n.setSelected(1)
						dependenciesOfWrite = nuke.dependencies([n])
						for d in dependenciesOfWrite:
							self.dicModif[name] = self.goodColor
			else:
				self.dicModif[name] = self.darkColor
		#Add Viewer Nodes
		viewer = nuke.allNodes('Viewer')
		for i in viewer:
			name = i.name()
			self.dicModif[name] = self.darkColor
		#Store Data
		self.edit(0)
Example #3
0
	def noOutput(self):
		self.edit(1)
		for a in nuke.allNodes():
			name = a.name()
			x = a.dependent()
			y = a.dependencies()
			if y == []:
				self.dicModif[name] = self.darkColor

			else:
				if a.inputs():
					if x == []:
						self.dicModif[name] = self.goodColor
					else:
						self.dicModif[name] = self.darkColor
				else:
					self.dicModif[name] = self.darkColor

		#Add Viewer Nodes
		viewer = nuke.allNodes('Viewer')
		for i in viewer:
			name = i.name()
			self.dicModif[name] = self.darkColor
		#Store Data
		self.edit(0)
Example #4
0
def kiss_down(proximity=100):
  try:
    sel = nuke.selectedNode()
    sel_xywh = [sel.xpos(), sel.ypos(), sel.screenWidth(), sel.screenHeight()]
  except:
    return
  all_nodes = nuke.allNodes()
  input_count = sel.maxInputs()
  connected = []
  disconnected = []
  related = False
  all_nodes = nuke.allNodes()
  for node in all_nodes:
    if not node is sel:
      node_xywh = [node.xpos(), node.ypos(), node.screenWidth(), node.screenHeight()]
      if check_proximity(sel_xywh, node_xywh, 'down'):
        max_inputs = node.maxInputs()
        for m in range(max_inputs):
          if node.input(m) is sel:
            return
          if node.canSetInput(m, sel):
            if node.input(m) is None:
              node.setInput(m, sel)
              return
        return
Example #5
0
def listbookmarks():
    
    bm=[]
    zoomBy=1

    #find bookmark nodes
    for n in nuke.allNodes():
        n['selected'].setValue( False )
        if n['icon'].value() == 'bookmark.png':
            n['selected'].setValue( True )      #select nodes for clarity
            bmLabel=nuke.selectedNode()['label'].value() 

            if bmLabel:
                bm_name='"'+bmLabel+'"' # '"'<-lets it list correctly
            else:
                bm_name='"'+n.name()+'"' # '"'<-allows it to be sorted correctly with above
            bm.append(bm_name)
    if 0==len(bm):
        nuke.message('no bookmarks found')
    else:
        bookmarkList=str(sorted(bm))  

        #clean up list name
        pattern = re.compile('[\[\]\']')
        bookmarkList = pattern.sub('', bookmarkList)
        pattern = re.compile('[\,]')
        bookmarkList = pattern.sub(' ', bookmarkList)

           
        #let user choose bookmark
        panel = nuke.Panel ('BookMarks',200)     
        panel.addEnumerationPulldown('go to',bookmarkList)
        panel.addSingleLineInput('zoom',zoomBy)
        panel.addBooleanCheckBox('also open node', False)          
        panel.addButton("Cancel")
        panel.addButton("Zoom to")
        panel.addButton("Open")
        result=panel.show()

        if result:
            goto= panel.value('go to')
            zoomf= panel.value('zoom')
            alwaysOpen= panel.value('also open node')

            #select only relevent node
            for n in nuke.allNodes():
                if goto == n.name() or goto == n['label'].value():
                    n['selected'].setValue( True )
                else:
                    n['selected'].setValue( False )

            #set nuke to highlight chosen node, get xy pos and zoom into area and open if selected.
            if result ==1:                  
                nuke.zoom(float(zoomf),(nuke.selectedNode().xpos(),nuke.selectedNode().ypos()))
                if alwaysOpen:
                    nuke.show(nuke.selectedNode())
            elif result ==2:                  
                nuke.show(nuke.selectedNode())
            else:
                pass
Example #6
0
def locatorsToLights():
	dNodes = nuke.selectedNodes()
	if len (dNodes) < 1:
		dNodes = nuke.allNodes('TransformGeo')
		for curNode in nuke.allNodes('Axis2'):
			dNodes.append(curNode)

	# initialize the array so we can store the lights
	allLights = []
	# create a light for each axis/transformgeo
	for curNode in dNodes:
		if curNode.Class() == 'TransformGeo' or curNode.Class() == 'Axis2':
		    # add a light each time
		    lt = nuke.nodes.Light()
		    allLights.append(lt)
		    #copy the animation here
		    lt['translate'].fromScript(curNode['translate'].toScript()) 
		    #lt['rotate '].fromScript(curNode['rotate'].toScript()) 

	# make a scene node and it will plug all the lights in for you
	sceneNode = nuke.nodes.Scene()    

	# init the count variable so we can assign inputs
	count = 0 
	# now let's select the lights
	for curNode in allLights:
	    sceneNode.setInput(count,curNode)
	    count = count + 1
Example #7
0
def leafNodes(nodeType="", nodes=[nuke.root()]):
    return sum( map(lambda x: [x] \
                    if nuke.allNodes(group=x)==[] \
                    and ( x.Class() == nodeType or nodeType=="")   \
                    else \
                    leafNodes(nodeType, nuke.allNodes(group=x)), nodes)\
             ,[] )
Example #8
0
    def generateLog(self):
        if self.comment.value() != '':
            note = 'Notes\n\n' + self.comment.value(
            ) + '\n\n===================\n\n'
        else:
            note = self.comment.value()

        nodeInfo = ''

        a = {}
        b = []
        c = []

        for n in nuke.allNodes():
            a[n.Class()] = 0

        for n in nuke.allNodes():
            c.append(n.Class())

        for i in a:
            b.append(i)

        b.sort()

        for i in c:
            a[i] += 1

        for i in b:
            nodeInfo = nodeInfo + '(' + str(a[i]) + ')' + ' ' + i + '\n'

        stats = nukescripts.get_script_data()
        logFile = open(self.file.value() + 'log.txt', 'w')
        logFile.write(note + nodeInfo + '\n\n\n\n' + stats)
        logFile.close()
Example #9
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")
    def execute(self, templates_to_look_for, **kwargs):

        # The default implementation goes through all tank write nodes 
        # and all normal write nodes and checks them against the templates
        # defined in the configuration. Any matching templates are returned.

        resolved_nodes = []
        
        #
        #
        # First look for normal write nodes
        #
        for node in nuke.allNodes("Write"):
            path = node.knobs()["file"].value()
            # see if this path matches any template
            norm_path = path.replace("/", os.path.sep)
            # test the templates
            for t in templates_to_look_for:
                if t.validate(norm_path): 
                    # yay - a matching path!
                    d = {}
                    d["template"] = t
                    d["fields"] = t.get_fields(norm_path)
                    d["node"] = node
                    resolved_nodes.append(d)
                    
        #
        #
        # Now look for Tank write nodes
        #
        for node in nuke.allNodes("WriteTank"):
            try:
                path = node.knobs()["cached_path"].value()
            except:
                # fail gracefully - old version of tank write node?
                pass
            else:
                # see if this path matches any template
                norm_path = path.replace("/", os.path.sep)
                
                # test the templates
                for t in templates_to_look_for:
                    if t.validate(norm_path):
                        # yay - a matching path!
                        d = {}
                        d["template"] = t
                        d["fields"] = t.get_fields(norm_path)
                        d["node"] = node
                        resolved_nodes.append(d)

        # we return a list of dictionaries. 
        # Each dictionary has got the following keys:
        #
        # - template: the tank template associated with the match
        # - fields: the resolved field values (you can resolve the path 
        #   by plugging these into the template)
        # - node: the nuke node object associated with the match
        #
        return resolved_nodes
Example #11
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)
Example #12
0
def closeAllControlPanel():
    """close all node control panel"""
    for node in nuke.allNodes():
        node.hideControlPanel()
        if node.Class() == 'Group':
            node.begin()
            for child in nuke.allNodes():
                child.hideControlPanel()
                child['selected'].setValue(False)
            node.end()
Example #13
0
 def get_current_project_dir(self):
     all_dirs = list()
     if not nuke.allNodes('Read'):
         return
     for read_node in nuke.allNodes('Read'):
         file_name = read_node['file'].getValue()
         file_dir_name = os.path.dirname(os.path.dirname(file_name))
         all_dirs.append(file_dir_name)
     all_dirs = list(set(all_dirs))
     return all_dirs
Example #14
0
def stereo_script():
    for read in (x for x in nuke.allNodes() if x.Class() == 'Read'):
        if is_stereo(read):
            return True
    for write in (x for x in nuke.allNodes() if x.Class() == 'Write'):
        if is_stereo(write):
            return True
        if 'left right' == write.knob('views').value():
            return True

    return False
Example #15
0
def createViewerInput():
    """create the color check node"""
    if 'VIEWER_INPUT' not in [node.name() for node in nuke.allNodes()]:
        for node in nuke.allNodes():
            node['selected'].setValue(False)
        nuke.createNode("dmpViewerInput")
        node = nuke.toNode('VIEWER_INPUT')
        node.showControlPanel()
        node['selected'].setValue(False)
    else:
        nuke.toNode('VIEWER_INPUT').showControlPanel()
Example #16
0
def getInputNodes( afnode, parent):
	if parent is None:
		print 'Node is "None"'
		return None

	if VERBOSE == 2: print 'Getting inputs of "%s"' % parent.name()

	global LastAfNode
	global InputNumber
	global InputName

	inputnodes = []
	for i in range( parent.inputs()):
		node = parent.input(i)
		if node is None: continue
		inputnodes.append( node)

	if afnode != None:
		LastAfNode = afnode
		addnodes = afnode.knob('addnodes').value()
		if addnodes != None and addnodes != '':
			if VERBOSE == 2: print 'Adding nodes "%s" to "%s"' % ( addnodes, afnode.name())
			rexpr = re.compile( addnodes + '$')
			addnodes = []
			addnodes.extend( nuke.allNodes( RenderNodeClassName,  nuke.root()))
			addnodes.extend( nuke.allNodes( AfanasyNodeClassName, nuke.root()))
			if len(addnodes) > 1: addnodes.sort( None, getNodeName)
			for node in addnodes:
				if rexpr.match( node.name()):
					inputnodes.append( node)

	nodes = []
	for i in range( len(inputnodes)):
		node = inputnodes[i]
		if afnode != None:
			InputNumber = i + 1
			InputName = node.name()
		if node.Class() == RenderNodeClassName or node.Class() == AfanasyNodeClassName or node.Class() == DailiesNodeClassName:
			disableknob = node.knob('disable')
			if disableknob:
				if not disableknob.value():
					nodes.append( node)
				else:
					if VERBOSE==1: print 'Node "%s" is disabled' % node.name()
					continue
		else:
			if node.inputs() > 0:
				childs = getInputNodes( None, node)
				if childs == None: return None
				if len( childs) > 0: nodes.extend( childs)
			else:
				nuke.message('Leaf node reached "%s"-"%s" on "%s" input #%d.' % ( node.name(), InputName, LastAfNode.name(), InputNumber))
				return None
	return nodes
    def _import_script(self, new_script_path):
        """
        Import contents of the given file into the scene.

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

        # first we look at the current read nodes in the scene (they've been updated to their latest version already)
        preloaded_nodes = nuke.allNodes('Read')


        # We import the new nodes into the scene
        # if not os.path.exists(new_path):
        #     raise Exception("File not found on disk - '%s'" % new_path)

        nuke.nodePaste(new_script_path)
        node = nuke.toNode('Published Data')
        node['text'].setValue(new_script_path)

        # Compare the new nodes with the old ones and delete the duplicates
        new_nodes = [item for item in nuke.allNodes('Read') if item not in preloaded_nodes]

        # Initialise the tank
        tk = sgtk.sgtk_from_path(new_script_path)

        # Get the maya render template
        maya_render_template = tk.templates["maya_shot_render"]

        cleanup_list = []
        # Iterate through all the node
        for new_node in new_nodes:
            new_path = new_node['file'].value()
            # Is it a published render
            if maya_render_template.validate(new_path):
                new_fields = maya_render_template.get_fields(new_path)
                # Iterate through all the pre loaded node
                for old_node in preloaded_nodes:
                    old_path = old_node['file'].value()
                    # Is it a published node
                    if maya_render_template.validate(old_path):
                        old_fields = maya_render_template.get_fields(old_path)
                        # Compare the fields
                        if (new_fields['Shot'] == old_fields['Shot']
                            and new_fields['render_layer'] == old_fields['render_layer']
                            and new_fields['version'] > old_fields['version']):
                            old_node["file"].setValue(new_path)
                            cleanup_list.append(new_node)
                            self.color_updated_read_node(old_node)

        #Delete any redundents nodes
        for node in list(set(cleanup_list)):
            nuke.delete(node )
def assembleScript(dstPath=None):
    
    log = ""
    
    if not dstPath:
        dstPath = nuke.getFilename("Select Destination Path")
    
    
    
    addLogLine(log, "--[ Und Los! ]--")
    
    # copy Files
    
    # Selected Outs
    for node in nuke.selectedNodes():
        if node.Class() == "Write":
            log = addLogLine(log, copyNodeFileTo(node, dstPath, "outs"))
    
    
    # Reads
    for node in nuke.allNodes():
        if node.Class() != "Write":
            log = addLogLine(log, copyNodeFileTo(node, dstPath, "source"))
    
    for group in nuke.allNodes('Group'):
        with group:
            for node in nuke.allNodes():
                if node.Class() != "Write":
                    log = addLogLine(log, copyNodeFileTo(node, dstPath, "source"))
    

    # Save Script
    nr = nuke.root()
    
    nr["project_directory"].setValue("[python {nuke.script_directory()}]")
    
    scriptpath, scriptname = os.path.split(nr["name"].getValue())
    
    if scriptname =="":
        scriptname = "shotscript_v01.nk"
    
    try:
        os.makedirs(os.path.join(dstPath, "setup"))
    except:
        pass
    
    nuke.scriptSaveAs(os.path.join(dstPath, "setup", scriptname) )
    
    # Fettig
    
    log = addLogLine(log, "--[ fin ]--")
    
    nuke.message(log)
def get_all_write_nodes():
    '''
    Return a dictionary of all Write and Deep Write nodes that exist in the current
    Nuke script.  The dictionary key is the node name, and the value (bool) indicates
    whether the node is currently selected or not.
    '''
    write_nodes = nuke.allNodes(filter="Write")
    write_nodes.extend(nuke.allNodes(filter="DeepWrite"))
    # Filter out Write / DeepWrite nodes that are marked as disabled
    write_nodes = [node for node in write_nodes if not node['disable'].value()]
    selected_nodes = nuke.selectedNodes()
    node_names = dict([(node.fullName(), bool(node in selected_nodes)) for node in write_nodes])
    return node_names
Example #20
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')
Example #21
0
def do( tocut):
   nodes = []
   nodes.extend( nuke.allNodes('Read'))
   nodes.extend( nuke.allNodes('Write'))
   for node in nodes:
      for knobname in knobnames:
         knob = node.knob( knobname)
         if knob is not None:
            value = knob.value()
            if value is not None and value != '':
               if tocut:
                  knob.setValue( value.replace( os.getcwd()+'/',''))
               elif value[0] != '/':
                  knob.setValue( os.getcwd()+'/'+value)
Example #22
0
def setDisplayTexturedLines():
    """set all 3d to textured mode"""
    for node in nuke.allNodes():
        print node.name()
        goodGeo = ["Group", "ReadGeo","ReadGeo2","Sphere","Cube","Cylinder","Card", "Card2"]
        if node.Class() in goodGeo:
            if node.Class() == "Group":
                node.begin()
                for child in nuke.allNodes():
                    if child.Class() in goodGeo:
                        child['display'].setValue(5)
                node.end()
            else:
                node['display'].setValue(5)
Example #23
0
def gizmos_to_groups(nodes):
  """If the node is a Gizmo, use makeGroup() to turn it into a Group."""
  # Deselect all nodes. catch errors for nuke versons that don't support the recurseGroups option.
  try:
    node_list = nuke.allNodes(recurseGroups=True)
  except:
    node_list = nuke.allNodes()
  for node in node_list:
    node.setSelected(False)
  for node in nodes:
    if hasattr(node, 'makeGroup') and callable(getattr(node, 'makeGroup')):
      node.setSelected(True)
      node.makeGroup()
      nuke.delete(node)
    def scan_scene(self):
        """
        The scan scene method is executed once at startup and its purpose is
        to analyze the current scene and return a list of references that are
        to be potentially operated on.

        The return data structure is a list of dictionaries. Each scene reference
        that is returned should be represented by a dictionary with three keys:

        - "node": The name of the 'node' that is to be operated on. Most DCCs have
          a concept of a node, path or some other way to address a particular
          object in the scene.
        - "type": The object type that this is. This is later passed to the
          update method so that it knows how to handle the object.
        - "path": Path on disk to the referenced object.

        Toolkit will scan the list of items, see if any of the objects matches
        any templates and try to determine if there is a more recent version
        available. Any such versions are then displayed in the UI as out of date.
        """

        reads = []

        # first let's look at the read nodes
        for node in nuke.allNodes("Read"):

            node_name = node.name()

            # note! We are getting the "abstract path", so contains
            # %04d and %V rather than actual values.
            path = node.knob("file").value().replace("/", os.path.sep)

            reads.append({"node": node_name, "type": "Read", "path": path})

        # then the read geometry nodes
        for node in nuke.allNodes("ReadGeo2"):
            node_name = node.name()

            path = node.knob("file").value().replace("/", os.path.sep)
            reads.append({"node": node_name, "type": "ReadGeo2", "path": path})

        # then the read camera nodes
        for node in nuke.allNodes("Camera2"):
            node_name = node.name()

            path = node.knob("file").value().replace("/", os.path.sep)
            reads.append({"node": node_name, "type": "Camera2", "path": path})

        return reads
Example #25
0
    def alfredRender(self):
        
        self.node.end()
        
        for node in nuke.allNodes():
            node.knob('selected').setValue(0)
            
        for write in nuke.allNodes('Write'):
            write.knob('disable').setValue(1)
        
        self.node.begin()
        
        writeRender = nuke.toNode('WriteShot')
        writeRender.knob('selected').setValue(1)
        #nuke.show(writeRender)
        
        # alfred render luncher

        currTime = str(time.strftime('%d%m%y_%H%M%S'))
        nuke.scriptSave('')
        nukeScene = nuke.toNode('root').name()
        fileDir = os.path.dirname(nukeScene)+'/'

        panel = nuke.Panel('Alfred batch render')
        panel.addSingleLineInput('frame range', str(int(nuke.root()['first_frame'].getValue()))+','+str(int(nuke.root()['last_frame'].getValue())))
        val = panel.show()
        if val ==1:
            frameRange = panel.value('frame range')
            
            for write in nuke.allNodes('Write'):
                write.knob('disable').setValue(1)
            
            writeRender.knob('disable').setValue(0)

            renderScene = fileDir+'.'+os.path.basename(nukeScene).split('.')[0]+'_alfredrender_'+writeRender.name()+'_'+currTime+'.nk'
            nuke.scriptSaveAs(renderScene, overwrite = 1)
            
            print 'sending '+renderScene+' to Alfred ...'
            #nuke.tcl('exec rnuke "'+renderScene+'" '+frameRange+' &;')
            os.popen('rnuke '+renderScene+' '+frameRange+' &')
            
            for write in nuke.allNodes('Write'):
                write.knob('disable').setValue(0)
            
            nuke.scriptSaveAs(nukeScene, overwrite = 1)
            
        else:
            print 'abort...'
    def process(self, context):

        for node in nuke.allNodes():
            if node.Class().lower().startswith('ofxcom.absoft.neatvideo'):
                if not node['disable'].getValue():
                    msg = 'Neat Video is active in file: "%s"' % node.name()
                    raise ValueError(msg)
    def _nuke_find_script_dependencies(self):
        """
        Find all dependencies for the current nuke script
        """
        import nuke
        
        # figure out all the inputs to the scene and pass them as dependency candidates
        dependency_paths = []
        for read_node in nuke.allNodes("Read"):
            # make sure we have a file path and normalize it
            # file knobs set to "" in Python will evaluate to None. This is different than
            # if you set file to an empty string in the UI, which will evaluate to ""!
            file_name = read_node.knob("file").evaluate()
            if not file_name:
                continue
            file_name = file_name.replace('/', os.path.sep)

            # validate against all our templates
            for template in self.parent.tank.templates.values():
                if template.validate(file_name):
                    fields = template.get_fields(file_name)
                    # translate into a form that represents the general
                    # tank write node path.
                    fields["SEQ"] = "FORMAT: %d"
                    fields["eye"] = "%V"
                    dependency_paths.append(template.apply_fields(fields))
                    break

        return dependency_paths
Example #28
0
def iterateAllNodes(rootnode=None, triggerFn=None, opFn=None, deep=True):
    """from a given root level apply a certain function (opFn) to any node
    which makes a trigger return True (triggerFn).

    Defaults (assuming None supplied are:
    root -  nuke.root(),
    trigger - True (i.e. always fires)
    operation - print node's fullName
    deep - True (i.e. will recurse into groups as far as it can)
    """
    if rootnode is None:
        rootnode = nuke.root()

    if triggerFn is None:
        def triggerFn(x): return True

    if opFn is None:
        def opFn(x): print(x.fullName())

    with rootnode:
        for x in nuke.allNodes():
            if x.Class() == 'Group' and deep:   # recurse
                iterateAllNodes(rootnode=x, triggerFn=triggerFn,
                                opFn=opFn, deep=deep)
            elif triggerFn(x):
                opFn(x)
Example #29
0
def shakeClone():
	EXCLUSION_LIST = ["xpos","ypos","help","hide_input","note_font_color","onCreate","updateUI","knobChanged","note_font","tile_color","selected","autolabel","process_mask","label","onDestroy","inject","indicators","maskFrom","maskChannelMask","maskChannelInput","Mask","postage_stamp", "postage_stamp_frame","disable","maskChannelMask", "panel", "maskFromFlag","name","cached","fringe", "maskChannelInput" , "note_font_size" , "filter", "gl_color","transform", "dope_sheet"]

	originals = nuke.selectedNodes()
	[ n['selected'].setValue(False) for n in nuke.allNodes() ]

	for original in originals:
		new = nuke.createNode(original.Class())

		for i in original.knobs():
			if i not in EXCLUSION_LIST:
								# Try to set the expression on the knob
				new.knob(i).setExpression("%s.%s" % (original.name(), original.knob(i).name()))

								# This will fail if the knob is an Array Knob...use setSingleValue to compensate
								# Thanks Hugh!
				if isinstance(new.knob(i), nuke.Array_Knob):
					new.knob(i).setSingleValue(original.knob(i).singleValue()) 

								# This will fail if the knob is a String Knob...use a TCL expression link to compensate
								# Thanks Michael!
				elif isinstance(new.knob(i), nuke.String_Knob): 
					new.knob(i).setValue("[value %s.%s]" % (original.name(), original.knob(i).name())) 

		new['selected'].setValue(False)	

	[ n['selected'].setValue(True) for n in originals ]
Example #30
0
def reloadAllReads():
	'''
	Reload all read nodes
	'''
	nodes = [node for node in nuke.allNodes(recurseGroups = True) if node.Class() == 'Read']
	for node in nodes:
		node.knob('reload').execute()
Example #31
0
def resetNodeCol():
    aNode = []

    for n in nuke.allNodes():
        if n.Class() == "Grade" or n.Class() == "Merge2" or n.Class(
        ) == "Keymix":
            n['tile_color'].setValue(0)
            aNode.append(n.name())

    nuke.message('Reseted Color For: ' + '\n' + str(', '.join(aNode)))
Example #32
0
def disableDeselectedWrites():

    nodes = nuke.selectedNodes()
    if len(nodes) < 1:
        print('No nodes selected')
    else:
        allNodes = nuke.allNodes('Write')
        for node in allNodes:
            if node not in nodes:
                node['disable'].setValue(True)
Example #33
0
    def get_main_write_nodes(self):
        """Returns the main write node in the scene or None.
        """
        # list all the write nodes in the current file
        all_main_write_nodes = []
        for write_node in nuke.allNodes("Write"):
            if write_node.name().startswith(self._main_output_node_name):
                all_main_write_nodes.append(write_node)

        return all_main_write_nodes
Example #34
0
    def update_write_dict(self):
        wd = dict()
        for node in (x for x in nuke.allNodes()
                     if x.Class() in WRITE_NODE_CLASSES):
            if not node.knob('disable').value():
                wd[node.name()] = node

        self.writeDict.update(wd)
        self.writeListNames = self.writeDict.keys()
        self.writeListNames.sort()
Example #35
0
def _force_update_all():
    with nuke.root():
        node_count = 0
        for node in nuke.allNodes():
            if node.Class() == "Cryptomatte":
                node_count = node_count + 1
                cinfo = CryptomatteInfo(node)
                _update_cryptomatte_gizmo(node, cinfo, force=True)

        nuke.message("Updated %s cryptomatte gizmos." % node_count)
Example #36
0
def delete_error_read():
    """
    Delete all Read nodes with error.
    :return: None
    :rtype: None
    """
    all_nodes = nuke.allNodes("Read")
    for read in all_nodes:
        if read.error() is True:
            nuke.delete(read)
Example #37
0
    def post_validate(self, publish_tree):
        """
        This method is executed after the validation pass has completed for each
        item in the tree, before the publish pass.

        A :ref:`publish-api-tree` instance representing the items to publish,
        and their associated tasks, is supplied as an argument. The tree can be
        traversed in this method to inspect the items and tasks and process them
        collectively. The instance can also be used to save the state of the
        tree to disk for execution later or on another machine.

        To glean information about the validation of particular items, you can
        iterate over the items in the tree and introspect their
        :py:attr:`~.api.PublishItem.properties` dictionary. This requires
        customizing your publish plugins to populate any specific validation
        information (failure/success) as well. You might, for example, set a
        ``validation_failed`` boolean in the item properties, indicating if any
        of the item's tasks failed. You could then include validation error
        messages in a ``validation_errors`` list on the item, appending error
        messages during task execution. Then, this method might look something
        like this:

        .. code-block:: python

            def post_validate(self, publish_tree):

                all_errors = []

                # the publish tree is iterable, so you can easily loop over
                # all items in the tree
                for item in publish_tree:

                    # access properties set on the item during the execution of
                    # the attached publish plugins
                    if item.properties.validation_failed:
                        all_errors.extend(item.properties.validation_errors)

                # process all validation issues here...

        .. warning:: You will not be able to use the item's
            :py:attr:`~.api.PublishItem.local_properties` in this hook since
            :py:attr:`~.api.PublishItem.local_properties` are only accessible
            during the execution of a publish plugin.

        :param publish_tree: The :ref:`publish-api-tree` instance representing
            the items to be published.
        """
        self.logger.debug("Executing post validate hook method...")

        for item in publish_tree:
            if item.name == "Current Nuke Session":
                if 'write_node_paths_dict' in item.properties:
                    item.properties['write_node_paths_dict'] = dict()
                if 'visited_dict' in item.properties:
                    item.properties['visited_dict'] = {node: 0 for node in nuke.allNodes(recurseGroups=True)}
Example #38
0
def processWriteNode():
    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():
                outputFile = nuke.filename(curNode)
    elif n.Class() == 'Read' or n.Class == 'Write':
        outputFile = nuke.filename(curNode)
    else:
        nuke.message('Error:\nThis node is not an AutoWrite, Read, or Write')
        return

    if checkPath(outputFile) == True:

        p = nuke.Panel('Send this to Client')
        p.addEnumerationPulldown('For:', 'WIP Final')
        p.show()

        status = p.value('For:').lower()
        frameFirst = int(nuke.root()['first_frame'].getValue()) - 1
        frameLast = int(nuke.root()['last_frame'].getValue())
        frameRange = '%04d-%04d' % (frameFirst, frameLast)

        jobFiles = createDeadlineJobFiles(outputFile, status, frameRange)
        submitToDeadline(jobFiles[0], jobFiles[1])

    else:
        nuke.message(
            'Error : Your output is not in a format like aa000_000_task_v000\nPlease resolve and try again'
        )
Example #39
0
def autoBackdrop():
    '''
  Automatically puts a backdrop behind the selected nodes.

  The backdrop will be just big enough to fit all the select nodes in, with room
  at the top for some text in a large font.
  '''
    selNodes = nuke.selectedNodes()
    if not selNodes:
        return nuke.nodes.BackdropNode()

    # Calculate bounds for the backdrop node.
    bdX = min([node.xpos() for node in selNodes])
    bdY = min([node.ypos() for node in selNodes])
    bdW = max([node.xpos() + node.screenWidth() for node in selNodes]) - bdX
    bdH = max([node.ypos() + node.screenHeight() for node in selNodes]) - bdY

    zOrder = 0
    selectedBackdropNodes = nuke.selectedNodes("BackdropNode")
    #if there are backdropNodes selected put the new one immediately behind the farthest one
    if len(selectedBackdropNodes):
        zOrder = min(
            [node.knob("z_order").value()
             for node in selectedBackdropNodes]) - 1
    else:
        #otherwise (no backdrop in selection) find the nearest backdrop if exists and set the new one in front of it
        nonSelectedBackdropNodes = nuke.allNodes("BackdropNode")
        for nonBackdrop in selNodes:
            for backdrop in nonSelectedBackdropNodes:
                if nodeIsInside(nonBackdrop, backdrop):
                    zOrder = max(zOrder, backdrop.knob("z_order").value() + 1)

    # Expand the bounds to leave a little border. Elements are offsets for left, top, right and bottom edges respectively
    left, top, right, bottom = (-10, -80, 10, 10)
    bdX += left
    bdY += top
    bdW += (right - left)
    bdH += (bottom - top)

    n = nuke.nodes.BackdropNode(xpos=bdX,
                                bdwidth=bdW,
                                ypos=bdY,
                                bdheight=bdH,
                                tile_color=int(
                                    (random.random() * (16 - 10))) + 10,
                                note_font_size=42,
                                z_order=zOrder)

    # revert to previous selection
    n['selected'].setValue(False)
    for node in selNodes:
        node['selected'].setValue(True)

    return n
Example #40
0
def fixBackdropDepth():
    '''
    Layer smaller backdrops on top of bigger ones
    '''
    sel = nuke.selectedNodes('BackdropNode')
    all = nuke.allNodes('BackdropNode')
    all.sort(key = lambda x: x.screenHeight() * x.screenWidth(), reverse = True)
    try:
        [b.selectNodes() for b in all if (b in sel or len(sel) ==0)]
    except: # This will be used for Nuke versions below 6.3v5
        [selectBackdropContents(b) for b in all if (b in sel or len(sel) ==0)]
Example #41
0
def list_disabled_nodes():
    """
    Returns the list of disabled nodes present in the flow
    :return:
    """
    disabled_nodes = []
    for node in nuke.allNodes():
        if 'disable' in [i.name() for i in node.allKnobs()]:
            if node['disable'].getValue():
                disabled_nodes.append(node.name())
    return disabled_nodes
Example #42
0
def selectRandom():
    theSelectedNodes = nuke.selectedNodes()

    for aNode in nuke.allNodes():
        aNode['selected'].setValue(False)

    theValue = float(nuke.getInput("ratio?"))

    for aNode in theSelectedNodes:
        if random.random() < theValue:
            aNode['selected'].setValue(True)
def disconnectViewer():

    n = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    nodes = nuke.allNodes()
    for i in nodes:
        cls = i.Class()
        if cls == 'Viewer':
            print cls
            for nums in n:
                i.setInput(nums, None)
    return 'disconnected'
Example #44
0
def getAllNodesByType(typ=''):
    return_nodes = []

    if typ == '':
        return None

    for n in nuke.allNodes():
        if n.Class() == typ:
            return_nodes.append(n)

    return return_nodes
Example #45
0
def versionDown():
    node = nuke.thisNode()
    path = node['file'].value()
    renderString = path.split(publishPath)[-1].split('/')[0]
    with node:
        nuke.selectAll()
        nuke.invertSelection()
        for n in nuke.allNodes('Read'):
            if renderString in n['file'].value():
                n.setSelected(1)
        versionTools.version_down()
Example #46
0
def versionDown():
    node = nuke.thisNode()
    with node:
        for n in nuke.allNodes('Read'):
            n.setSelected(1)
        mlScripts.utils.version.version_down()
        print 'updated'
    file = node['file'].value()
    fName = file.split('/')[-1].split('.')[0]
    regex = re.compile("v[0-9]{2,9}")
    vers = regex.findall(file)[0]
Example #47
0
def loadShotLut():
    logBig("Loading: " + os.path.basename(__file__))

    try:
        import sgtk

        # get the engine we are currently running in
        current_engine = sgtk.platform.current_engine()

        # get hold of the shotgun api instance used by the engine, (or we could have created a new one)
        sg = current_engine.shotgun

        # Get current Context
        context = current_engine.context

        # Get the Just Created Viewer Process
        lut = nuke.thisNode()

        ############# ADD SHOW FUNCTION CODE HERE ########################
        """
        Use the 'lut' var to acces the created gizmo and its knobs.
        """

        # Get Shot Data
        filters = [["id", "is", context.entity["id"]]]
        fields = ["sg_cdl_asc_sat", "sg_cdl_asc_sop", "sg_lut"]
        sg_shot = sg.find_one("Shot", filters, fields)
        log(sg_shot)

        dataField = "sg_cdl_asc_sop"
        if sg_shot[dataField] != None:
            lut["slope"].setValue(_filterSatSop("slope", sg_shot[dataField]))
            lut["offset"].setValue(_filterSatSop("offset", sg_shot[dataField]))
            lut["power"].setValue(_filterSatSop("power", sg_shot[dataField]))
        lut["working_space"].setValue("AlexaV3LogC")

        dataField = "sg_cdl_asc_sat"
        if sg_shot[dataField] != None:
            lut["saturation"].setValue(
                _filterSatSop("saturation", sg_shot[dataField]))

        ############# END SHOW FUNCTION CODE ##############################

        # Set Current and more Viewers to LUT we Created
        #node = nuke.activeViewer().node()['viewerProcess'].setValue(lut_name)
        log("Setting all Viewers to use the Lut")
        for node in nuke.allNodes("Viewer"):
            node["viewerProcess"].setValue(lut_name)

    except Exception as e:
        print "\n\n"
        print "ERROR loading Shot Lut!"
        print e
        print "\n\n"
def makeSad():
    count = 0
    for sel in nuke.allNodes():
        if sel.Class() in ("RotoPaint", "Roto"):
            rt = sel['curves'].rootLayer
            count += len(rt)

    nuke.message(
        "You have used %d paint strokes for only %d frames! You should feel very proud."
        % (count, (nuke.root()['last_frame'].getValue() -
                   nuke.root()['first_frame'].getValue())))
Example #49
0
    def getBackdropNodes(self, node):
        allBDs = nuke.allNodes('BackdropNode')
        nodeBackdrops = []
        # store original selection
        originalSelection = nuke.selectedNodes()
        for bd in allBDs:
            # clear original selection:
            for n in nuke.allNodes():
                n.setSelected(False)
            # select backdrop nodes
            bd.selectNodes()
            # store new selection
            bdNodes = nuke.selectedNodes()
            if node in bdNodes:
                nodeBackdrops.append(bd)
        # restore previous selection
        for n in nuke.allNodes():
            n.setSelected(n in originalSelection)

        return nodeBackdrops
Example #50
0
def list_expression_driven_nodes():
    """
    Returns the list of all Expression Driven Nodes in the flow
    :return:
    """
    exp_driven_nodes = []
    for node in nuke.allNodes():
        for knob in node.allKnobs():
            if knob.hasExpression():
                exp_driven_nodes.append(node.name())
    return exp_driven_nodes
Example #51
0
def list_animated_nodes():
    """
    Returns the list of all Animated Nodes in the flow
    :return:
    """
    animated_nodes = []
    for node in nuke.allNodes():
        for knob in node.allKnobs():
            if knob.isAnimated():
                animated_nodes.append(node.name())
    return animated_nodes
    def _find_position(self):
        import nuke
        all_nodes = nuke.allNodes()
        xpos_t, ypos_t = 0, 0

        for node in all_nodes:
            if node.xpos() < xpos_t:
                xpos_t = node.xpos()
            if node.ypos() > ypos_t:
                y_pos_t = node.ypos()
        return xpos_t - 300, ypos_t + 300
Example #53
0
    def get_plugin_nodes(self):
        plugin_nodes = []
        class_prefixes = [
            "OFXcom.borisfx.ofx.mochapro", "OFXcom.borisfx.ofx.mochavr",
            "OFXcom.borisfx.ofx.mochavr_v1"
        ]
        for node in nuke.allNodes():
            if node.Class() in class_prefixes:
                plugin_nodes.append(node)

        return plugin_nodes
Example #54
0
def main_comp():
    """returns a list of all nodes in the largest tree in the comp,
    assumed to be the main comp"""
    all_nodes = nuke.allNodes('Write')
    above_nodes = []
    above_nodes = [(above(n), n) for n in all_nodes]
    main_comp = max(above_nodes, key=lambda x: len(x[0]))
    main_comp_nodes = main_comp[0]
    main_comp_nodes.reverse()
    main_comp_nodes.append(main_comp[1])
    return main_comp_nodes
Example #55
0
def gq_disableHeavy():
    nuke.root().begin()
    allNodes = nuke.allNodes()
    classTypes = [
        "Defocus", "VectorBlur", "MotionBlur", "pgBokeh", "ZDefocus2"
    ]

    for node in allNodes:
        for cType in classTypes:
            if cType in node.Class():
                node.knob("disable").setValue(True)
def start():
    """Start up function for Hotbox. Checks if Viewer available and active."""
    if nuke.allNodes('Viewer'):
        if nuke.activeViewer().activeInput() is not None:
            global HOTBOX
            HOTBOX = HotBox()
            HOTBOX.show()
        else:
            print('No active viewer connected to node.')
    else:
        print('No viewer found in script.')
Example #57
0
 def __init__(self, *args, **kwargs):
     super(Creator, self).__init__(*args, **kwargs)
     # make sure no duplicity of subsets are in workfile
     if lib.check_subsetname_exists(
             nuke.allNodes(),
             self.data["subset"]):
         msg = "The subset name `{0}` is already used on a node in" \
               "this workfile.".format(self.data["subset"])
         self.log.error(msg + '\n\nPlease use other subset name!')
         raise NameError("`{0}: {1}".format(__name__, msg))
     return
Example #58
0
 def get_all_nodes_of_type(class_type):
     """
     get all nodes matching the type
     :param class_type: a nuke class
     :return: the list of nodes
     """
     node_list = []
     for n in nuke.allNodes():
         if n.Class() == class_type:
             node_list.append(n)
     return node_list
Example #59
0
def get_closest_node(node):
    # Return the closest node to node
    distances = {}
    for n in nuke.allNodes():
        if n.name() == node.name():
            continue
        distance = math.sqrt(
            math.pow((node.xpos() - n.xpos()), 2) +
            math.pow((node.ypos() - n.ypos()), 2))
        distances[n.name()] = distance
    return nuke.toNode(min(distances, key=distances.get))
Example #60
0
def nextVersion():

    p = nextVersionPanel()
    if p.show():
        #script version up
        nukescripts.script_version_up()
        #writeNode version up and create folder
        for node in nuke.allNodes("Write"):
            name = node.name()
            if p.value(name) == 1:
                node.knob("create next version").execute()