コード例 #1
0
ファイル: createReadWrite.py プロジェクト: robmoggach/nuke-py
def createReadFromWrite(nodes=[]):
	'''
	function to create a read node
	from a selected write node
	'''

	# if no nodes are defined look for selected nodes
	if not nodes:
		nodes = nuke.selectedNodes()
	
	# if nodes is still empty, nothing is selected
	if nodes == ():
		nuke.message('ERROR: No node(s) selected.')
		return
	
	#work around to select single node as an object
	node = nodes[0]
	_class = node.Class()
	if _class == "Write":
		file = node.knob('file').getValue()
		proxy = node.knob('proxy').getValue()
		first = nuke.toNode('root').knob('first_frame').getValue()
		last = nuke.toNode('root').knob('last_frame').getValue()
		xpos = node.knob('xpos').getValue()
		ypos = int(node.knob('ypos').getValue()) + 40
		knobs = []
		fields = ('file','proxy','first','last','xpos','ypos')
		for entry in fields:
			if eval(entry) != '':
				knobs.append(entry)
				knobs.append(str(eval(entry)))
		nuke.createNode('Read', string.join(knobs))	
	return
コード例 #2
0
def setBoundingBox():
    '''
    Sets the bounding box dimensions for the particles at the current frame
    Applies an offset to the particles to keep them everything centered on origin
    '''
    # Calculate the particle bounds
    pos_node = nuke.toNode('Position_Checker')
    x = getMinMax( pos_node, 'rgba.red' )
    y = getMinMax( pos_node, 'rgba.green' )
    z = getMinMax( pos_node, 'rgba.blue' )

    cube = nuke.toNode('BoundingBox')

    # Centerpoint of Bounds
    mid_x = ( x[1] - x[0] ) / 2.0 + x[0]
    mid_y = ( y[1] - y[0] ) / 2.0 + y[0]
    mid_z = ( z[1] - z[0] ) / 2.0 + z[0]

    # Set cube size centered on origin
    cube['cube'].setValue( [ x[0] - mid_x, y[0] - mid_y, z[0] - mid_z, x[1] - mid_x, y[1] - mid_y, z[1] - mid_z ] )

    if nuke.thisNode()['center_pivot'].value():
        # Grade offset to particle positions to center on origin
        offset = nuke.toNode('Offset')
        offset['value'].setValue( -mid_x, 0 )
        offset['value'].setValue( -mid_y, 1 )
        offset['value'].setValue( -mid_z, 2 )
コード例 #3
0
ファイル: jobLocal.py プロジェクト: horitin/pipeline
def switchStatus():
	
	if int(nuke.toNode('locController').knob('location').value()) == 0:
		nuke.toNode('status').knob('label').setValue('LOCAL')
	
	else:
		nuke.toNode('status').knob('label').setValue('NETWORK')
コード例 #4
0
ファイル: menu.py プロジェクト: andybclarke/Nuke_prefs
def preferencesCreatedCallback():
    p = nuke.toNode('preferences')
    
    #Setup J_Ops prefs knobs if they don't exist.
    try:
        jopsKnobsPresent = p["J_Ops"]
    except (SyntaxError, NameError):
        k = nuke.Tab_Knob("J_Ops")
        k.setFlag(nuke.ALWAYS_SAVE)
        p.addKnob(k)

        v = nuke.Double_Knob("j_ops_ver", "j_ops_ver")
        v.setFlag(nuke.ALWAYS_SAVE)
        v.setFlag(nuke.INVISIBLE)
        v.setValue(2.0101)
        p.addKnob(v)
        
        k = nuke.Boolean_Knob("j_ops_enable_drop", "Improved drag and drop")
        k.setFlag(nuke.ALWAYS_SAVE)
        k.setFlag(nuke.STARTLINE)
        k.setValue(1.0)
        k.setTooltip("Enable/disable a somewhat improved drag and drop behaviour. Requires Nuke restart to take effect. Adds creation of geo, camera, light and vectorfield nodes based on incoming file extensions, as well as support for sequences when dropping folders onto DAG.")
        p.addKnob(k)

        k = nuke.Boolean_Knob("j_ops_enable_bookmark", "DAG bookmarks")
        k.setFlag(nuke.ALWAYS_SAVE)
        k.setFlag(nuke.STARTLINE)
        k.setValue(1.0)
        k.setTooltip("Enable/disable DAG bookmarks, allowing storing and recalling of particular DAG locations and zoom settings, for easy navigation around a script. Requires Nuke restart to take effect. Adds Python-DAG Bookmarks menu to J_Ops toolbar, offering access via mouse, tab menu, or hotkeys.")
        p.addKnob(k)

        k = nuke.Text_Knob("j_ops_dropdivider_label", "Drag And Drop")
        k.setFlag(nuke.ALWAYS_SAVE)
        p.addKnob(k)

        k = nuke.Boolean_Knob("j_ops_drop_recurse", "Recurse directories")
        k.setFlag(nuke.ALWAYS_SAVE)
        k.setValue(1.0)
        k.setTooltip("Enable/disable recursion into directories dropped on DAG. When enabled will result in entire directory structure being imported into DAG, when disabled only the directory dropped will be imported (ie none of its sub directories)")
        p.addKnob(k)
        
    #Check for preference setting, and if drop enabled add its callback/
    dropEnabled = False
    try:
        dropEnabled = nuke.toNode('preferences')["j_ops_enable_drop"].getValue()
    except (SyntaxError, NameError):
        pass

    if dropEnabled == True:
        nukescripts.drop.addDropDataCallback(jopsDropHandler)

    #Check for preference setting, and if drop enabled add its callback/
    bookmarkEnabled = False
    try:
        bookmarkEnabled = nuke.toNode('preferences')["j_ops_enable_bookmark"].getValue()
    except (SyntaxError, NameError):
        pass

    if bookmarkEnabled == True:
        jopsBookmarkAddMenus()
コード例 #5
0
ファイル: update.py プロジェクト: mkolar/pyblish-bumpybox
    def swapOutNode(self, targetNode, newNode):
        '''
        Mostly mimics the Ctrl + Shift + drag-and-drop node functionality in Nuke.

        'targetNode': The node (or node name) to be replaced.
        'newNode': The node (or node name) that will replace it.
        '''
        if isinstance(targetNode, basestring):
            targetNode = nuke.toNode(targetNode)
        if isinstance(newNode, basestring):
            newNode = nuke.toNode(newNode)
        if not (isinstance(targetNode, nuke.Node) and isinstance(newNode, nuke.Node)):
            return
        sourcePos = (newNode.xpos(), newNode.ypos())
        targetPos = (targetNode.xpos(), targetNode.ypos())
        oldSel = nuke.selectedNodes()
        inputNodes, outputNodes = self.getConnectedNodes(targetNode)
        nukescripts.clear_selection_recursive()
        targetNode.setSelected(True)
        nuke.extractSelected()
        targetNode.setSelected(False)
        newNode.setXYpos(*targetPos)
        targetNode.setXYpos(*sourcePos)
        for inNode in inputNodes:
            newNode.setInput(*inNode)
        for index, node in outputNodes:
            node.setInput(index, newNode)
        for node in oldSel:
            node.setSelected(True)
        return True
コード例 #6
0
def knobChanged():
    n = nuke.thisNode()
    k = nuke.thisKnob()

    if k.name() == 'opt_knob':
        if k.value() == 'text':
            n.begin()
            nuke.toNode('watermark_image')['file'].setValue('')
            n.end()

            n['w_text_knob'].setEnabled(True)
            n['wm_file'].setEnabled(False)

            n['tiles'].setValue(7.4)
            n['translate'].setValue([nuke.Root().width()/2, -nuke.Root().height()/2])
            n['rotate'].setValue(34)
            n['scale'].setValue(6.3)
        elif k.value() == 'image':
            n.begin()

            nuke.toNode('watermark_image')['file'].fromScript('[value parent.wm_file]')
            n.end()
            n['w_text_knob'].setEnabled(False)
            n['wm_file'].setEnabled(True)

            n['tiles'].setValue(7.4)
            n['translate'].setValue([0, 0])
            n['rotate'].setValue(0)
            n['scale'].setValue(1)
コード例 #7
0
ファイル: viewerSync.py プロジェクト: ThoriumGroup/thorium
def _extract_viewer_list(viewer):
    """Extracts a list of Viewer nodes from a callback.

    Searches a viewer node for a viewerSync callback, and extracts the
    value of the `viewers` arg.

    Args:
        viewer : (<nuke.nodes.Viewer>)
            The viewer node with the callback attached.

    Returns:
        [<nuke.nodes.Viewer>]
            A list of viewer nodes that were listed in the callback arg.

    Raises:
        ValueError
            If the callback found on the viewer is present, but not for
            viewerSync.

    """
    callback = viewer['knobChanged'].value()

    if not callback:
        return []
    elif 'viewerSync' not in callback:
        raise ValueError("Not a viewerSync'd viewer.")

    callback = callback.replace('viewerSync.sync_viewers(', '')[:-1]
    linked_viewers = literal_eval(callback)
    viewer_nodes = [
        nuke.toNode(node) for node in linked_viewers if nuke.toNode(node)
    ]

    return viewer_nodes
コード例 #8
0
ファイル: chanData.py プロジェクト: robmoggach/nuke-py
def getKnobChannels(node):
  '''
  function that searches a node for knobs that have
  data for import or export and returns a list
  '''
  knobData = nuke.toNode(node).writeKnobs(1)
  knobIndex = nuke.toNode(node).writeKnobs(0)
  knobList = knobIndex.split(' ')
  knobs = []
  for knob in knobList:
    if knob in KNOBS_TO_IGNORE:
      continue
    if knob in KNOBS_3D:
      knob3dRegex = re.compile('%s \{[0-9]* [0-9]* [0-9]*\}' % knob)
      knob3dRegexMatch = knob3dRegex.search(knobData)
      if knob3dRegexMatch != None:
        knobs.append(knob+'.x')
        knobs.append(knob+'.y')
        knobs.append(knob+'.z')
        continue
    if knob in KNOBS_UV:
      knobUVregex = re.compile('%s \{[0-9]* [0-9]*\}' % knob)
      knobUVregexMatch = knobUVregex.search(knobData)
      if knobUVregexMatch != None:
        knobs.append(knob+'.u')
        knobs.append(knob+'.v')
        continue
    knobs.append(knob)
  return knobs
コード例 #9
0
ファイル: createReadWrite.py プロジェクト: robmoggach/nuke-py
def createWriteFromRead(nodes=[]):
  '''
  function to create a write node
  from a selected read node
  '''

  # if no nodes are defined look for selected nodes
  if not nodes:
    nodes = nuke.selectedNodes()
  
  # if nodes is still empty, nothing is selected
  if not nodes:
    nuke.message('ERROR: No node(s) selected.')
    return
  
  for node in nodes:
    _class = node.Class()
    if _class == "Read":
      file = node.knob('file').getValue()
      proxy = node.knob('proxy').getValue()
      first = nuke.toNode('root').knob('first_frame').getValue()
      last = nuke.toNode('root').knob('last_frame').getValue()
      xpos = node.knob('xpos').getValue()
      ypos = int(node.knob('ypos').getValue()) + 40
      knobs = []
      fields = ('file','proxy','first','last','xpos','ypos')
      for entry in fields:
        if eval(entry) != '':
          knobs.append(entry)
          #knobs.append(str(eval(entry)))
      nuke.createNode('Write', string.join(knobs))  
  return
コード例 #10
0
ファイル: diskcache.py プロジェクト: RonThomas/nuke.env
def getDiskCachePerc5():
  
  # Get Preference Settings
  totalDiskCacheGB = nuke.toNode('preferences').knob('diskCacheGB').value()
    
  diskCacheDir = nuke.toNode('preferences').knob('DiskCachePath').value()
  tileCacheDir = nuke.toNode('preferences').knob('DiskCachePath').value() + "/tilecache"
  if (diskCacheDir.find("getenv") != -1):
    diskCacheDir = os.environ['NUKE_TEMP_DIR']
    tileCacheDir = os.environ['NUKE_TEMP_DIR'] + "/tilecache"
    
    
  # DiskCache
  diskCachedBytes = 0
  for (path, dirs, files) in os.walk(diskCacheDir):
    for file in files:
      filename = os.path.join(path, file)
      diskCachedBytes += os.path.getsize(filename)
      
  paintCachedBytes = 0
  for (path, dirs, files) in os.walk(tileCacheDir):
    for file in files:
      filename = os.path.join(path, file)
      paintCachedBytes += os.path.getsize(filename)   
      
  
      
  # Work out the Cache Limit set in Bytes
  totalDiskCacheBytes = totalDiskCacheGB*pow(1024,3)
  # Percentage Cache Used
  diskCachePerc = ((diskCachedBytes-paintCachedBytes)/totalDiskCacheBytes)*100
  
  return diskCachePerc
コード例 #11
0
    def setShot(self, shot):
        
        try:
            scene = str(shot.split("_")[0])+"_"+str(shot.split("_")[1])
        except:
            scene = 'n/a'
        
        if not shot == 'n/a':
            
            try:
                #cameraGrp = self.node.knob("grpS_"+shot)
                camera = nuke.toNode(self.job+'_'+shot+'_renderCamera')
                #self.node.knob('cameraName').setValue(shot)
            except:
                pass
            try:
                version = camera.knob('versionHub').value()
            except:
                version = 'n/a'
            try:
                self.cameraSwitch.setInput(0, camera)
            except:
                pass
        
        if shot == 'n/a':
            version = 'n/a'
            #self.cameraSwitch.setInput(0)
            
        self.node.knob('shotList').setValue(shot)
        
        #set the timerange
        timeRange = hubUtils.getShotTimeRangeInfo(shot, scene, hubUtils.HubShotTimeRange.WORKING)['workFrameRange']
        
        if timeRange in ['n/a', 'n/a ', 'n/a - n/a', 'n/a-n/a']:
            try:
                camera = nuke.toNode(self.job+'_'+shot+'_renderCamera')
                label = camera.knob('label').value()
                if label:
                    timeRange = str(label)
            except:
                pass
        try:
            self.node.knob('actualCamera').setValue("<FONT COLOR=\"#7777EE\"> v"+version+" :   "+timeRange+"<\FONT>")
            self.node.knob('txt_'+shot).setValue("handles: <FONT COLOR=\"#7777EE\">"+timeRange+"<\FONT>")
        except:
            pass
            
        if not timeRange in ['n/a', 'n/a ', 'n/a - n/a', 'n/a-n/a']:

            firstFrame, lastFrame = timeRange.split('-')[0], timeRange.split('-')[1]
            
            if not firstFrame == 'n/a' and not lastFrame == 'n/a':
                
                # set root frame range
                nuke.root().knob('first_frame').setValue(int(firstFrame))
                nuke.root().knob('last_frame').setValue(int(lastFrame))
                # if the current frame is not in the frame range set frame at the begining of the shot
                if nuke.frame() not in range(int(firstFrame), int(lastFrame)):
                    nuke.frame(int(firstFrame))
コード例 #12
0
ファイル: nukeCommands.py プロジェクト: jonntd/dmptools
def connectMasterScene():
    """
        try to connect the master scene to the Viewer1 is exists
    """
    try:
        nuke.toNode('Viewer1').setInput(0, nuke.toNode('MASTER_SCENE'))
    except:
        print 'no master scene found!'
コード例 #13
0
ファイル: TX_Ramp.py プロジェクト: RonThomas/nuke.env
def createRamp():
	## Variables
	n = nuke.thisNode()
	pCount = n['pCounter'].value()


	## Create ramp expressions
	if pCount == 0:
		n.begin()
		nuke.toNode('COLORAMA')['expr0'].setValue( '(1-x/width)*start_color.r  + x/width*end_color.r' )
		nuke.toNode('COLORAMA')['expr1'].setValue( '(1-x/width)*start_color.g  + x/width*end_color.g' )
		nuke.toNode('COLORAMA')['expr2'].setValue( '(1-x/width)*start_color.b  + x/width*end_color.b' )
		nuke.toNode('COLORAMA')['expr3'].setValue( '(1-x/width)*start_color.a  + x/width*end_color.a' )
		n.end()
	
	else :
		n.begin()
		rampExpr = ''

		for i in range(int(pCount)):
			## Variables
			pt_i  = 'p%03d.x' % (i+1)
			
			if i == 0 :
				pt_im = 'start.x'
			else :
				pt_im = 'p%03d.x'  % (i)	
				
			if i+1 == pCount:
				pt_ip = 'end.x'
			else :
				pt_ip = 'p%03d.x' % (i+2)
			
			c_i  = 'p%03d_color' % (i+1)
			if i == 0 :
				c_im = 'start_color'
			else :
				c_im = 'p%03d_color' % (i)	
				
			if i+1 == pCount:
				c_ip = 'end_color'
			else :
				c_ip = 'p%03d_color' % (i+2)
	
	
			#expression =  'x>=' + pt_im + ' && x<' + pt_i + '? (1-x/(' + pt_i + '-' + pt_im + '))*' + c_im + '.%s + x/(' + pt_i + '-' + pt_im + ')*' + c_i + '.%s  : x>=' + pt_i + ' && x<' + pt_ip + '? (1-x/(' + pt_ip + '-' + pt_i + '))*' + c_i + '.%s + x/(' + pt_ip + '-' + pt_i + ')*' + c_ip + '.%s  : '
			expression =  'x>=' + pt_im + ' && x<' + pt_i + '? (1-(x-' + pt_im + ')/(' + pt_i + '-' + pt_im + '))*' + c_im + '.%s + (x-' + pt_im + ')/(' + pt_i + '-' + pt_im + ')*' + c_i + '.%s  : x>=' + pt_i + ' && x<' + pt_ip + '? (1-(x-' + pt_i + ')/(' + pt_ip + '-' + pt_i + '))*' + c_i + '.%s + (x-' + pt_i + ')/(' + pt_ip + '-' + pt_i + ')*' + c_ip + '.%s  : '
		
			rampExpr = rampExpr + expression
		
		rampExpr = rampExpr + ' 0'
	
		## Set expressions
		for i in range(4):
			chan = ['r', 'g', 'b', 'a']
			nuke.toNode('COLORAMA')['expr'+ str(i)].setValue(rampExpr.replace('%s', chan[i]))

		n.end()
コード例 #14
0
ファイル: FnCutDetector.py プロジェクト: Aeium/dotStudio
 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)
コード例 #15
0
ファイル: nukeCommands.py プロジェクト: jonntd/dmptools
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()
コード例 #16
0
ファイル: menu.py プロジェクト: raiscui/nuke7plugin
def preferencesCreatedCallback():
    p = nuke.toNode('preferences')
    
    #Setup J_Ops prefs knobs if they don't exist.
    try:
        jopsKnobsPresent = p["J_Ops"]
    except (SyntaxError, NameError):
        k = nuke.Tab_Knob("J_Ops")
        k.setFlag(nuke.ALWAYS_SAVE)
        p.addKnob(k)

        v = nuke.Double_Knob("j_ops_ver", "j_ops_ver")
        v.setFlag(nuke.ALWAYS_SAVE)
        v.setFlag(nuke.INVISIBLE)
        v.setValue(2.0101)
        p.addKnob(v)
        
        k = nuke.Boolean_Knob("j_ops_enable_drop", "Improved drag and drop")
        k.setFlag(nuke.ALWAYS_SAVE)
        k.setFlag(nuke.STARTLINE)
        k.setValue(1.0)
        k.setTooltip("Enable/disable a somewhat improved drag and drop behaviour. Requires Nuke restart to take effect. Adds creation of geo, camera, light and vectorfield nodes based on incoming file extensions, as well as support for sequences when dropping folders onto DAG. Warning: does not observe hash vs regex file path expression, due to Nuke python functions ignoring it.")
        p.addKnob(k)

        k = nuke.Text_Knob("j_ops_dropdivider_label", "Drag And Drop")
        k.setFlag(nuke.ALWAYS_SAVE)
        p.addKnob(k)

        k = nuke.Boolean_Knob("j_ops_drop_recurse", "Recurse directories")
        k.setFlag(nuke.ALWAYS_SAVE)
        k.setValue(1.0)
        k.setTooltip("Enable/disable recursion into directories dropped on DAG. When enabled will result in entire directory structure being imported into DAG, when disabled only the directory dropped will be imported (ie none of its sub directories)")
        p.addKnob(k)
    
    #Knobs created. Hide obselete ones, update ver
    #2.1
	try:
		p["j_ops_ver"].setValue(2.0201)
		try:
			p["j_ops_enable_bookmark"].setFlag(nuke.INVISIBLE)
		except Exception:
			pass
	except Exception:
		pass
                    
    #Check for preference setting, and if drop enabled add its callback/
    dropEnabled = False
    try:
        dropEnabled = nuke.toNode('preferences')["j_ops_enable_drop"].getValue()
    except (SyntaxError, NameError):
        pass

    if dropEnabled == True:
        nukescripts.drop.addDropDataCallback(jopsDropHandler)
コード例 #17
0
 def __init__(self):
     
     self.node = nuke.thisNode()
     self.job = jobtools.jobName()
     self.scene = jobtools.sceneName()
     self.shot = jobtools.shotName()
     
     # get some nodes inside the group
     
     self.scene3D = nuke.toNode('scene')
     self.cameraSwitch = nuke.toNode('cameraSwitch')
コード例 #18
0
 def makeGroup(self): 
     if len(self.lista) >= 2:
         for shuffleknob in self.sGroup:
             shuffleknob['selected'].setValue(True) 
         node = nuke.collapseToGroup(show=False)
         node.autoplace()
         gName = node.name()
         nuke.toNode(gName)["name"].setValue("Exr Merge %s" %self.nIncrement)
         self.nIncrement += 1
         #node.lock_connections(True)
     else:
         pass
コード例 #19
0
ファイル: NodeGraphGrid.py プロジェクト: gobomus/Pr_Suite
def NodeGraphGrid():
	show_value = nuke.toNode("preferences").knob("show_grid").value()
	show = nuke.toNode("preferences").knob("show_grid")
	snap_value = nuke.toNode("preferences").knob("SnapToGrid").value()
	snap = nuke.toNode("preferences").knob("SnapToGrid")

	if show_value == 1 & snap_value == 1:
		show.setValue(0)
		snap.setValue(0)
	else:
		show.setValue(1)
		snap.setValue(1)
コード例 #20
0
ファイル: diskcache.py プロジェクト: RonThomas/nuke.env
  def __init__(self):
    nukescripts.PythonPanel.__init__( self, 'DiskCache', 'uk.co.thefoundry.DiskCache')
    
    # CREATE KNOBS
    self.diskCachePrefText = nuke.Text_Knob('disk_cache_pref_GB','Disk cache limit:')
    self.addKnob( self.diskCachePrefText)
    self.diskCachePrefText.setValue('?GB')
    self.diskCachePercUsed = nuke.Double_Knob('disk_cache_pref_GB','% used:')
    self.addKnob( self.diskCachePercUsed)
    self.diskCachePercUsed.setValue(50)
    self.diskCachePercUsed.setRange(0,100)
    self.diskCachePercUsed.setEnabled(False)
   
    totalCacheGB = nuke.toNode('preferences').knob('diskCacheGB').value()
    
    self.diskCachePrefText.setValue(str(totalCacheGB) + 'GB')
 
    # Check if Major Version is 6 or later... 
    if nuke.env['NukeVersionMajor'] >= 6:
      self.paintCachePrefText = nuke.Text_Knob('paint_cache_pref_GB','Paint cache limit:')
      self.addKnob( self.paintCachePrefText)
      self.paintCachePrefText.setValue('?GB')
      self.paintCachePercUsed = nuke.Double_Knob('paint_cache_pref_GB','% used:')
      self.addKnob( self.paintCachePercUsed)
      self.paintCachePercUsed.setValue(50)
      self.paintCachePercUsed.setRange(0,100)
      self.paintCachePercUsed.setEnabled(False)
      self.paintCachePercUsed.setFlag(0x00002000)
	  
      paintCacheGB = nuke.toNode('preferences').knob('PaintCacheGB').value()
      self.paintCachePrefText.setValue(str(paintCacheGB) + 'GB')
      
    # Update Cache usage button
    self.updateButton = nuke.Script_Knob('update','Update')
    self.addKnob(self.updateButton) 
    
    # Clear DiskCacheButton   
    self.clearCacheButton = nuke.Script_Knob('clearCache','Clear Disk Cache')
    self.addKnob(self.clearCacheButton) 
    
    self.addKnob(nuke.Text_Knob('',''))
	
    # Clear Buffer Button
    self.clearBuffers = nuke.Script_Knob('clearBuffers','Clear Buffers')
    self.addKnob(self.clearBuffers) 
	
    self.bufferReport = nuke.nuke.Multiline_Eval_String_Knob( "bufferReport", "Buffer Report" )
    self.addKnob(self.bufferReport)
    self.bufferReport.setValue(str(nukescripts.cache_report(str())))	


    # Initially populate the Sliders...
    updateSliders(self)
コード例 #21
0
    def frame_info(self, node, knob_value, knob_eval):
        """Returns all information required to create a Read node"""
        filepath = self.filepath_from_disk(node, knob_value, knob_eval)
        if isinstance(filepath, type(None)):
            not_found = 'Filepath does not exist and/or cannot be' + \
                        'translated:\n' + node + ': ' + knob_eval + \
                        '\n\nCreate Read node anyway and guess framerange?'
            if nuke.ask(not_found):
                limit_to_range = self.get_knob_value(node, 'use_limit')
                if (not isinstance(limit_to_range, type(None)) and
                        int(limit_to_range) == 1):
                    # Use explicit framerange set on Write node
                    firstframe = int(self.get_knob_value(node, 'first'))
                    lastframe = int(self.get_knob_value(node, 'last'))
                else:
                    # Look at the framerange coming into the Write node
                    firstframe = int(nuke.toNode(node).frameRange().first())
                    lastframe = int(nuke.toNode(node).frameRange().last())

                filepath_processed = self.determine_relativity(knob_eval)
                node_options = self.node_options(node)
                frame_data = {
                            'filepath': filepath_processed,
                            'firstframe': firstframe,
                            'lastframe': lastframe,
                            'node_options': node_options
                            }
                return frame_data

        else:
            filepath = os.path.abspath(filepath)
            filepath = filepath.replace('\\', '/')
            current_frame = re.findall(r'\d+', filepath)[-1]
            padding = len(current_frame)
            basename = filepath[: filepath.rfind(current_frame)]
            filetype = filepath.split('.')[-1]
            firstframe, lastframe = self.get_framerange(node,
                                                        basename,
                                                        filetype)
            filepath_processed = self.process_filepath(filepath,
                                                       filetype,
                                                       basename,
                                                       padding,
                                                       knob_value)
            node_options = self.node_options(node)
            frame_data = {
                        'filepath': filepath_processed,
                        'firstframe': firstframe,
                        'lastframe': lastframe,
                        'node_options': node_options
                        }
            return frame_data
コード例 #22
0
ファイル: diskcache.py プロジェクト: RonThomas/nuke.env
def getCachePerc():
  folder = nuke.toNode('preferences').knob('DiskCachePath').value()
  cachedBytes = 0
  for (path, dirs, files) in os.walk(folder):
    for file in files:
      filename = os.path.join(path, file)
      cachedBytes += os.path.getsize(filename)
  # Work out the Cache Limit set in Bytes
  totalCacheGB = nuke.toNode('preferences').knob('diskCacheGB').value()
  totalCacheBytes = totalCacheGB*pow(1024,3)
  # Percentage Cache Used
  cacheUsed = (cachedBytes/totalCacheBytes)*100
  return cacheUsed
コード例 #23
0
ファイル: cornerPinToTracker.py プロジェクト: hradec/pipeVFX
def cornerPinToTracker():

    cp = nuke.selectedNode()

    cp1 = cp["to1"].animations()
    cp2 = cp["to2"].animations()
    cp3 = cp["to3"].animations()
    cp4 = cp["to4"].animations()

    tr = nuke.createNode("Tracker3")
    tr.knob("enable2").setValue("True")
    tr.knob("enable3").setValue("True")
    tr.knob("enable4").setValue("True")
    tr.knob("warp").setValue("srt")
    tr.knob("transform").setValue("match-move")
    tr.knob("use_for1").setValue("all")
    tr.knob("use_for2").setValue("all")
    tr.knob("use_for3").setValue("all")
    tr.knob("use_for4").setValue("all")
    tr.knob("reference_frame").setValue(nuke.frame())

    nuke.toNode(tr.knob("name").value())["track1"].copyAnimations(cp1)
    nuke.toNode(tr.knob("name").value())["track2"].copyAnimations(cp2)
    nuke.toNode(tr.knob("name").value())["track3"].copyAnimations(cp3)
    nuke.toNode(tr.knob("name").value())["track4"].copyAnimations(cp4)
コード例 #24
0
    def frameDo(self):
        b = self.sender()
        if b is None or not isinstance(b, QtGui.QPushButton):
            return

        if not self.delmodel.isChecked():
            vName, frame = self.frameButtons[b]
            nuke.toNode(vName).knob("frame").setValue(int(frame))
        else:
            print "del"
            vName, frame = self.frameButtons.pop(b)
            self.data[vName]["frame"].pop(frame).deleteLater()
            del self.js_data[vName]["frame"][frame]
            self.chkTab(vName)
            self.proDataSave()
コード例 #25
0
def makeGroup(): 
    if len(lista) >= 2:
        global node, nIncrement
        for shuffleknob in sGroup:
            shuffleknob['selected'].setValue(True) 
        node = nuke.collapseToGroup(show=False)
        node.autoplace()
        gName = node.name()
        #print gName
        nuke.toNode(gName)["name"].setValue("Exr Merge %s" %nIncrement)
        nIncrement += 1
        #node.lock_connections(True)
        #print node
    else:
        pass
コード例 #26
0
ファイル: canvas.py プロジェクト: hobbeslovestuna/VFX-scripts
def doIT():
    n = nuke.selectedNode()
    print '_'*20
    print 'Selected Node on which the calculation will be processed %s' %n['name'].value()
    
    first   = nuke.Root()['first_frame'].value()
    last    = nuke.Root()['last_frame'].value()
    total   = last - first
    
    maxBBoxX = nuke.toNode('FrameBlend1').bbox().x()
    maxBBoxY = nuke.toNode('FrameBlend1').bbox().y()
    maxBBoxR = nuke.toNode('FrameBlend1').bbox().w() + maxBBoxX
    maxBBoxT = nuke.toNode('FrameBlend1').bbox().h() + maxBBoxY
    
    maxBBox = [maxBBoxX, maxBBoxY, maxBBoxR, maxBBoxT]
    print 'Value of the BBox '+str(maxBBox)
    
    task        = nuke.ProgressTask('Getting Frame for max BBox\n value at x,y,r,t')
    progIncr    = 100.0 / total
    result      = []
    for frame in xrange(int(first), int(last)):
        
        frame = float(frame)

        if task.isCancelled():
            nuke.executeInMainThread(nuke.message, args=('Calculation aborted'))
            return
        
        
        nuke.frame(frame)
        time.sleep(.1)
        
        # if n.bbox().x() == maxBBox[0]:
        #     print 'x found at frame %f' %frame
        #     result.append(('x', frame))
        # if n.bbox().y() == maxBBox[1]:
        #     print 'y found at frame %f' %frame
        #     result.append(('y', frame))
        print frame, n.bbox().w()-maxBBox[0], maxBBox[2]
        if n.bbox().w() == maxBBox[2]:
            print 'r found at frame %f' %frame
        if n.bbox().h() == maxBBox[3]:
            print 't found at frame %f' %frame
        
        task.setProgress(int(frame * progIncr))
        task.setMessage('Processing frame : '+str(frame))

    return 
コード例 #27
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...'
コード例 #28
0
ファイル: load_src.py プロジェクト: horitin/pipeline
def load_src():
	import pipe
	asset_obj = pipe.Projects().GetAssetByInfo(nuke.root().name())
	if not asset_obj: return
	shot_obj = asset_obj.GetShot()
	if not shot_obj: raise Exception('Shot not found')
	src_path = shot_obj.GetSrcPath()
	sequences = condensing_is(src_path,'src')
	if not sequences: nuke.message("There aren't files in folder SRC")
	filenameSearch = "Load"
	enumerationPulldownp = "None " + ' '.join(sequences.keys()) 
	p = nuke.Panel("Presets selection")
	p.addEnumerationPulldown("SRC to load:", enumerationPulldownp)
	p.addButton("Cancel") 
	p.addButton("Load")
	
	result = p.show()
	enumVal = p.value("SRC to load:")
	if enumVal == 'None': return
	#nuke.message(sequences[enumVal])
	n = nuke.toNode(enumVal)
	if not n: 
		n = nuke.createNode('Read', inpanel=False)
		n.setName(enumVal)
	n.knob('file').fromUserText(sequences[enumVal])
コード例 #29
0
ファイル: nukeCommands.py プロジェクト: jonntd/dmptools
def setDefaultSettings():
    """
    set some default startup settings
    """
    if PLATFORM == 'Windows':
        font = 'Consolas'
    else:
        font = 'Monospace'

    preferenceNode = nuke.toNode('preferences')
    # viewer settings
    preferenceNode['maxPanels'].setValue(5)
    preferenceNode['TextureSize'].setValue('2048x2048')
    preferenceNode['viewer_bg_color_3D'].setValue(1280068863)
    preferenceNode['viewer_fg_color_3D'].setValue(4294967295L)
    preferenceNode['Viewer3DControlEmulation'].setValue('Maya')
    preferenceNode['middleButtonPans'].setValue(False)
    preferenceNode['dot_node_scale'].setValue(1.5)

    # script editor settings
    preferenceNode['clearOnSuccess'].setValue(False)
    preferenceNode['echoAllCommands'].setValue(True)
    preferenceNode['ScriptEditorFont'].setValue(font)
    preferenceNode['ScriptEditorFontSize'].setValue(12.0)
    preferenceNode['kwdsFgColour'].setValue(2629566719L)
    preferenceNode['stringLiteralsFgColourDQ'].setValue(10354943)
    preferenceNode['stringLiteralsFgColourSQ'].setValue(10354943)
    preferenceNode['commentsFgColour'].setValue(2442236415L)
コード例 #30
0
ファイル: FnAxis.py プロジェクト: ImageEngine/cortex
	def __init__( self, node ) :

		if isinstance( node, str ) :

			axis = nuke.toNode( node )

		self.__node = node
コード例 #31
0
ファイル: addCallbacks.py プロジェクト: tws0002/nukeScripts
def removeStartRGBAChannel():
    keep = nuke.toNode('multiKeepChannels2')
    if keep:
        keep['channels2'].setValue('none')
コード例 #32
0
    stub = config.get('shot_template', '%s'%sys.platform)
    cfg_backdrop_node = config.get('shot_template', 'backdrop_node')
    cfg_backdrop_node_write = config.get('shot_template', 'backdrop_node_write')
    cfg_main_read_node = config.get('shot_template', 'main_read_node')
    cfg_main_write_node = config.get('shot_template', 'main_write_node')
    cfg_viewer_cc_node = config.get('shot_template', 'viewer_cc_node')

    if not master_nuke_script:
        output_script = full_nuke_script_path
    log.info("Building Nuke Script for final shot from template.")
    comp_render_dir_dict = { 'pathsep' : os.path.sep, 'compdir' : nuke_script_starter }
    comp_write_path = os.path.join(shot_dir, g_shot_comp_render_dir.format(**comp_render_dir_dict), "%s.%s.%s"%(nuke_script_starter, g_write_frame_format, g_write_extension))
    log.info("About to open: %s"%stub)
    nuke.scriptOpen(stub)
    log.info("Shot template loaded.")
    bd_node = nuke.toNode(cfg_backdrop_node)
    bd_node_w = nuke.toNode(cfg_backdrop_node_write)
    main_read = nuke.toNode(cfg_main_read_node)
    main_write = nuke.toNode(cfg_main_write_node)
    main_cdl = nuke.toNode(cfg_viewer_cc_node)
    
    frames_glob = mainplate.replace(g_write_frame_format, '*')
    frames_list = sorted(glob.glob(frames_glob))
        
    # handle non-standard plate format
    start_file_path = frames_list[0]
    start_file_base = os.path.basename(start_file_path)
    start_file_match = imgseq_re.search(start_file_base)
    file_base = start_file_match.group('base')
    start_frame = int(start_file_match.group('frame'))
    head_in = start_frame + int(config.get('scan_ingest', 'head_in_offset'))
コード例 #33
0
    def mergeCamera(self,layer,_source,_bd_X,backDropStr):
        #获取选择的Read节点的个数
        self.numSelect=len(_source)
        #所选择的_contactSheet方格 _constant黑板 _backDropStr背板
        _contactSheet,_constant,_bd='','',''
        #新创建的_contactSheet方格 _constant黑板 _backDropStr背板
        _contactSheet_1,_constant_1,_backDropStr='','',''
        #保存的摄像机字典
        _sortedCam = {}
        _backDropStr=backDropStr.knob('label').value()
        #获取所选择的contactSheet方格 _constant黑板 _backDropStr背板中的信息
        if len(nuke.selectedNodes('ContactSheet')):
            _contactSheet=nuke.selectedNodes('ContactSheet')[0]
            _contactSheet.setSelected(False)
            #获取所选择的ContactSheet的信息
            conts_w=_contactSheet.knob('rows').value()
            conts_h=_contactSheet.knob('columns').value()
            conts_row=_contactSheet.knob('roworder').value()
            conts_width=_contactSheet.knob('width').value()
            conts_height=_contactSheet.knob('height').value()
            const_color=_contactSheet.knob('colorder').value()
            const_split=_contactSheet.knob('splitinputs').value()

        if len(nuke.selectedNodes('Constant')):
            _constant=nuke.selectedNodes('Constant')[0]
            _constant.setSelected(False)

        if len(nuke.selectedNodes('BackdropNode')):
            _bd=nuke.selectedNodes('BackdropNode')[0]
            _bd.setSelected(False)
        else:
            nuke.message('No BackdropNode Nodes Selected...')
            return

        #判断是否选择了Shuffle
        if len(nuke.selectedNodes('Shuffle')):
            self.flag=True
        else:
            self.flag=False


        #获取BackdropNode的大小
        _bd_w=_bd.knob('bdwidth').value()
        _bd_h=_bd.knob('bdheight').value()

        #获取BackdropNode的位置
        _bd_pos=[_bd.xpos(),_bd.ypos()]
        #以第一个素材为例,定义素材的格式_w,_h
        _node=_source[0]
        #素材大小
        _w=_node.knob('format').value().width()
        _h=_node.knob('format').value().height()

        #素材屏幕大小
        _bbox=[_node.screenWidth(),_node.screenHeight()]
        _pos=[_node.xpos(),_node.ypos()]

        #判断素材的格式是否为EXR
        myfileFlagEXR=False

        myfileName=_source[0]['file'].value()    
        myfileNameType = os.path.splitext(myfileName)[1]
        if myfileNameType:
            if myfileNameType.find('exr')>=0:
                myfileFlagEXR=True


        #常见节点,并设置它的坐标为第一个素材的节点的位置
        if not myfileFlagEXR:
            return

        _dot_bd=nuke.nodes.Dot()
        _dot_bd.setXYpos(_bd_pos[0]+int(_bd_w),_bd_pos[1]+int(_bd_h))

        if const_split:
            starframes=_contactSheet.knob('startframe').value()
            endframes=_contactSheet.knob('endframe').value()
            _contactSheet_1 = nuke.nodes.ContactSheet(width=conts_width,height=conts_height,rows=conts_w,columns=conts_h,roworder=conts_row,colorder=const_color,splitinputs=True,startframe=starframes,endframe=endframes).name()
        else:
            _contactSheet_1 = nuke.nodes.ContactSheet(width=conts_width,height=conts_height,rows=conts_w,columns=conts_h,roworder=conts_row,colorder=const_color,splitinputs=False).name()  

        _node_1 = nuke.toNode(_contactSheet_1)

        #在所有的尺寸格式中,寻找跟素材一样的样式,在创建黑板,并设置位置
        _allFormat = nuke.formats()
        for _eachFormat in _allFormat:
               if _eachFormat.width()==_w and _eachFormat.height()==_h:
                   _constant_1=nuke.nodes.Constant(format=_eachFormat.name()).name()
                   _node_1=nuke.toNode(_constant_1)
        
        _sheetNode_1= nuke.toNode(_contactSheet_1)
        _conNode_1=nuke.toNode(_constant_1)

        for _x in range(18):
            _sheetNode_1.setInput(_x,_conNode_1)

        mii=0
        newMyShuffle_clone=[]
        for each in  _source:
            if mii==0:
                #创建管道
                myShuffle_1=nuke.nodes.Shuffle()

                myShuffle_1['in'].setValue(layer)
                myShuffle_1['hide_input'].setValue(True)
                for i in range(18):
                    if self.flag:
                        if _contactSheet.input(i).input(0)==each:
                            myShuffle_1.setInput(0,each)
                            #方格与管道连接
                            _sheetNode_1.setInput(i,myShuffle_1)
                            #设置管道的位置
                            myS_w=each.xpos()-_bd_X
                            myS_h=each.ypos()
                            myShuffle_1.setXYpos(_dot_bd.xpos()+myS_w+10,myS_h)
                            break
                    else:
                        if _contactSheet.input(i)==each:
                            #管道与Read节点连接
                            myShuffle_1.setInput(0,each)
                            #方格与管道连接
                            _sheetNode_1.setInput(i,myShuffle_1)
                            #设置管道的位置
                            myS_w=each.xpos()-_bd_X
                            myS_h=each.ypos()
                            myShuffle_1.setXYpos(_dot_bd.xpos()+myS_w+10,myS_h)
                            break
            else:
                self.setSelecteNone()
                newMyShuffle_1 = nuke.clone(myShuffle_1)
                for i in range(18):
                    if self.flag:
                        if _contactSheet.input(i).input(0)==each:
                            newMyShuffle_1.setInput(0, each)
                            _sheetNode_1.setInput(i, newMyShuffle_1)
                            myS_w=each.xpos()-_bd_X
                            myS_h=each.ypos()
                            newMyShuffle_1.setXYpos(_dot_bd.xpos()+myS_w+10,int(myS_h))
                            newMyShuffle_clone.append(newMyShuffle_1)
                            break  
                    else:
                        if _contactSheet.input(i)==each:
                            newMyShuffle_1.setInput(0, each)
                            _sheetNode_1.setInput(i, newMyShuffle_1)
                            myS_w=each.xpos()-_bd_X
                            myS_h=each.ypos()
                            newMyShuffle_1.setXYpos(_dot_bd.xpos()+myS_w+10,int(myS_h))
                            newMyShuffle_clone.append(newMyShuffle_1)
                            break

            mii=mii+1
        for each in _source:
            each.setSelected(False)

        #创建背板,并设置名字,
        cs_w=_contactSheet.xpos()-_bd.xpos()
        cs_h=_contactSheet.ypos()
        _sheetNode_1.setXYpos(_dot_bd.xpos()+cs_w+10,cs_h)
        #_sheetNode_1.setInput(0,_contactSheet)

        const_w=_constant.xpos()-_bd.xpos()
        const_h=_constant.ypos()
        _conNode_1.setXYpos(_dot_bd.xpos()+const_w+10,const_h)

        #删除黑板
        conUsed = _conNode_1.dependent()
       # print conUsed

        if not conUsed:
            nuke.delete(_conNode_1)
        else:
            _conNode_1.setSelected(1)

        nuke.delete(_dot_bd)

        for shuffle in newMyShuffle_clone:
            shuffle.setSelected(True)
        _sheetNode_1.setSelected(True)
       
        _conNode_1.setSelected(True)
        myShuffle_1.setSelected(True)
        newMyShuffle_1.setSelected(True)

        myOldbdWidth_1=backDropStr.knob('bdwidth').value()
        myOldbdHeight_1=backDropStr.knob('bdheight').value()
        bd_1 = nukescripts.autoBackdrop()
        bd_1.knob('label').setValue(_backDropStr+'_'+layer)

        #myOldbdHeight_1 = bd_1.knob('bdheight').value()
        #myOldbdWidth_1=bd_1.knob('bdwidth').value()
        bd_1.knob('bdheight').setValue(myOldbdHeight_1) 
        bd_1.knob('bdwidth').setValue(myOldbdWidth_1) 
      
        bd_1.setSelected(True)
コード例 #34
0
 def get_knob_value(self, node, knob_name):
     """Return the value of a knob or return None if it is missing"""
     value = None
     if not isinstance(nuke.toNode(node).knob(knob_name), type(None)):
         value = nuke.toNode(node).knob(knob_name).getValue()
     return value
コード例 #35
0
ファイル: batch_edit.py プロジェクト: xmjtx/MJTLab
def batch_edit():
    knob_error = 'Knob does not exist.'
    value_error = 'Sat value need to be a number.'

    p = nuke.Panel('select edit mode')
    p.addEnumerationPulldown('select edit mode',
                             '"selected nodes" "node class"')
    if p.show() == 1:
        editmode = p.value('select edit mode')

        if editmode == 'selected nodes':
            snc = []
            for i in nuke.selectedNodes():
                snc.append(i.name())

            if len(snc) == 0:
                nuke.message('No node selected.')
            else:
                subp = nuke.Panel('batch edit - selected nodes')
                subp.addSingleLineInput('selected nodes', ','.join(snc))
                subp.addSingleLineInput('edit knob', '')
                subp.addEnumerationPulldown('set value type',
                                            '"Number" "Text" "Expression"')
                subp.addSingleLineInput('value', '')

                if subp.show() == 1:
                    nc = subp.value('selected nodes').split(',')
                    ek = subp.value('edit knob')
                    vt = subp.value('set value type')
                    sv = subp.value('value')

                    try:
                        for node in nc:
                            if nuke.toNode(node)[ek].isAnimated():
                                nuke.toNode(node)[ek].clearAnimated()
                            if vt == 'Number':
                                try:
                                    nuke.toNode(node)[ek].setValue(float(sv))
                                except TypeError:
                                    nuke.toNode(node)[ek].setValue(int(sv))
                            elif vt == 'Text':
                                nuke.toNode(node)[ek].setValue(str(sv))
                            elif vt == 'Expression':
                                nuke.toNode(node)[ek].setExpression(str(sv))
                        nuke.message('Edit succeed.')
                    except NameError:
                        nuke.message(knob_error)
                    except ValueError:
                        nuke.message(value_error)

        if editmode == 'node class':
            try:
                snc = nuke.selectedNode().Class()
            except:
                snc = ''

            subp = nuke.Panel('batch edit - node class')
            subp.addSingleLineInput('node class', snc)
            subp.addSingleLineInput('edit knob', '')
            subp.addEnumerationPulldown('set value type',
                                        '"Number" "Text" "Expression"')
            subp.addSingleLineInput('value', '')

            if subp.show() == 1:
                nc = subp.value('node class')
                ek = subp.value('edit knob')
                vt = subp.value('set value type')
                sv = subp.value('value')

                try:
                    for node in nuke.allNodes():
                        if node.Class() == nc:
                            if nuke.toNode(node.name())[ek].isAnimated():
                                nuke.toNode(node.name())[ek].clearAnimated()
                            if vt == 'Number':
                                try:
                                    nuke.toNode(node.name())[ek].setValue(
                                        float(sv))
                                except TypeError:
                                    nuke.toNode(node.name())[ek].setValue(
                                        int(sv))
                            elif vt == 'Text':
                                nuke.toNode(node.name())[ek].setValue(str(sv))
                            elif vt == 'Expression':
                                nuke.toNode(node.name())[ek].setExpression(
                                    str(sv))
                    nuke.message('Edit succeed.')
                except NameError:
                    nuke.message(knob_error)
                except ValueError:
                    nuke.message(value_error)
コード例 #36
0
def createLayout():
    nodes = selectedList()
    if not nodes:
        print "There is nothing selected!"
    else:
        #organize render elements and creat backdrops
        organizeRenders()
        #get result dictionary
        result = resultDict()
        #get dictionary for layout
        layoutNodes = layoutDict()
        if beauty_grp in layoutNodes.keys():
            if lightingPass_grp in layoutNodes.keys():
                #create lighting passes for building layout 
                layoutNodesList = []
                if lightSelect_grp in result.keys():
                    layoutNodesList = layoutNodes[lightSelect_grp] + layoutNodes[lightingPass_grp]
                    print "Layout Completed. Built with:\nBEAUTY"
                    for node in layoutNodesList:
                        print node.knob("label").value()
                else:
                    if 'Lighting' in layoutNodes.keys():
                        layoutNodesList = layoutNodes['Lighting'] + layoutNodes[lightingPass_grp]
                        print "Layout completed. Built with:\nBEAUTY"
                        for node in layoutNodesList:
                            print node.knob("label").value()
                    else:
                        print "Error building layout: Missing both " + lightSelect_grp + " and Lighting Pass"
                #get initial position
                centerPos = getCenterPos(nodes)
                offsetOriginY = 600
                originX = result[beauty_grp][0].xpos()
                originY = centerPos[1] + offsetOriginY
                offsetX = 0
                #store beauty postageStamp node
                pStamp_beauty = []
                #store all unpremultBy nodes
                unpremultNodeList = []
                #store all unpremultBy dot nodes
                unpremultNodeDotList = []
                #store all merge nodes
                mergeNodeList = []
                for node in layoutNodes[beauty_grp]:
                    posX = originX
                    posY = originY
                    pStampName = pStamp(node,posX,posY)
                    pStamp_beauty.append(nuke.toNode(pStampName))
                #create and connect light select postageStamp nodes
                for node in layoutNodesList:
                    #define offset value for each postageStamp
                    offsetX += 200
                    #define postageStamp position
                    posX = originX + offsetX
                    posY = originY + 100
                    #create postageStamp
                    pStampName = pStamp(node,posX,posY)
                    pStampNode = nuke.toNode(pStampName)
                    #create unpremultBy node and connect inputs
                    unpremultNode = nuke.createNode("UnpremultBy")
                    unpremultNode['xpos'].setValue(posX-75)
                    unpremultNode['ypos'].setValue(posY+100)
                    unpremultNodeDot = nuke.nodes.Dot()
                    unpremultNodeDot['xpos'].setValue(unpremultNode.xpos() + 34)
                    unpremultNodeDot['ypos'].setValue(pStamp_beauty[0].ypos() + 27)
                    unpremultNode.setInput(0,pStampNode)
                    unpremultNode.setInput(1,unpremultNodeDot)
                    unpremultNodeList.append(unpremultNode)
                    unpremultNodeDotList.append(unpremultNodeDot)
                    #create merge nodes
                    if len(unpremultNodeList) > 1:
                        mergeNode = nuke.nodes.Merge()
                        mergeNode['xpos'].setValue(posX-75)
                        mergeNode['ypos'].setValue(posY+300)
                        mergeNode['operation'].setValue('plus')
                        mergeNode.setInput(1,unpremultNode)
                        mergeNodeList.append(mergeNode)
                #connect merge nodes
                for i in range(0,len(mergeNodeList)):
                    if i == 0:
                        mergeNodeDot = nuke.nodes.Dot()
                        mergeNodeDot['xpos'].setValue(unpremultNodeList[0].xpos() + 34)
                        mergeNodeDot['ypos'].setValue(mergeNodeList[0].ypos() + 4)
                        mergeNodeDot.setInput(0,unpremultNodeList[0])
                        mergeNodeList[i].setInput(0,mergeNodeDot)
                    else:
                        mergeNodeList[i].setInput(0,mergeNodeList[i-1])
                #connect unpremultBy dots to beauty
                for d in range(0,len(unpremultNodeDotList)):
                    if d == 0:
                        unpremultNodeDotList[d].setInput(0,pStamp_beauty[0])
                    else:
                        unpremultNodeDotList[d].setInput(0,unpremultNodeDotList[d-1])
                #create copy node 
                copyNode = nuke.nodes.Copy()
                copyNode['from0'].setValue('rgba.alpha')
                copyNode['to0'].setValue('rgba.alpha')
                copyNode['xpos'].setValue(mergeNodeList[-1].xpos())
                copyNode['ypos'].setValue(mergeNodeList[-1].ypos() + 200)
                copyNodeDot = nuke.nodes.Dot()
                copyNodeDot['xpos'].setValue(pStamp_beauty[0].xpos() + 34)
                copyNodeDot['ypos'].setValue(copyNode.ypos() + 10)
                copyNodeDot.setInput(0,pStamp_beauty[0])
                copyNode.setInput(1,copyNodeDot)
                copyNode.setInput(0,mergeNodeList[-1])
                #create copyBBox node
                copyBBoxNode = nuke.nodes.CopyBBox()
                copyBBoxNode['xpos'].setValue(mergeNodeList[-1].xpos())
                copyBBoxNode['ypos'].setValue(mergeNodeList[-1].ypos() + 238)
                copyBBoxDot = nuke.nodes.Dot()
                copyBBoxDot['xpos'].setValue(pStamp_beauty[0].xpos() + 34)
                copyBBoxDot['ypos'].setValue(copyBBoxNode.ypos() + 4)
                copyBBoxDot.setInput(0,copyNodeDot)
                copyBBoxNode.setInput(1,copyBBoxDot)
                copyBBoxNode.setInput(0,copyNode)
                #create premult node
                premultNode = nuke.nodes.Premult()
                premultNode['xpos'].setValue(mergeNodeList[-1].xpos())
                premultNode['ypos'].setValue(mergeNodeList[-1].ypos() + 300)
                premultNode.setInput(0,copyBBoxNode)
            else:
                print "Error building layout: Missing lighting passes."
        else:
            print "Error building layout: Missing beayty pass."
コード例 #37
0
		Camera name of selected else None if user cancels.
	"""
    panel = nuke.Panel("connectCamera", 100)
    panel.addEnumerationPulldown('selectCamera', cameras)
    panel.addButton("cancel")
    panel.addButton("connect")
    if panel.show() != 0:
    	return panel.value("selectCamera")

def connectCamera():
	"""Connects the camera .
	"""
    # Getting all available cameras in the nukescript.
    cameras = ' '.join([n.name() for n in nuke.allNodes('Camera2')])
    if not cameras:
    	msg = '<center>No Camera Found\nimport some camera to connect.'
		nuke.message(msg)
		return

    selCamera = _cameraPanel(cameras)

    if not selCamera:
    	return
    # Creating a Dot node and connect with selected camera
    dot = nuke.createNode("Dot", inpanel=False)
    dot.setInput(0, nuke.toNode(selCamera))
    dot['label'].setValue(' \n'+selCamera)
    dot['note_font_size'].setValue(20)
    dot['note_font'].setValue('Bitstream Vera Sans Bold')
    dot['hide_input'].setValue(True)
コード例 #38
0
ファイル: load_luts_ip.py プロジェクト: ldunham1/pype
 def remove(self, container):
     from avalon.nuke import viewer_update_and_undo_stop
     node = nuke.toNode(container['objectName'])
     with viewer_update_and_undo_stop():
         nuke.delete(node)
コード例 #39
0
ファイル: TPD_ColorPalette.py プロジェクト: nncatan/TPD_Tools
def create_lp_tree(lightPassesList, inputNode):
    '''
        Creates an node tree of light pass nodes, links them together with dots and merges
    '''

    # Set initial dot and previous dot
    node = inputNode
    prev_node = node
    merge_list = []
    merge = None

    # For every item in the Light Passes List...
    for lp in lightPassesList:
        # If the list index is 1, create a light pass tree connected to the first dot.
        if lightPassesList.index(lp) == 0:
            if lp not in lightPassesMultiply:
                # Create Light Pass Nodes
                create_lp_nodes(lp, node)
        
        # If the list index is equal or greater than 2, create a light pass tree and connect it to a new dot.
        elif lightPassesList.index(lp) >= 1:
            if lp not in lightPassesMultiply:
                # Set position of and create a new dot
                x, y = prev_node.xpos(), prev_node.ypos()
                node = nuke.nodes.Dot(xpos=350+x,ypos=0+y,inputs=[prev_node])
                prev_node = node
                
                # Create Light Pass Nodes
                create_lp_nodes(lp, node)
                
                # Link merge node to previous merge node
                merge = nuke.toNode('{}_MERGE'.format(lp.upper()))
                merge.setInput(0, nuke.toNode('{}_MERGE'.format(lightPassesList[lightPassesList.index(lp)-1].upper())))
                merge_list.append(merge)


    for lp in lightPassesMultiply:
        if lp in lightPassesList:
            # Set position of and create a new dot
            x, y = prev_node.xpos(), prev_node.ypos()
            node = nuke.nodes.Dot(xpos=350+x,ypos=0+y,inputs=[prev_node])
            prev_node = node

            # Create Light Pass Nodes
            create_lp_nodes(lp, node)

            # Link merge node to previous merge node
            total_lp_items = len(lightPassesList)
            merge = nuke.toNode('{}_MERGE'.format(lp.upper()))
            if lightPassesMultiply.index(lp) == 0:
                merge.setInput(0, nuke.toNode('{}_MERGE'.format(lightPassesList[len(lightPassesList)-1].upper())))
                merge_list.append(merge)
            else:
                merge.setInput(0, nuke.toNode('{}_MERGE'.format(lightPassesMultiply[lightPassesMultiply.index(lp)-1].upper())))
                merge_list.append(merge)

    
    # Creates the last set of nodes that multiplies all the lightpasses with the DIP pass
    x, y = prev_node.xpos(), prev_node.ypos()
    dot1        = nuke.nodes.Dot        (xpos=384+x,ypos=0+y, inputs=[prev_node])
    shuffle1    = nuke.nodes.Shuffle    (xpos=350+x, ypos=72+y, inputs=[dot1])
    unpremult1  = nuke.nodes.Unpremult  (xpos=350+x, ypos=108+y, inputs=[shuffle1])
    blur        = nuke.nodes.Blur       (xpos=225+x, ypos=250+y, inputs=[merge])
    merge1      = nuke.nodes.Merge2     (xpos=350+x, ypos=250+y, inputs=[unpremult1, blur])
    premult     = nuke.nodes.Premult    (xpos=350+x, ypos=300+y, inputs=[merge1])
    output      = nuke.nodes.Output     (xpos=350+x, ypos=350+y, inputs=[premult])
    
    shuffle1['in'].setValue('DIP')
    shuffle1['label'].setValue('[value in]')
    blur['channels'].setValue('rgb')
    blur['size'].setValue(2)
    merge1['operation'].setValue('multiply')
    merge1['Achannels'].setValue('rgb')
    merge1['Bchannels'].setValue('rgb')
    merge1['output'].setValue('rgb')

    connect_first_merge_node()
コード例 #40
0
ファイル: load_sequence.py プロジェクト: 3dzayn/pype
    def update(self, container, representation):
        """Update the Loader's path

        Nuke automatically tries to reset some variables when changing
        the loader's path to a new file. These automatic changes are to its
        inputs:

        """

        from avalon.nuke import (update_container)

        node = nuke.toNode(container['objectName'])

        assert node.Class() == "Read", "Must be Read"

        repr_cont = representation["context"]

        file = api.get_representation_path(representation)

        if not file:
            repr_id = representation["_id"]
            self.log.warning(
                "Representation id `{}` is failing to load".format(repr_id))
            return

        file = file.replace("\\", "/")

        if "#" not in file:
            frame = repr_cont.get("frame")
            if frame:
                padding = len(frame)
                file = file.replace(frame, "#" * padding)

        # Get start frame from version data
        version = io.find_one({
            "type": "version",
            "_id": representation["parent"]
        })

        # get all versions in list
        versions = io.find({
            "type": "version",
            "parent": version["parent"]
        }).distinct('name')

        max_version = max(versions)

        version_data = version.get("data", {})

        self.first_frame = int(nuke.root()["first_frame"].getValue())
        self.handle_start = version_data.get("handleStart", 0)
        self.handle_end = version_data.get("handleEnd", 0)

        first = version_data.get("frameStart")
        last = version_data.get("frameEnd")

        if first is None:
            self.log.warning("Missing start frame for updated version"
                             "assuming starts at frame 0 for: "
                             "{} ({})".format(node['name'].value(),
                                              representation))
            first = 0

        first -= self.handle_start
        last += self.handle_end

        # Update the loader's path whilst preserving some values
        with preserve_trim(node):
            node["file"].setValue(file)
            self.log.info("__ node['file']: {}".format(node["file"].value()))

        # Set the global in to the start frame of the sequence
        loader_shift(node, first, relative=True)
        node["origfirst"].setValue(int(first))
        node["first"].setValue(int(first))
        node["origlast"].setValue(int(last))
        node["last"].setValue(int(last))

        updated_dict = {}
        updated_dict.update({
            "representation": str(representation["_id"]),
            "frameStart": str(first),
            "frameEnd": str(last),
            "version": str(version.get("name")),
            "colorspace": version_data.get("colorspace"),
            "source": version_data.get("source"),
            "handleStart": str(self.handle_start),
            "handleEnd": str(self.handle_end),
            "fps": str(version_data.get("fps")),
            "author": version_data.get("author"),
            "outputDir": version_data.get("outputDir"),
        })

        # change color of node
        if version.get("name") not in [max_version]:
            node["tile_color"].setValue(int("0xd84f20ff", 16))
        else:
            node["tile_color"].setValue(int("0x4ecd25ff", 16))

        if version_data.get("retime", None):
            speed = version_data.get("speed", 1)
            time_warp_nodes = version_data.get("timewarps", [])
            self.make_retimes(node, speed, time_warp_nodes)

        # Update the imprinted representation
        update_container(node, updated_dict)
        self.log.info("udated to version: {}".format(version.get("name")))
コード例 #41
0
 def changeVersion(self, iAObj=None, applicationObject=None):
     '''Change current version of the give *iAObj* and *applicationObject*.'''
     n = nuke.toNode(HelpFunctions.safeString(applicationObject))
     n['file'].fromUserText(HelpFunctions.safeString(iAObj.filePath))
     self.setFTab(n, iAObj)
     return True
コード例 #42
0
ファイル: scan_ingest.py プロジェクト: nedwilson/studio_bin
        # upload a thumbnail for the plate to the shot, in the event that this is a new shot
        if b_new_shot_thumb:
            ihdb.upload_thumbnail('Shot', dbshot, generated_thumb_path)
            print "INFO: Uploaded thumbnail %s to DB shot object %s."%(generated_thumb_path, dbshot.g_shot_code)

    print "INFO: Got plate %s object from database with ID of %s."%(dbplate.g_plate_name, dbplate.g_dbid)

    if b_create_nuke:
        print "INFO: Building Nuke Script from template."
        comp_render_dir_dict = { 'pathsep' : os.path.sep, 'compdir' : nuke_script_starter }
        comp_write_path = os.path.join(shot_dir, g_shot_comp_render_dir.format(**comp_render_dir_dict), "%s.%s.%s"%(nuke_script_starter, g_write_frame_format, g_write_extension))
        print "INFO: About to open: %s"%g_shot_template
        nuke.scriptOpen(g_shot_template)
        print "INFO: Shot template loaded."
        bd_node = nuke.toNode("BackdropNode1")
        bd_node_w = nuke.toNode("BackdropNode2")
        main_read = nuke.toNode("Read1")
        main_write = nuke.toNode("Write_exr")
        main_cdl = nuke.toNode("VIEWER_INPUT.OCIOCDLTransform1")
        
        # handle non-standard plate format
        start_file_path = "%s.%s.%s"%(plates[0], mainplate_first, mainplate_ext)
        start_file = None
        width = 3424
        height = 2202
        try:
            start_file = OpenEXR.InputFile(start_file_path)
            dwindow_header = start_file.header()['displayWindow']
            width = dwindow_header.max.x - dwindow_header.min.x + 1
            height = dwindow_header.max.y - dwindow_header.min.y + 1
コード例 #43
0
def auto_render(render_path):
    read_nodes = nuke.selectedNodes("Read")
    all_nodes_list = []

    for i in read_nodes:
        read_path = i["file"].getValue()
        if len(read_path.split(".")) == 2:
            if read_path.split(".")[0].find("-") != -1:
                read_num = read_path.split(".")[0].split("-")[-1].split("_")[0]
            else:
                read_num = read_path.split(".")[0].split("_")[-2]

        elif len(read_path.split(".")) == 3:
            if read_path.split(".")[0].find("-") != -1:
                read_num = read_path.split(".")[0].split("-")[-1]
            else:
                read_num = read_path.split(".")[0].split("_")[-1]

        i["colorspace"].setValue("Gamma1.8")
        all_nodes_list.append((read_num, i))

    all_nodes_list.sort(key=lambda x: x[0])

    write_num = []

    for k in range(0, len(all_nodes_list)):
        try:
            all_nodes_list[k + 1][1].setXpos(all_nodes_list[k][1].xpos() + 120)
            all_nodes_list[k + 1][1].setYpos(all_nodes_list[k][1].ypos())

            merge_node = nuke.createNode("Merge")
            merge_node.setInput(1, nuke.toNode("Premult1"))
            merge_node.setInput(0, all_nodes_list[k][1])
            merge_node.setXpos(all_nodes_list[k][1].xpos())
            merge_node.setYpos(all_nodes_list[k][1].ypos() + 120)

            write_node = nuke.createNode("Write")
            read_name = all_nodes_list[k][1]["file"].getValue()

            name = read_name.split("/")[-1]
            if len(name.split(".")) == 3:
                write_name = render_path + name.split(".")[0] + ".mov"
            elif len(name.split(".")) == 2:
                if len(name.split("_")) == 3:
                    write_name = render_path + name.split(
                        "_")[0] + "_" + name.split("_")[1] + ".mov"
                elif len(name.split("_")) == 2:
                    write_name = render_path + name.split("_")[0] + ".mov"

            write_node["file"].setValue(write_name)
            write_node["mov64_fps"].setValue(25)
            write_node["mov32_fps"].setValue(25)
            write_num.append(write_node["name"].getValue())

        except:
            merge_node = nuke.createNode("Merge")
            merge_node.setInput(1, nuke.toNode("Premult1"))
            merge_node.setInput(0, all_nodes_list[k][1])
            merge_node.setXpos(all_nodes_list[k][1].xpos())
            merge_node.setYpos(all_nodes_list[k][1].ypos() + 120)

            write_node = nuke.createNode("Write")
            read_name = all_nodes_list[k][1]["file"].getValue()

            name = read_name.split("/")[-1]
            if len(name.split(".")) == 3:
                write_name = render_path + name.split(".")[0] + ".mov"
            elif len(name.split(".")) == 2:
                if len(name.split("_")) == 3:
                    write_name = render_path + name.split(
                        "_")[0] + "_" + name.split("_")[1] + ".mov"
                elif len(name.split("_")) == 2:
                    write_name = render_path + name.split("_")[0] + ".mov"

            write_node["file"].setValue(write_name)
            write_node["mov64_fps"].setValue(25)
            write_node["mov32_fps"].setValue(25)
            write_num.append(write_node["name"].getValue())
    nuke.scriptSaveAs(render_path + 'render_%s.nk' % getpass.getuser())

    ft = open(
        render_path + "render_%s_%d.bat" %
        (getpass.getuser(), int(time.time())), 'w')
    for g in xrange(0, len(all_nodes_list)):
        nuke_path = '\"C:\\Program Files\\Nuke9.0v1\\Nuke9.0.exe\" -x -m 8 -F %s' % str(
            int(all_nodes_list[g][1]["first"].getValue())) + "-" + str(
                int(all_nodes_list[g][1]["last"].getValue()))

        nuke_name1 = " -X %s " % write_num[g]
        nuke_name2 = render_path + "render_%s.nk" % getpass.getuser()
        full_path = nuke_path + nuke_name1 + nuke_name2

        ft.write(full_path + '\n')
    ft.write("pause" + '\n')
    ft.close()
コード例 #44
0
import json
import nuke
import os.path

DATABASE_PATH = "Y:\\Workspace\\SCRIPTS\\pipeline\\database"
PROJECT_PATH  = "Y:\\Workspace\\MASTER_PROJECTS\\NBA_2016\\001_PROJECTS\\000_Animation\\NBA_ES_PLAYER_TRANS_01"
NUKE_PATH     = os.path.join(PROJECT_PATH, 'nuke')
RENDER_PATH   = os.path.join(PROJECT_PATH, 'render_2d')


SWATCHES = {
    'primary': nuke.toNode('PRI'),
    'secondary': nuke.toNode('SEC'),
    'tertiary': nuke.toNode('TRI'),
    '3d_logo': nuke.toNode('LOGO_3D'),
    '2d_logo': nuke.toNode('LOGO_2D'),
    'wordmark': nuke.toNode('LOGO_WORDMARK'),
    'ticker': nuke.toNode('TICKER'),
    'typography': nuke.toNode('TYPOGRAPHY')
}

# GETTERS ##########################################################################################
def getProduction(prod_):
    ''' Gets a production's global variables from the database. '''
    PRODUCTION_GLOBALS_DB = os.path.join(DATABASE_PATH, "productions_db.json")
    merged_prod = {}
    with open(PRODUCTION_GLOBALS_DB, 'r') as stream:
        full_db = json.load(stream)
        for k,v in full_db.iteritems():
            # default project is stored
            if (k == 'DEFAULT'):
コード例 #45
0
nuke.pluginAddPath(pipe_path + './gizmos')
nuke.pluginAddPath(pipe_path + './gizmos/Franklin')
nuke.pluginAddPath(pipe_path + './gizmos/C')
nuke.pluginAddPath(pipe_path + './gizmos/C/icons')
#nuke.pluginAddPath(pipe_path + './gizmos/MM');
nuke.pluginAddPath(pipe_path + './gizmos/Toolsets')
nuke.pluginAddPath(pipe_path + './gizmos/Other')
nuke.pluginAddPath(pipe_path + './gizmos/Other/pixelfudger')

# nuke.pluginAddPath(pipe_path + './smartScripter');

# -----------------------------------------------------------------------------------------------------------------
# SET NUKE PREFERENCES - W_HOTBOX
# -----------------------------------------------------------------------------------------------------------------
pipe_path = pipe_path.replace('\\', "/")
pref = nuke.toNode('preferences')

try:  # > Nuke 7
    pref.knob('hotboxLocation').setValue(pipe_path + 'Python/W_hotbox/')
    pref.knob('hotboxIconLocation').setValue(pipe_path +
                                             'Python/W_hotbox/icons/')
    pref.knob('hotboxShortcut').setValue('<')
except:  # < Nuke 6
    pass

#-----------------------------------------------------------------------------------------------------------------
# DEV OPTIONS
#-----------------------------------------------------------------------------------------------------------------
# dev = "True"
# if dev == "True":
#     devPrint = '- Dev Options ................... OK'
コード例 #46
0
def updateAllWriteNames():
    if nuke.toNode("L_PROJECT"):
        for n in nuke.allNodes("Write"):
            updateWriteName(n)
コード例 #47
0
        def validate():
            if type == 'upload':
                nukeScriptName = nuke.toNode('root').name()
                nukeScriptName = 'Untitled' if nukeScriptName == 'Root' else nukeScriptName
                # elif type = 'download':
                fragment1 = os.path.basename(self.filepath).split('_v')
                fragment2 = fragment1[0].split('_')
                fragmentsArr = []
                self.filename = fragment1[0]

                # validate
                exceptions = []
                try:
                    fileversion = int(fragment1[1].split('.')[0])
                    self.fileversion = fileversion
                except:
                    exceptions.append(
                        '--> Current filename contains no version-number!\n\nCorrect naming:\nshowcode_shotname_vXXX\n\n')
                # showFolder, showCode, shotName
                try:
                    if not self.showFolder.path.set('remote', retrieveServerShowFolder(fragment2[0])):
                        exceptions.append(
                            '--> No corresponding Show folder found at:\n' + self.gladiator + '\n\n')
                    else:
                        self.showCode = fragment2[0]
                        self.shotName = fragment1[0].split(
                            (self.showCode + '_'))[1].split('.')[0]
                except:
                    exceptions.append(
                        '--> Problem retrieving Show directories. Now show found for:\n' + str(fragment2[0]) + '\n\n')
                # shotFolder
                try:
                    if not self.shotFolder.path.set('remote', retrieveServerShotFolder(self.showFolder.path.remote, self.showCode, self.shotName)):
                        exceptions.append(
                            '--> No corresponding Shot folder found for\n\'' + str(nukeScriptName) + '\'\n\n')
                    else:
                        self.shotFolder.path.set('local', os.path.abspath(
                            os.path.join(filepath, os.pardir)))
                except:
                    exceptions.append(
                        '--> Problem retrieving Shot directories. Now shot found for:\n\'' + str(nukeScriptName) + '\'\n\n')
                # versionFolder
                try:
                    self.versionFolder.path.set('local', os.path.abspath(
                        os.path.join(self.filepath, os.pardir)))
                    latestVersion = retrieveLatestVersion(
                        self.shotFolder.path.remote, self.showCode)
                    self.versionFolder.path.set(
                        'remote', latestVersion['path'])
                    self.versionFolder.ver.set('remote', latestVersion['int'])
                except:
                    exceptions.append(
                        '--> Problem setting the path or version for ' + nukeScriptName + '.\n\n')
                try:
                    ver = int(os.path.basename(
                        self.versionFolder.path.local).split('_v')[1])
                    self.versionFolder.ver.set('local', ver)
                except:
                    exceptions.append(
                        '--> The folder you\'r working out of doesn\'t have a valid version-number.\n\n')
            # download
            elif type == 'download':
                fragment1 = os.path.basename(self.filepath).split('_v')
                fragment2 = fragment1[0].split('_')
                fragmentsArr = []
                self.filename = fragment1[0]
                exceptions = []
                try:
                    fileversion = int(fragment1[1].split('.')[0])
                    self.fileversion = fileversion
                except:
                    exceptions.append(
                        '--> Current filename contains no version-number!\n\nCorrect naming:\nshowcode_shotname_vXXX\n\n')
                # showFolder, showCode, shotName
                try:
                    if not self.showFolder.path.set('remote', retrieveServerShowFolder(fragment2[0])):
                        exceptions.append(
                            '--> No corresponding Show folder found at:\n' + self.gladiator + '\n\n')
                    else:
                        self.showCode = fragment2[0]
                        self.shotName = fragment1[0].split(
                            (self.showCode + '_'))[1].split('.')[0]
                except:
                    exceptions.append(
                        '--> Problem retrieving Show directories. Now show found for:\n' + str(fragment2[0]) + '\n\n')
                # shotFolder
                try:
                    if not self.shotFolder.path.set('remote', retrieveServerShotFolder(self.showFolder.path.remote, self.showCode, self.shotName)):
                        exceptions.append(
                            '--> No corresponding Shot folder found for\n\'' + str(nukeScriptName) + '\'\n\n')
                    else:
                        self.shotFolder.path.set('local', os.path.abspath(
                            os.path.join(filepath, os.pardir)))
                except:
                    exceptions.append(
                        '--> Problem retrieving Shot directories. Now shot found for:\n\'' + str(nukeScriptName) + '\'\n\n')
                # versionFolder
                try:
                    # self.versionFolder.path.set( 'local', os.path.abspath(os.path.join(self.filepath, os.pardir)) )
                    latestVersion = c1_tools.retrieveLatestVersion(
                        self.shotFolder.path.remote, self.showCode)
                    self.versionFolder.path.set(
                        'remote', latestVersion['path'])
                    self.versionFolder.ver.set('remote', latestVersion['int'])
                except:
                    raise
                    exceptions.append(
                        '--> Problem setting the path or version for ' + fragment1[0] + '.\n\n')
                # try:
                #     ver = int(os.path.basename(self.versionFolder.path.local).split('_v')[1])
                #     # self.versionFolder.ver.set( 'local', ver )
                # except:
                #     exceptions.append('--> The folder you\'r working out of doesn\'t have a valid version-number.\n\n' )

            # exceptions
            if len(exceptions) > 0:
                msg = ''
                i = 1
                for exception in exceptions:
                    msg = msg + 'Filenaming Error ' + \
                        str(i) + '):\n ' + exception
                    i = i + 1
                nuke.message(msg)
                return False
            else:
                return True
コード例 #48
0
             # print node.fullName(), ':', node['file'].value()
             path = cwd + '/' + node.fullName(
             ) + '/' + node.fullName() + '.%04d.exr'
             if len(frame_range) == 0:
                 list_of_files = glob.glob(path[:-8] +
                                           '????.*')
                 first = int(list_of_files[0].split('.')[4])
                 last = int(list_of_files[-1].split('.')[4])
                 frame_range.append(first)
                 frame_range.append(last)
                 nuke.root()['first_frame'].setValue(
                     frame_range[0])
                 nuke.root()['last_frame'].setValue(
                     frame_range[1])
                 nuke.root()['fps'].setValue(30)
                 out = nuke.toNode('OUT')
                 vid = path_root + '/' + course + '/' + fairway_loop + '.mov'
                 out['file'].setValue(vid)
                 # out['file_type'].setValue(6)
                 # out['meta_codec'].setValue('avc1')
                 # out['mov32_fps'].setValue(30)
                 audio = settings[
                     'audio'] + '/' '%s_%s.wav' % (
                         course, fairway_loop)
                 out['mov64_audiofile'].setValue(audio)
                 out['create_directories'].setValue(1)
             node['file'].setValue(path)
             node['first'].setValue(frame_range[0])
             node['last'].setValue(frame_range[1])
 #####################################################################
 nuke.scriptSave(comp)
コード例 #49
0
ファイル: udim.py プロジェクト: sgadsden/_NukeStudio
def findNextName(name):
  i = 1
  while nuke.toNode ( name + str(i) ) != None:
    i += 1

  return name + str(i)
コード例 #50
0
ファイル: Basic.py プロジェクト: kuchinal/lamakaha
def Basic():
    import nuke
    S = nuke.selectedNode()
    y = nuke.toNode("Basic")
    S.setInput(0, y)
コード例 #51
0
def copyToProjector(node=None, frame=None, gui=nuke.GUI):
    if not node:
        node = nuke.thisNode()
    if not frame:
        frame = nuke.root()['frame'].value()

    if node.Class() not in ['StereoCam', 'StereoCam2', 'Camera', 'Camera2']:
        m = 'this node is not a supported camera type, unable to convert to projector'
        if gui:
            nuke.message(m)
        nuke.error(m)
        return

    saved_frame = nuke.root()['frame'].value()
    nuke.root()['frame'].setValue(frame)

    # Turn off all selected nodes, otherwise they mess up the node paste:
    for n in nuke.selectedNodes():
        n.knob('selected').setValue(False)

    # Now select this node then copy and paste it:
    node['selected'].setValue(True)
    nukescripts.node_copypaste()
    proj = nuke.selectedNode()

    # Name/label new node:
    new_name = 'projector_cam'
    if node.knob('shot') is not None:
        if node['shot'].getText() != '':
            new_name += '_%s_' % proj['shot'].getText().replace('.', '_')
    new_name += 'fr%d_' % nuke.frame()
    # De-duplicate the new name:
    counter = 1
    while 1:
        new_name2 = new_name + '%d' % counter
        if nuke.toNode(new_name2) is None:
            new_name = new_name2
            break
        counter += 1
    proj['name'].setValue(new_name)

    l = proj['label'].getText()
    if l != '' and not l.endswith('\\n'):
        l += '\\n'
    l += 'frame %d' % nuke.frame()
    proj['label'].setValue(l)

    # Offset its position in the DAG:
    xpos = node['xpos'].value()
    proj['xpos'].setValue(xpos + 100)
    ypos = node['ypos'].value()
    proj['ypos'].setValue(ypos + 100)

    # Unsplit all knobs (remove views):
    vs = nuke.views()
    if len(vs) > 1:
        for name, knob in proj.knobs().items():
            if issubclass(knob.__class__, nuke.Array_Knob):
                #print 'knob %s: unsplitting view %s' % (knob.name(), vs[1])
                knob.unsplitView(view=vs[1])

    # Clear animations from all knobs:
    for name, knob in proj.knobs().items():
        if knob.isAnimated():
            knob.clearAnimated()

    # Disable updating:
    if proj.knob('read_from_file') is not None:
        proj['read_from_file'].setValue(False)

    nuke.root()['frame'].setValue(saved_frame)
コード例 #52
0
ファイル: afanasy.py プロジェクト: ansenlong/cgru
    def __init__(self, afnode, wnode, subblock, prefix, fparams):
        if VERBOSE == 2:
            print 'Initializing block parameters for "%s"' % wnode.name()
        self.wnode = wnode
        self.valid = True

        self.subblock = subblock
        self.prefix = prefix

        self.framefirst = nuke.root().firstFrame()
        self.framelast = nuke.root().lastFrame()
        self.frameinc = 1
        self.framespertask = 1
        self.maxhosts = -1
        self.capacity = -1
        self.maxperhost = -1
        self.maxruntime = -1
        self.hostsmask = None
        self.hostsmaskexclude = None
        self.fullrangedepend = 0
        self.tmpimage = 1
        self.pathsmap = 1
        if afnode is not None:
            self.framefirst = int(afnode.knob('framefirst').value())
            self.framelast = int(afnode.knob('framelast').value())
            self.frameinc = int(afnode.knob('frameinc').value())
            self.framespertask = int(afnode.knob('framespertask').value())
            self.maxhosts = int(afnode.knob('maxhosts').value())
            self.capacity = int(afnode.knob('capacity').value())
            self.maxperhost = int(afnode.knob('maxperhost').value())
            self.maxruntime = int(afnode.knob('maxruntime').value())
            self.tmpimage = int(afnode.knob('tmpimage').value())
            self.pathsmap = int(afnode.knob('pathsmap').value())
            self.hostsmask = afnode.knob('hostsmask').value()
            self.hostsmaskexclude = afnode.knob('hostsmaskexcl').value()

        self.writename = str(wnode.fullName())

        if wnode.Class() == RenderNodeClassName:
            afcommon = __import__('afcommon', globals(), locals(), [])
            # Get images files:
            self.imgfiles = []
            if nuke.toNode('root').knob('proxy').value():
                fileknob = wnode.knob('proxy')
            else:
                fileknob = wnode.knob('file')
            # Get views:
            views = wnode.knob('views')
            if views is not None:
                views = views.value()
                if views is None or views == '': views = nuke.views()
                else: views = views.split(' ')
            else: views = nuke.views()
            # Iterate views:
            for view in views:
                view = view.strip()
                if not len(view):
                    continue  # skip empty view, may be after split(' ')
                # Check view exists:
                if not view in nuke.views():
                    print('Error: Skipping invalid view: "%s"' % view)
                    continue


#				if len( self.imgfiles): self.imgfiles += ';'
# Get thow files for current view and fitst and last frames:
                octx = nuke.OutputContext()
                octx.setView(1 + nuke.views().index(view))
                octx_framefirst = self.framefirst
                octx_framelast = self.framelast
                if octx_framefirst < 0: octx_framefirst = 0
                if octx_framelast < 0: octx_framelast = 0
                # If frame first and frame last are equal no sequence needed
                if octx_framefirst == octx_framelast:
                    octx.setFrame(octx_framefirst)
                    self.imgfiles.append(fileknob.getEvaluatedValue(octx))
                else:
                    # Get files from first and last frames to calculate frames pattern:
                    octx.setFrame(octx_framefirst)
                    images1 = fileknob.getEvaluatedValue(octx)
                    if images1 is None or images1 == '':
                        nuke.message(
                            'Error:\n%s\nFiles are empty.\nView "%s", frame %d.'
                            % (self.writename, view, self.framefirst))
                        self.valid = False
                        return
                    octx.setFrame(octx_framelast)
                    images2 = fileknob.getEvaluatedValue(octx)
                    if images2 is None or images2 == '':
                        nuke.message(
                            'Error:\n%s\nFiles are empty.\nView "%s", frame %d.'
                            % (self.writename, view, self.framelast))
                        self.valid = False
                        return
                    part1, padding, part2 = afcommon.splitPathsDifference(
                        images1, images2)
                    if padding < 1:
                        nuke.message(
                            'Error:\n%s\nInvalid files pattern.\nView "%s".' %
                            (self.writename, view))
                        self.valid = False
                        return
                    self.imgfiles.append(part1 + '@' + '#' * padding + '@' +
                                         part2)

            # Check images folders:
            for imgfile in self.imgfiles:
                folder = os.path.dirname(imgfile)
                if folder != '':
                    if not os.path.isdir(folder):
                        result = nuke.ask(
                            'Write Node "%s" Directory\n%s\ndoes not exist.\nCreate it?'
                            % (self.writename, folder))
                        if result:
                            os.makedirs(folder)
                            if not os.path.isdir(folder):
                                nuke.message('Can`t create folder:\n%s' %
                                             folder)
                                self.valid = False
                        else:
                            self.valid = False
        elif wnode.Class() == DailiesNodeClassName:
            if VERBOSE: print 'Generating dailies "%s"' % self.writename
        else:
            nuke.message('Node type\n"%s"\nis unsendable.' % self.writename)
            self.valid = False

        for par in fparams:
            if fparams[par] is not None:
                if hasattr(self, par):
                    setattr(self, par, fparams[par])

        self.name = self.writename
        if subblock:
            if self.prefix != None:
                if self.prefix != '':
                    self.name = self.prefix + self.name

        self.dependmask = ''
        self.tasksdependmask = ''
コード例 #53
0
ファイル: layergrade.py プロジェクト: sharpencrag/vfx_utils
def remove_light(added_light, copied_light, node=None):
    node.removeKnob(node.knobs()[(added_light + '_disable_lnk')])
    node.removeKnob(node.knobs()[(added_light + '_link')])
    node.removeKnob(node.knobs()[(added_light + '_rmb')])
    nuke.delete(nuke.toNode(added_light))
    nuke.delete(nuke.toNode(copied_light))
コード例 #54
0
ファイル: afanasy.py プロジェクト: ansenlong/cgru
def render(node=None):
    nodes = []
    fparams = dict()

    if node is not None:
        # Render only specified node:
        nodes.append(node)
        renderNodes(nodes, fparams, False)
        return

    # Store minimum and maximum frames to show in dialog
    hasafanasynodes = False
    framefirst_min = None
    framefirst_max = None
    framelast_min = None
    framelast_max = None
    framespertask_min = None
    framespertask_max = None
    selectednodes = nuke.selectedNodes()
    selectednodes.sort(None, getNodeName)
    for node in selectednodes:
        if node.Class() == AfanasyNodeClassName or node.Class(
        ) == RenderNodeClassName or node.Class() == DailiesNodeClassName:
            nodes.append(node)
            # Check for minimum and maximum
            if node.Class() == AfanasyNodeClassName:
                hasafanasynodes = True
                framefirst = int(node.knob('framefirst').value())
                framelast = int(node.knob('framelast').value())
                framespertask = int(node.knob('framespertask').value())
            else:
                framefirst = nuke.root().firstFrame()
                framelast = nuke.root().lastFrame()
                framespertask = 1
            if framefirst_min is None: framefirst_min = framefirst
            else: framefirst_min = min(framefirst_min, framefirst)
            if framefirst_max is None: framefirst_max = framefirst
            else: framefirst_max = max(framefirst_max, framefirst)
            if framelast_min is None: framelast_min = framelast
            else: framelast_min = min(framelast_min, framelast)
            if framelast_max is None: framelast_max = framelast
            else: framelast_max = max(framelast_max, framelast)
            if framespertask_min is None: framespertask_min = framespertask
            else: framespertask_min = min(framespertask_min, framespertask)
            if framespertask_max is None: framespertask_max = framespertask
            else: framespertask_max = max(framespertask_max, framespertask)

    if len(nodes) < 1:
        nuke.message(
            'No nodes to render founded.\nSelect "%s" or "%s" node(s) to render.'
            % (AfanasyNodeClassName, RenderNodeClassName))
        return

    nodesstring = nodes[0].name()
    if len(nodes) > 1:
        for i in range(1, len(nodes)):
            nodesstring += ' ' + nodes[i].name()

    # Construct frame ranges:
    if framefirst_min != framefirst_max:
        framefirst = '%s..%s' % (framefirst_min, framefirst_max)
    else:
        framefirst = framefirst_min
    if framelast_min != framelast_max:
        framelast = '%s..%s' % (framelast_min, framelast_max)
    else:
        framelast = framelast_min
    if framespertask_min != framespertask_max:
        framespertask = '%s..%s' % (framespertask_min, framespertask_max)
    else:
        framespertask = framespertask_min

    # Dialog:
    panel = nuke.Panel('Afanasy Render')
    panel.addSingleLineInput('Nodes:', nodesstring)
    panel.addSingleLineInput('First Frame:', framefirst)
    panel.addSingleLineInput('Last Frame:', framelast)
    panel.addSingleLineInput('Frames Per Task:', framespertask)
    if hasafanasynodes: panel.addBooleanCheckBox('Store Frames Settings', 0)
    panel.addBooleanCheckBox('Start Paused', 0)
    panel.addButton("Cancel")
    panel.addButton("OK")
    result = panel.show()
    if not result: return

    # Check for selected nodes:
    nodesstring = panel.value('Nodes:')
    selectednodes = nodesstring.split()
    nodes = []
    for name in selectednodes:
        node = nuke.toNode(name)
        if node is None:
            nuke.message('Node "%s" not founded.' % name)
            return
        if node.Class() == AfanasyNodeClassName or node.Class(
        ) == RenderNodeClassName or node.Class() == DailiesNodeClassName:
            nodes.append(node)

    if len(nodes) < 1:
        nuke.message(
            'No nodes to render founded.\nSelect "%s" or "%s" node(s) to render.'
            % (AfanasyNodeClassName, RenderNodeClassName))
        return

    # Get parameters:
    sframefirst = str(panel.value('First Frame:'))
    sframelast = str(panel.value('Last Frame:'))
    sframespertask = str(panel.value('Frames Per Task:'))
    storeframes = False
    if hasafanasynodes: storeframes = int(panel.value('Store Frames Settings'))
    if panel.value('Start Paused'): fparams['startpaused'] = 1
    # Check frame range was set:
    if sframefirst.find('..') == -1:
        try:
            framefirst = int(sframefirst)
        except:
            nuke.message('Invalid first frame "%s"' % sframefirst)
            return
        fparams['framefirst'] = framefirst
    if sframelast.find('..') == -1:
        try:
            framelast = int(sframelast)
        except:
            nuke.message('Invalid last frame "%s"' % sframelast)
            return
        fparams['framelast'] = framelast
    if sframespertask.find('..') == -1:
        try:
            framespertask = int(sframespertask)
        except:
            nuke.message('Invalid frames per task "%s"' % sframespertask)
            return
        fparams['framespertask'] = framespertask
    if checkFrameRange(framefirst, framelast, 1, framespertask) == False:
        return

    # Render selected nodes:
    renderNodes(nodes, fparams, storeframes)
コード例 #55
0
ファイル: create_write_render.py プロジェクト: ldunham1/pype
    def process(self):

        inputs = []
        outputs = []
        instance = nuke.toNode(self.data["subset"])
        selected_node = None

        # use selection
        if (self.options or {}).get("useSelection"):
            nodes = self.nodes

            if not (len(nodes) < 2):
                msg = ("Select only one node. "
                       "The node you want to connect to, "
                       "or tick off `Use selection`")
                self.log.error(msg)
                nuke.message(msg)

            if len(nodes) == 0:
                msg = (
                    "No nodes selected. Please select a single node to connect"
                    " to or tick off `Use selection`")
                self.log.error(msg)
                nuke.message(msg)

            selected_node = nodes[0]
            inputs = [selected_node]
            outputs = selected_node.dependent()

            if instance:
                if (instance.name() in selected_node.name()):
                    selected_node = instance.dependencies()[0]

        # if node already exist
        if instance:
            # collect input / outputs
            inputs = instance.dependencies()
            outputs = instance.dependent()
            selected_node = inputs[0]
            # remove old one
            nuke.delete(instance)

        # recreate new
        write_data = {
            "class": self.n_class,
            "families": [self.family],
            "avalon": self.data
        }

        if self.presets.get('fpath_template'):
            self.log.info("Adding template path from preset")
            write_data.update(
                {"fpath_template": self.presets["fpath_template"]})
        else:
            self.log.info("Adding template path from plugin")
            write_data.update({
                "fpath_template": ("{work}/renders/nuke/{subset}"
                                   "/{subset}.{frame}.{ext}")
            })

        write_node = pnlib.create_write_node(self.data["subset"],
                                             write_data,
                                             input=selected_node)

        # relinking to collected connections
        for i, input in enumerate(inputs):
            write_node.setInput(i, input)

        write_node.autoplace()

        for output in outputs:
            output.setInput(0, write_node)

        return write_node
コード例 #56
0
def findElements(sel):
    '''Find Roto node, Transform node and Curve'''
    '''
	a. Selected Roto, promot Transform, option for Curve
	b. Selected Transform, prompt Roto, Curve layer set to rootLayer
	c. Selected Roto and Transform, prompt for Curve
	'''

    sel = nuke.selectedNodes()
    node_roto, node_trans, roto_curve, op_cancel = None, None, None, False
    type_roto = ['Roto', 'Rotopaint']
    type_transform = ['Transform', 'Tracker4']
    type_all = type_roto + type_transform
    type_sel = [c.Class() for c in sel]

    if len(sel) == 1:

        # a. Selected Roto, promot Transform, option for Curve
        if sel[0].Class() in type_roto:
            print "Selected Roto"
            node_roto = sel[0]
            k = node_roto['curves']
            all_transform = [n.name() for n in nuke.allNodes('Transform')]
            all_curves = [
                c.name for c in k.rootLayer
                if isinstance(c, nuke.rotopaint.Shape)
            ]
            all_curves.insert(0, 'all')
            p = nuke.Panel("Select Transform node and Shape")
            p.addEnumerationPulldown('MatchMove', ' '.join(all_transform))
            p.addEnumerationPulldown('Shape', ' '.join(all_curves))
            if p.show():
                node_trans = nuke.toNode(p.value('MatchMove'))
                sel_shape = p.value('Shape')
                roto_curve = k.toElement(
                    sel_shape) if sel_shape != 'all' else k.rootLayer
            else:
                op_cancel = True

        # b. Selected Transform, prompt Roto, Curve layer set to rootLayer
        elif sel[0].Class() in type_transform:
            print "Selected Transform"
            node_trans = sel[0]
            all_roto = [
                n.name() for n in nuke.allNodes() if n.Class() in type_roto
            ]
            all_roto.insert(0, 'new')
            p = nuke.Panel("Select Roto node")
            p.addEnumerationPulldown('Roto', ' '.join(all_roto))
            if p.show():
                sel_roto = p.value('Roto')
                node_roto = nuke.toNode(
                    sel_roto) if sel_roto != 'new' else nuke.nodes.Roto(
                        output='alpha', cliptype='no clip')
                roto_curve = node_roto['curves'].rootLayer
            else:
                op_cancel = True

    elif len(sel) == 2:

        node_roto = [r for r in sel if r.Class() in type_roto][0]
        node_trans = [t for t in sel if t.Class() in type_transform][0]

        # c. Selected Roto and Transform, prompt for Curve
        if node_roto and node_trans:
            print "Selected Roto and Transform"
            k = node_roto['curves']
            all_curves = [
                c.name for c in k.rootLayer
                if isinstance(c, nuke.rotopaint.Shape)
            ]
            all_curves.insert(0, 'all')
            p = nuke.Panel("Select Shape")
            p.addEnumerationPulldown('Shape', ' '.join(all_curves))
            if p.show():
                sel_shape = p.value('Shape')
                roto_curve = k.toElement(
                    sel_shape) if sel_shape != 'all' else k.rootLayer
            else:
                op_cancel = True

    return {'r': node_roto, 't': node_trans, 'c': roto_curve, 'op': op_cancel}
コード例 #57
0
ファイル: pkgProj_v001.py プロジェクト: mightyang/yangTools
                 print e.message
         try:
             shutil.copy(os.path.join(self.__dirPath, self.__value), os.path.join(pkgPath, self.__value))
             self.__status = pkgStatus.PKGED
             self.callback(self, 1)
         except Exception, e:
             print e.message
 elif self.__type == pkgItemType.NODE:
     pkgPath = os.path.join(path, '/'.join(self.__nodePath.split('.')))
     filePath = os.path.join(pkgPath, os.path.basename(os.path.dirname(self.__dirPath)), os.path.basename(self.__dirPath)).replace('\\', '/')
     if self.__dirPath not in pkgedFilePathList:
         pkgedFilePathList[self.__dirPath] = filePath
     else:
         filePath = pkgedFilePathList[self.__dirPath]
         self.__status = pkgStatus.PKGED
     n = nuke.toNode(self.__nodePath)
     for nodeClass, knob, conditionKnob, conditionKnobValue in searchNodes:
         if n.Class() == nodeClass:
             n[knob].setValue(filePath)
 elif self.__type == pkgItemType.SPACEROOT:
     pkgPath = os.path.join(path, os.path.basename(self.getDirPath()))
     if not os.path.exists(pkgPath):
         try:
             os.makedirs(pkgPath)
         except Exception, e:
             print e.message
     try:
         nuke.scriptSaveAs(os.path.join(path, self.__value))
         self.__status = pkgStatus.PKGED
         self.callback(self, 1)
     except Exception, e:
コード例 #58
0
ファイル: pkgProj_v001.py プロジェクト: mightyang/yangTools
 def getSpaces(self):
     spaces = ['root']
     while len(spaces) > 0:
         yield spaces
         spaces = ['.'.join((s, n.name())) for s in spaces for n in nuke.toNode(s).nodes() if n.Class() == 'Group']
コード例 #59
0
ファイル: load_luts_ip.py プロジェクト: ldunham1/pype
    def update(self, container, representation):
        """Update the Loader's path

        Nuke automatically tries to reset some variables when changing
        the loader's path to a new file. These automatic changes are to its
        inputs:

        """

        from avalon.nuke import (update_container)
        # get main variables
        # Get version from io
        version = io.find_one({
            "type": "version",
            "_id": representation["parent"]
        })
        # get corresponding node
        GN = nuke.toNode(container['objectName'])

        file = api.get_representation_path(representation).replace("\\", "/")
        name = container['name']
        version_data = version.get("data", {})
        vname = version.get("name", None)
        first = version_data.get("frameStart", None)
        last = version_data.get("frameEnd", None)
        workfile_first_frame = int(nuke.root()["first_frame"].getValue())
        namespace = container['namespace']
        colorspace = version_data.get("colorspace", None)
        object_name = "{}_{}".format(name, namespace)

        add_keys = [
            "frameStart", "frameEnd", "handleStart", "handleEnd", "source",
            "author", "fps"
        ]

        data_imprint = {
            "representation": str(representation["_id"]),
            "frameStart": first,
            "frameEnd": last,
            "version": vname,
            "colorspaceInput": colorspace,
            "objectName": object_name
        }

        for k in add_keys:
            data_imprint.update({k: version_data[k]})

        # Update the imprinted representation
        update_container(GN, data_imprint)

        # getting data from json file with unicode conversion
        with open(file, "r") as f:
            json_f = {
                self.byteify(key): self.byteify(value)
                for key, value in json.load(f).iteritems()
            }

        # get correct order of nodes by positions on track and subtrack
        nodes_order = self.reorder_nodes(json_f["effects"])

        # adding nodes to node graph
        # just in case we are in group lets jump out of it
        nuke.endGroup()

        # adding content to the group node
        with GN:
            # first remove all nodes
            [nuke.delete(n) for n in nuke.allNodes()]

            # create input node
            pre_node = nuke.createNode("Input")
            pre_node["name"].setValue("rgb")

            for ef_name, ef_val in nodes_order.items():
                node = nuke.createNode(ef_val["class"])
                for k, v in ef_val["node"].items():
                    if k in self.ignore_attr:
                        continue

                    try:
                        node[k].value()
                    except NameError as e:
                        self.log.warning(e)
                        continue

                    if isinstance(v, list) and len(v) > 3:
                        node[k].setAnimated()
                        for i, value in enumerate(v):
                            if isinstance(value, list):
                                for ci, cv in enumerate(value):
                                    node[k].setValueAt(
                                        cv, (workfile_first_frame + i), ci)
                            else:
                                node[k].setValueAt(value,
                                                   (workfile_first_frame + i))
                    else:
                        node[k].setValue(v)
                node.setInput(0, pre_node)
                pre_node = node

            # create output node
            output = nuke.createNode("Output")
            output.setInput(0, pre_node)

        # try to place it under Viewer1
        if not self.connect_active_viewer(GN):
            nuke.delete(GN)
            return

        # get all versions in list
        versions = io.find({
            "type": "version",
            "parent": version["parent"]
        }).distinct('name')

        max_version = max(versions)

        # change color of node
        if version.get("name") not in [max_version]:
            GN["tile_color"].setValue(int("0xd84f20ff", 16))
        else:
            GN["tile_color"].setValue(int("0x3469ffff", 16))

        self.log.info("udated to version: {}".format(version.get("name")))
コード例 #60
0
ファイル: nodepresets.py プロジェクト: sgadsden/_NukeStudio
def buildPresetSavePanel(nodeName, node=None):
    if (node == None):
        node = nuke.toNode(nodeName)
    return CreateNodePresetsPanel(node).showModalDialog()