def WaitForSubmissions( submitThreads ):
	for thread in submitThreads:
		thread.join()
	
	nuke.executeInMainThread( nuke.message, multiJobResults )
	
	print "Results thread exiting"
예제 #2
0
    def do_POST(self):
        post_data_len = int(self.headers['Content-Length'])
        post_data = self.rfile.read(post_data_len)

        print post_data
        sys.stdout.flush()

        updatedNodes = 0
        for blinknode in nuke.allNodes("BlinkScript"):
            print blinknode
            if os.path.samefile(post_data,
                                blinknode.knob("kernelSourceFile").getValue()):
                print "Found {0}, reloading".format(blinknode.name())

                # Force control panel to be shown or else the knobs won't execute properly
                nuke.executeInMainThread(blinknode.showControlPanel, ())
                # nuke.executeInMainThread(blinknode.knob("clearKernelSource").execute, ())
                nuke.executeInMainThread(
                    blinknode.knob("reloadKernelSourceFile").execute, ())
                # nuke.executeInMainThread(blinknode.hideControlPanel, ())

                updatedNodes += 1

        nuke.debug("Updated {0} Blink nodes in script {1}".format(
            updatedNodes, post_data))

        self.send_response(200)  # OK Response

        return
예제 #3
0
def trackRangeForward():
    node = nuke.thisNode()
    size = nuke.thisNode()['size'].value()
    rootLayer = node.knob("curves").rootLayer
    curve = node.knob("curves").getSelected()[0]
    start = int(nuke.root()['frame'].value())
    end = int(nuke.root()['last_frame'].value())
    task = nuke.ProgressTask('Baking camera from meta data in %s' %
                             node.name())
    for i in range(start, end):
        if task.isCancelled():
            nuke.executeInMainThread("")
            break
        task.setMessage('processing frame %s' % i)
        task.setProgress(int((float(i - start) / float(end)) * 100))
        temp = nuke.nodes.CurveTool()
        nuke.execute(temp, i, i)

        nuke.root()['frame'].setValue(i)
        for c, point in enumerate(curve):
            point.center.evaluate(i)
            pos = point.center.getPosition(i)
            print pos
            dx = nuke.sample(node, "red", pos.x, pos.y, size, size)
            dy = nuke.sample(node, "green", pos.x, pos.y, size, size)
            print c, dx, dy
            pos.x = pos.x + dx
            pos.y = pos.y + dy
            point.center.addPositionKey(i, pos)
            node['curves'].changed()
        nuke.delete(temp)
예제 #4
0
	def run(self):
		try:
			self.__node['file'].setValue(self.__filename)
			self.__node['proxy'].setValue(self.__filename)
			nuke.executeInMainThread(nuke.execute, args=(self.__node, self.__start, self.__end, 1), kwargs={'continueOnError': True})
		except Exception as e:
			print 'Warning: %s' % (e)
예제 #5
0
파일: archive.py 프로젝트: khpang/vfxpipe
    def action2(self):

        task = nuke.ProgressTask("Copying")
        task.setMessage('fsdf')
        lenght = len(self.copyDic)
        x = 0.0
        totalSize = 0.0

        for k, v in self.copyDic.iteritems():
            totalSize += v[1]
        totalSize = round((totalSize / 1000000000), 2)
        toGoSize = 0.0

        myList = []

        for i in self.copyDic:
            myList.append(i)
        myList.sort()
        for i in myList:

            p = int((x / lenght) * 100)
            task.setProgress(p)
            toGoSize = toGoSize + self.copyDic[i][1]
            progressStr = '	  (%s/%s)' % (int(x), lenght)
            size = '  ' + str(round(
                (toGoSize / 1000000000), 2)) + ' / ' + str(totalSize) + ' GB'
            task.setMessage(os.path.basename(i) + progressStr + size)
            shutil.copy(i, self.copyDic[i][0])
            x += 1
            if task.isCancelled():
                nuke.executeInMainThread(nuke.message, args=("Canceled"))
                break

        self.replacePath()
예제 #6
0
def create_snapshot_screenshot(DEV=None, snapImageFile=None):
    """
    Writes screenshot of currrent viewer and 100px thumbnail from it, chmod 444 both
    :param DEV: Debug level
    :param snapImageFile: Absolute path to .jpeg
    """
    if DEV > 0:
        import threading
        print "\n~ ---- Calling from: " + str(threading.current_thread())
        for x in threading.enumerate():
            print "* " + str(x)

    def captr():
        if DEV > 0:
            print "* executeInMainThread(): " + str(threading.current_thread())
        nuke.activeViewer().node().capture(snapImageFile)

    nuke.executeInMainThread(captr)
    im = Image.open(snapImageFile)
    imSize = ('', 100)
    im.thumbnail(imSize, Image.ANTIALIAS)
    imgPathThumb = str(snapImageFile).replace('jpg', 'thumb') + '.jpg'
    im.save(imgPathThumb, 'JPEG')
    os.chmod(snapImageFile, 0444)
    os.chmod(imgPathThumb, 0444)
    print "\n~ Writing autosnap screenshot: " + str(snapImageFile)
예제 #7
0
    def download(self, shotName):
        # NOTES _______________________________________________________________
        # need to integrate/share with SubmitShot()
        #_Notes for next version_
        # 1) create localShotFolder
        # 2) create subFolderStructure
        # 3) checkbox to include:
        #       raw footage,
        #       most recent submission,
        #       pipeline layers
        # 4) copy() selected items + Production Stitches
        # 5) version up & create new shotFolder
        # ------------------------------------------------------------------------------------------
        progIncr = 100.0 / self.numberOfThings

        def copy(src, dst):
            fsrc = open(src, 'rb').read()
            with open(dst, 'wb') as fdst:
                fdst.write(fsrc)
            fsrc.close()
            fdst.close()
        if self.task.isCancelled():
            nuke.executeInMainThread(nuke.message, args=("Aborted!"))
            return
        newDir = 'd:' + os.sep + self.showCode + '_' + shotName  # temp
        if not os.path.exists(newDir):
            os.mkdir(newDir)
            if not os.path.exists(os.path.join(newDir, self.showCode + '_' + shotName + '_v' + 005)):
                os.mkdir(os.path.join(newDir, self.showCode + '_' + shotName + '_v' + 005))
예제 #8
0
def _cvTracker( node, shapeName, cvID, fRange ):
    shape = node['curves'].toElement( shapeName )
   
    # SHAPE CONTROL POINT
    try:
        shapePoint = shape[cvID]
    except IndexError:
        nuke.message( 'Index %s not found in %s.%s' % (  ) )
        return

    # ANIM CONTROL POINT
    animPoint = shapePoint.center   
        
    # CREATE A TRACKER NODE TO HOLD THE DATA
    tracker = nuke.createNode( 'Tracker3' )
    tracker['label'].setValue( 'tracking cv#%s in %s.%s' % ( cvID, node.name(), shape.name ) )
    trackerKnob = tracker['track1']
    trackerKnob.setAnimated()    
    
    # SET UP PROGRESS BAR
    task = nuke.ProgressTask( 'CV Tracker' )
    task.setMessage( 'tracking CV' )
    
    # DO THE WORK
    for f in fRange:
        if task.isCancelled():
            nuke.executeInMainThread( nuke.message, args=( "CV Track Cancelled" ) )
            break
        task.setProgress( int( float(f)/fRange.last() * 100 ) )
        
        # GET POSITION
        pos = animPoint.getPosition( f )
        nuke.executeInMainThreadWithResult( trackerKnob.setValueAt, args=( pos.x, f, 0 ) ) # SET X VALUE
        nuke.executeInMainThreadWithResult( trackerKnob.setValueAt, args=( pos.y, f, 1 ) ) # SET Y VALUE
예제 #9
0
def FreeReservedSlaves(jobID, closed=False):
    if (jobID != None and jobID != ""):

        job = CallDeadlineCommand(["-getjob", jobID])

        if "JobStatus=Active" in job:

            output = CallDeadlineCommand(["-completejob", jobID])
            message = "Slaves released for job " + str(jobID)
            if closed:
                message = message + " because the dialog was closed!"
                nuke.executeInMainThread(showNukeMessage, message)
            else:
                nuke.executeInMainThread(updateOutputBox, message)

        elif dialog is not None:
            nuke.executeInMainThread(
                updateOutputBox,
                "Job was not active. Reserved Slaves were previously released."
            )

        if dialog is not None:
            nuke.executeInMainThread(toggleReserveButton)
            nuke.executeInMainThread(toggleFields)

            dialog.JobID = None
예제 #10
0
	def render():
		print "Background rendering %s" % name
		try:
			Popen(cmd).wait()
		except WindowsError: # TODO: WTF is up with this?
			os.popen(cmd).read()
		nuke.message("%s Background render finished!" % name)
		nuke.executeInMainThread(nuke.toNode(name)['reading'].setValue,True)
		os.remove(np)
예제 #11
0
def selfDestruct():
    task = nuke.ProgressTask("Self Destructing")
    task.setMessage("Deleting files")
    for i in xrange(0, 100):
        if task.isCancelled():
            nuke.executeInMainThread(nuke.message, args=("Stop!"))
            break
        task.setProgress(i)
        time.sleep(0.5)
예제 #12
0
def submitJobProgress():
    task = nuke.ProgressTask("Self Destructing")
    task.setMessage("Deleting files")
    for i in xrange( 0, 100 ):
        if task.isCancelled():
            nuke.executeInMainThread( nuke.message, args=( "Phew!" ) )
            break;
        task.setProgress(i)
        time.sleep( 0.5 )
    threading.Thread( None, selfDestruct ).start()
예제 #13
0
def submitJobProgress():
    task = nuke.ProgressTask("Self Destructing")
    task.setMessage("Deleting files")
    for i in xrange(0, 100):
        if task.isCancelled():
            nuke.executeInMainThread(nuke.message, args=("Phew!"))
            break
        task.setProgress(i)
        time.sleep(0.5)
    threading.Thread(None, selfDestruct).start()
예제 #14
0
def versionSwith():
    flag = nuke.ask('Are you sure you want to switch the Nuke type?')
    if flag:
        nuke.scriptSave()
        nukeScript = nuke.scriptName()
        nukeExe = sys.executable
        if nuke.env['nukex'] == True:
            nukeProcess = subprocess.Popen([nukeExe, nukeScript])
        else:
            nukeProcess = subprocess.Popen([nukeExe, "--nukex", nukeScript])
        nuke.executeInMainThread(nuke.scriptExit)
예제 #15
0
def versionSwitch():
    nuke.scriptSave() # Save current script
    nukeScript = nuke.root().knob('name').value() # Find current script path
    nukeExe = sys.executable # Find executable path
    if nuke.env['nukex'] == True: # Check Nuke or Nuke X
        nukeProcess = subprocess.Popen([nukeExe, nukeScript]) # Launch Nuke
        print 'Close nukeX and launch nuke'
    else:
        nukeProcess = subprocess.Popen([nukeExe, "--nukex", nukeScript]) # Launch Nuke X
        print 'Close nuke and launch nukeX'
    nuke.executeInMainThread(nuke.scriptExit) # Close current script
예제 #16
0
def index(cmdString="world"):
	cmd = "Cannot decode command.\n"
	try:
		cmd = decode(cmdString)
		def c():
			print cmd
			eval(cmd)
		nuke.executeInMainThread(c)
	except:
		pass
	return cmd
예제 #17
0
def copyFiles(render_path, exr_dest_fulldir):
    task = nuke.ProgressTask("Copy Files")
    task.setMessage("Copying files")
    fileList = glob.glob(os.path.join(os.path.dirname(render_path), r'*.exr'))

    for count, exrfile in enumerate(fileList):
        shutil.copy(exrfile, exr_dest_fulldir)
        if task.isCancelled():
            nuke.executeInMainThread(nuke.message, args=("Copy Cancelled!"))
            break
        task.setProgress(float(count) / float(len(fileList)))
예제 #18
0
    def convert(self):
        self.task = nuke.ProgressTask("NukeToPacking....")
        pack_dir = self.pack_dir + '/'
        pack_dir = self.unified_path_format(pack_dir)
        reads = [n for n in nuke.allNodes(recurseGroups=True) if n.Class() == 'Read']
        prog_incr = 100.0 / len(reads)
        for i, n in enumerate(reads):
            if self.task.isCancelled():
                nuke.executeInMainThread(nuke.message, args=('cancel',))
                return
            self.task.setProgress(int(i * prog_incr))

            file_ = n['file'].getValue()
            self.task.setMessage("Copy %s files.." % n.fullName())
            if self.check_format(file_):
                m = re.compile(r'(?P<root_dir>(\w:/))')
                match_ = m.match(file_)
                if match_:
                    old_file = file_
                    file_root = match_.groupdict()['root_dir']
                    file_ = file_.replace(file_root, pack_dir)
                    file_ = self.unified_path_format(file_)
                    new_dir = os.path.dirname(file_)
                    if not os.path.exists(new_dir):
                        os.makedirs(new_dir)
                    print old_file, new_dir,'single'
                    shutil.copy2(old_file, new_dir)
                    n['file'].setValue(file_.replace(pack_dir, self.pack_))
            else:
                dir_ = os.path.dirname(file_)
                for f in os.listdir(dir_):
                    seq_file_ = dir_ + "/" + f
                    m = re.compile(r'(?P<root_dir>(\w:/)(.+?/))')
                    match_ = m.match(seq_file_)
                    if match_:
                        old_file = seq_file_
                        file_root = match_.groupdict()['root_dir']
                        seq_file_ = seq_file_.replace(file_root, pack_dir)
                        seq_file_ = self.unified_path_format(seq_file_)
                        new_dir = os.path.dirname(seq_file_)
                        if not os.path.exists(new_dir):
                            os.makedirs(new_dir)
                        print old_file, new_dir
                        shutil.copy2(old_file, new_dir)
                m = re.compile(r'(?P<root_dir>(\w:/)(.+?/))')
                match_ = m.match(file_)
                if match_:
                    file_root = match_.groupdict()['root_dir']
                    n['file'].setValue(file_.replace(file_root, self.pack_))
        nuke.scriptSaveAs(joinpath(self.pack_dir, '{0}.nk'.format(self.base_name)))
        with open(joinpath(self.pack_dir, 'nuke2pack.info'), 'w') as f:
            f.write('Nuke: {0}'.format(self.nuke_version))
        self.to_zip()
        time.sleep(2)
예제 #19
0
def setSocketKnobState(active):
    """Turns on or off the 'enable socket' knob on the Mari tab.
    
    @param active: True or False
    """
    def setStates(active):
        root = nuke.root()
        root['enableSocket'].setValue(active)
        root['socketPort'].setEnabled(not active)
    
    nuke.executeInMainThread(lambda: setStates(active))
예제 #20
0
def Destruct(sourceDir,targetDir,obj):
    copyDate = getdirsize(targetDir)
    allData = getdirsize(sourceDir)
    task = nuke.ProgressTask("copying......")
    task.setMessage(obj)
    while (copyDate < allData):
        if task.isCancelled():
            nuke.executeInMainThread( nuke.message, args=( "确定中断复制!!!" ) )
            break
        task.setProgress(copyDate / allData * 100)
        time.sleep(1)
        copyDate = copyVFXNukeFile().getdirsize(targetDir)
예제 #21
0
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 
예제 #22
0
파일: snippet.py 프로젝트: szabo92/gistable
    def reset(self, gamebox):
        """Reset ball to centre. Reset velocity"""
        x, y = gamebox.xpos(), gamebox.ypos()
        w, h = gamebox.screenWidth(), gamebox.screenHeight()

        cx = x + (w / 2)
        cy = y + (h / 2)

        r = 2 - (random() * 4)

        if self.vx > 0:
            self.vx, self.vy = 4, 0
        else:
            self.vx, self.vy = -4, 0

        nuke.executeInMainThread(self.node.setXYpos, (cx, cy))
예제 #23
0
파일: HComNukeUtils.py 프로젝트: GJpy/HCom
def createAlembic(data, sender = "", settings=None):
    
    name = data["NAME"]
    binary = data["DATA"]
    
    abcFile = fetchMyReceivedFilesFolder() + os.sep + name + ".abc"
    abcFile = incrementFile(abcFile)
    
    with open(abcFile, 'wb') as f:
        f.write(binary)
    
    fileName = name = name + "_from_" + sender
    
    nuke.executeInMainThread(_importAlembic, args=(fileName, abcFile))
        
    return True
예제 #24
0
def reconnectMissing(indexCmd):
	# On Windows, use Everything (http://www.voidtools.com/).
	# Assumes "es.exe" command line program is in PATH. Note that
	# "es.exe" doesn't work with networked drives.
	# On OS X, use Spotlight.
	errors = [n for n in nuke._allNodes() if n.hasError() and nuke.filename(n) is not None]
	if errors:
		task = nuke.ProgressTask("Missing files!")
		task.setMessage("Reconnecting %i nodes" % len(errors))
		checkLog = False
		for (i,node) in enumerate(errors):
			(dirPath, basename, searchStr) = nuke.actualFilename(node)
			print "Reconnecting %s --> %s" % (node.name(), searchStr)
			results = [l.strip() for l in os.popen("""%s "%s" """ % (indexCmd,searchStr)).readlines()]
			def getNewPath(resultLine):
				(newPath, newBase) = os.path.split(resultLine)
				setPath = re.sub("\\\\","/",newPath) + "/" + basename
				return setPath
			if len(results)==1:
				node['file'].setValue(getNewPath(results[0]))
			elif len(results)>1:
				checkLog = True
				if 'checksums' in node.knobs().keys():
					crc = node['checksums'].value()
					checksums = [hashlib.sha1(open(f).read(10485760)).hexdigest() for f in results]
					if crc in checksums:
						res = results[checksums.index(crc)]
						node['file'].setValue(getNewPath(res))
					else:
						msg = "%s: CRC mismatch with found files" % node.name()
						print "-"*40 + "\n" + msg
						for (i,line) in enumerate(results): print "[%i] %s" % (i,line)
				else:
					node['file'].setValue(getNewPath(results[0]))
					msg = "More than 1 file found for %s:" % node.name()
					print "-"*40 + "\n" + msg
					for (i,line) in enumerate(results): print "[%i] %s" % (i,line)
			else:
				print "Reconnection failed. No files found."
			task.setProgress(int(i*1./len(errors)*100))
		if checkLog:
			msg = "More than 1 file was found for some nodes.\nCheck script editor."
			nuke.executeInMainThread( nuke.message, args=(msg) )
	else:
		pass
예제 #25
0
def trackChunkForward():
    node = nuke.thisNode()
    chunk = nuke.thisNode()['chunk'].value()
    size = nuke.thisNode()['size'].value()
    rootLayer = node.knob("curves").rootLayer
    curve = node.knob("curves").getSelected()[0]
    start = int(nuke.root()['frame'].value())
    end = int(start + chunk) + 1
    task = nuke.ProgressTask('Baking camera from meta data in %s' %
                             node.name())
    pvals = [0] * len(curve)
    for i in range(start, end):
        if task.isCancelled():
            nuke.executeInMainThread("")
            break
        task.setMessage('processing frame %s' % i)
        task.setProgress(int((float(i - start) / float(end)) * 100))
        temp = nuke.nodes.CurveTool()
        nuke.execute(temp, i, i)
        nuke.root()['frame'].setValue(i)
        print pvals
        for c, point in enumerate(curve):
            point.center.evaluate(i)
            if i == start:
                pos = point.center.getPosition(i)
            else:
                pos = pvals[c]
            posNextFrm = point.center.getPosition(i + 1)
            dx = nuke.sample(node, "red", pos.x, pos.y, size, size)
            dy = nuke.sample(node, "green", pos.x, pos.y, size, size)
            if posNextFrm != pos:
                pos.x = (pos.x + dx + posNextFrm.x) / 2
                pos.y = (pos.y + dy + posNextFrm.y) / 2
            else:
                pos.x = pos.x + dx
                pos.y = pos.y + dy
            if i == end - 1:
                point.center.addPositionKey(i, pos)
            else:
                pvals[c] = pos
        node['curves'].changed()
        nuke.delete(temp)
예제 #26
0
def updateList():
    global dialog

    jobID = dialog.JobID

    while jobID != "" and jobID is not None:
        nuke.executeInMainThread(updateJobID, jobID)

        servers = CallDeadlineCommand(["GetSlavesRenderingJob", jobID])

        nuke.executeInMainThread(updateReservedMachines, servers)

        job = CallDeadlineCommand(["-getjob", jobID])

        if "JobStatus=" in job:
            status = job.split("JobStatus=")[1].split("\n")[0]

            if status == "Active":
                if len(servers) > 0:
                    status = "Rendering"
                else:
                    status = "Queued"
            elif status == "":
                status = "Deleted"

            nuke.executeInMainThread(updateJobStatus, status)

        sleep(5.0)

        if dialog is not None:
            jobID = dialog.JobID
        else:
            jobID = ""
예제 #27
0
    def action2(self):

        task = nuke.ProgressTask("Copying")
        task.setMessage('fsdf')
        lenght = len(self.copyDic)
        x = 0.0
        totalSize = 0.0

        for k,v in self.copyDic.iteritems():
            totalSize+= v[1]
        totalSize = round((totalSize/1000000000),2)
        toGoSize = 0.0

        myList = []

        for i in self.copyDic:
            myList.append(i)
        myList.sort()
        for i in myList:

            p = int((x/lenght)*100)
            task.setProgress(p)
            toGoSize = toGoSize + self.copyDic[i][1]
            progressStr = '	  (%s/%s)' % (int(x),lenght)
            size = '  '+str(round((toGoSize/1000000000),2))+' / ' +str(totalSize) +' GB'
            task.setMessage(os.path.basename(i) + progressStr +size)
            shutil.copy( i,self.copyDic[i][0])
            x+=1
            if task.isCancelled(): 
                nuke.executeInMainThread( nuke.message, args=( "Canceled" ) )
                break






        self.replacePath()
예제 #28
0
def _pointsToKeys(curve, knob, fRange):
    '''
    Set keys along a shape.
    args:
        shape - CubicCurve to define animation path
        knob - knob to set keys on. This needs to be an Array_Knob
        fRange  - frame range across which to set keys (first frame = start of shape, last frame = end of shape)
    '''
    task = nuke.ProgressTask('Shape Tracker')
    task.setMessage('tracking shape')
    for f in fRange:
        # TAKE CARE OF PROGRESS BAR
        if task.isCancelled():
            nuke.executeInMainThread(nuke.message,
                                     args=("Shape Track Cancelled"))
            break
        task.setProgress(int(float(f) / fRange.last() * 100))
        # DO THE WORK
        curPoint = curve.getPoint(float(f) / fRange.last())
        nuke.executeInMainThreadWithResult(knob.setValueAt,
                                           args=(curPoint.x, f, 0))
        nuke.executeInMainThreadWithResult(knob.setValueAt,
                                           args=(curPoint.y, f, 1))
예제 #29
0
    def to_zip(self):
        dir_name = self.pack_dir
        zipfilename = joinpath(self.source_dir, '{0}.zip'.format(self.base_name))
        filelist = []
        if os.path.isfile(dir_name):
            filelist.append(dir_name)
        else:
            for root, dirs, files in os.walk(dir_name):
                for name in files:
                    filelist.append(os.path.join(root, name))

        zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED, True)
        prog_incr = 100.0 / len(filelist)
        for i, tar in enumerate(filelist):
            if self.task.isCancelled():
                nuke.executeInMainThread(nuke.message, args=('cancel',))
                return
            self.task.setProgress(int(i * prog_incr))
            arcname = tar[len(dir_name):]
            self.task.setMessage("compressed %s files.." % arcname)
            zf.write(tar, arcname)
        zf.close()
        time.sleep(2)
예제 #30
0
    def to_zip(self):
        dir_name = self.pack_dir
        zip_file_name = joinpath(self.source_dir,
                                 '{0}.zip'.format(self.base_name))
        file_list = []
        if os.path.isfile(dir_name):
            file_list.append(dir_name)
        else:
            for root, dirs, files in os.walk(dir_name):
                for name in files:
                    file_list.append(os.path.join(root, name))

        zf = zipfile.ZipFile(zip_file_name, "w", zipfile.zlib.DEFLATED, True)
        index = 100.0 / len(file_list)
        for i, tar in enumerate(file_list):
            if self.task.isCancelled():
                nuke.executeInMainThread(nuke.message, args=('cancel',))
                return
            self.task.setProgress(int(i * index))
            archive_name = tar[len(dir_name):]
            self.task.setMessage("Compressed %s files.." % archive_name)
            zf.write(tar, archive_name)
        zf.close()
        time.sleep(2)
예제 #31
0
    def run(self):
        # Store the current dag size and zoom
        original_zoom = nuke.zoom()
        original_center = nuke.center()
        # Calculate the total size of the DAG
        min_x, min_y, max_x, max_y = self.bbox
        zoom = self.zoom
        min_x -= int(self.margins / zoom)
        min_y -= int(self.margins / zoom)
        max_x += int(self.margins / zoom)
        max_y += int(self.margins / zoom)

        # Get the Dag Widget
        dag = self.dag

        # Check the size of the current widget, excluding the right side (because of minimap)
        capture_width = dag.width() - self.ignore_right
        capture_height = dag.height()

        # Calculate the number of tiles required to cover all
        image_width = int((max_x - min_x) * zoom)
        image_height = int((max_y - min_y) * zoom)
        horizontal_tiles = int(ceil(image_width / float(capture_width)))
        vertical_tiles = int(ceil(image_height / float(capture_height)))
        # Create a pixmap to store the results
        pixmap = QtGui.QPixmap(image_width, image_height)
        painter = QtGui.QPainter(pixmap)
        painter.setCompositionMode(painter.CompositionMode_SourceOver)
        # Move the dag so that the top left corner is in the top left corner, screenshot, paste in the pixmap, repeat
        for tile_x in range(horizontal_tiles):
            center_x = (min_x + capture_width / zoom * tile_x
                        ) + (capture_width + self.ignore_right) / zoom / 2
            for tile_y in range(vertical_tiles):
                center_y = (min_y + capture_height / zoom *
                            tile_y) + capture_height / zoom / 2
                nuke.executeInMainThread(nuke.zoom,
                                         (zoom, (center_x, center_y)))
                time.sleep(self.delay)
                nuke.executeInMainThread(grab_dag,
                                         (dag, painter, capture_width * tile_x,
                                          capture_height * tile_y))
        time.sleep(self.delay)
        painter.end()
        nuke.executeInMainThread(nuke.zoom, (original_zoom, original_center))
        save_sucessful = pixmap.save(self.path)
        if not save_sucessful:
            raise IOError("Failed to save PNG: %s" % self.path)
        self.successful = True
예제 #32
0
nuke.addOnScriptLoad(store_recent)
nuke.addOnScriptSave(store_recent)

if nuke.env['NukeVersionMajor'] < 11:
    execfile(os.path.join(main_folder, moduleName, "main.py"))

    ### Import Required Modules ###
    def WelcomeScreen_start():
        ws = WelcomeScreen()
        ws.start()

    ### Registering Menu ###
    menu = nuke.menu('Nuke')
    menu.addCommand('General/Welcome Screen',
                    lambda f=WelcomeScreen_start: nuke.executeInMainThread(f),
                    'ctrl+shift+w')

    ### Start Up Show ###
    if wsconfig.get_settings()['startup_show']:
        nuke.executeInMainThread(WelcomeScreen_start)

else:
    ### Import Required Modules ###
    exec("from {0} import main as wsgui".format(moduleName))

    ### Registering Menu ###
    menu = nuke.menu('Nuke')
    menu.addCommand('General/Welcome Screen',
                    lambda f=wsgui.start: nuke.executeInMainThread(f),
                    'ctrl+shift+w')
예제 #33
0
    def run(self):
        self.task = nuke.ProgressTask("Archive....")
        pack_dir = self.pack_dir + '/'
        pack_dir = self.unified_path_format(pack_dir)
        reads = [
            n for n in nuke.allNodes(recurseGroups=True)
            if n.Class() in ARCHIVE_TYPES
        ]
        process_bar_index = 100.0 / len(reads)
        for i, n in enumerate(reads):
            if self.task.isCancelled():
                nuke.executeInMainThread(nuke.message, args=('cancel',))
                return
            self.task.setProgress(int(i * process_bar_index))
            file_ = n['file'].getValue()
            self.task.setMessage("Copy %s files.." % n.fullName())
            if self.check_format(file_):
                m = re.compile(r'(?P<root_dir>(\w:/))')
                match_ = m.match(file_)
                if match_:
                    old_file = file_
                    file_root = match_.groupdict()['root_dir']
                    file_ = file_.replace(file_root, pack_dir)
                    file_ = self.unified_path_format(file_)
                    new_dir = os.path.dirname(file_)
                    if not os.path.exists(new_dir):
                        os.makedirs(new_dir)
                    if not os.path.isfile(new_dir):
                        shutil.copy2(old_file, new_dir)
                    n['file'].setValue(file_.replace(pack_dir, self.pack_))
            else:
                dir_ = os.path.dirname(file_)
                for f in os.listdir(dir_):
                    seq_file_ = dir_ + "/" + f
                    m = re.compile(r'(?P<root_dir>([a-zA-Z]:/)(.+?/))')
                    match_ = m.match(seq_file_)
                    if match_:
                        old_file = seq_file_
                        # file_name, _, ext = old_file.split('.')
                        file_root = match_.groupdict()['root_dir']
                        seq_file_ = seq_file_.replace(file_root, pack_dir)
                        seq_file_ = self.unified_path_format(seq_file_)
                        new_dir = os.path.dirname(seq_file_)
                        if not os.path.exists(new_dir):
                            os.makedirs(new_dir)
                        # TODO need fix copy from node frame range
                        if not os.path.isfile(new_dir):
                            shutil.copy2(old_file, new_dir)
                m = re.compile(r'(?P<root_dir>(\w:/)(.+?/))')
                match_ = m.match(file_)
                if match_:
                    file_root = match_.groupdict()['root_dir']
                    n['file'].setValue(file_.replace(file_root, self.pack_))
        nuke.scriptSaveAs(
            joinpath(self.pack_dir, '{0}.nk'.format(self.base_name)),
            overwrite=True)

        # Write the archive info.
        with open(joinpath(self.pack_dir, 'nuke2pack.info'), 'w') as f:
            f.write('Nuke: {0}'.format(self.nuke_version))
        self.to_zip()
        time.sleep(2)
예제 #34
0
	def changeNodeColor(thisName):
		if nuke.thisNode().name() == thisName:
			nuke.executeInMainThread(nuke.toNode(thisName)['tile_color'].setValue,552079871)
			nuke.executeInMainThread(nuke.toNode(thisName)['postage_stamp'].setValue,True)
			nuke.removeKnobChanged(changeNodeColor,thisName,{},"Write")
예제 #35
0
def killNuke():
	nuke.executeInMainThread(nuke.scriptClose, ()) 
예제 #36
0
파일: psd2.py 프로젝트: RonThomas/nuke.env
 def run(self):
   nuke.executeInMainThread( breakoutLayers, self.node )
예제 #37
0
파일: rvNuke.py 프로젝트: hradec/pipeVFX
    def ensureConnection (self, force=False) :
        if (self.rvc.connected) :
            return

        log ("ensureConnection crashed %d force %s" % (self.crashFlag.isSet(), force))
	
	"""
	if (self.crashFlag.isSet() and not force) :
	    log ("prev crashed and not force, so returning")
	    return
	"""

	self.crashFlag.unset()

        args = ["-flags", "ModeManagerPreload=rvnuke_mode", "-network", "-networkPort", str(self.port), "-flags", "rvnukePortFile=%s" % self.portFile]

        usingBuild = False
        if (self.rvExecPath != "") :
            cmd = [ self.rvExecPath ]
        else :
            try :
                src = os.environ["SRC_ROOT"]
                usingBuild = True
            except :
                pass

            cmd = [ src + "/build/run", "--p", src + "/bin/nsapps/RV" ]

        if (not usingBuild and not os.path.exists (self.rvExecPath)) :
            nuke.executeInMainThread (nuke.message,
            ("Sorry '%s' does not exist, please use the 'RV Preferences' menu item or toolbar button to designate the RV executable." % self.rvExecPath,))
            return;

        fullcmd = cmd + self.extraArgs.split() + args
        log ("starting cmd %s" % str(fullcmd))
        try :
            os.remove (self.portFile)
        except :
            pass

        try :
            self.rvProc = subprocess.Popen (fullcmd)
            self.rvProc.poll()
            if (self.rvProc.returncode) :
                log              ("ERROR: failed to start RV '%s' return: %d"   % (cmd[0], self.rvProc.returncode))
                sys.stderr.write ("ERROR: failed to start RV '%s' return: %d\n" % (cmd[0], self.rvProc.returncode))
                return
        except :
            log              ("ERROR: failed to start RV '%s'"   % cmd[0])
            sys.stderr.write ("ERROR: failed to start RV '%s'\n" % cmd[0])
            return

        
        self.port = 0
        for i in range (300) :
            if (os.path.exists (self.portFile)) :
                f = open (self.portFile)
                self.port = int(f.read())
                f.close()
                break
            else :
                time.sleep (0.1)

        log ("got port: %d" % self.port)
        if (self.port == 0) :
            log              ("ERROR: failed to connect to running RV")
            sys.stderr.write ("ERROR: failed to connect to running RV\n")
            return

        try :
            os.remove (self.portFile)
        except :
            pass

        if (self.port != 0) :
            log ("connecting")
            self.rvc.connect ("127.0.0.1", self.port)
            if (not self.rvc.connected) :
                log ("connect failed")

            self.rvc.handlers["remote-python-eval"] = pythonHandler;
예제 #38
0
def writeFile(node, fileOut):
    tic = timeit.default_timer()
    # if len(nuke.selectedNodes()) != 1:
    #     nuke.message("Exactly one BakedPointCloud node should be selected.")
    #     return

    # This string represents the XYZ positions
    xyzString = node.knob("serializePoints").getValue()
    # This string represents the RGB Colour
    rgbString = node.knob("serializeColors").getValue()
    # Create the .csv file
    csvString = fileOut
    # Open it for writing
    csvFile = open(csvString, 'w')
    # Find out the total number of points
    xyzGen = next_three(xyzString)
    rgbGen = next_three(rgbString)
    totalPoints = int(next(xyzGen))
    # We actually don't use the value below, but we need to get the first
    # generator value so that when we start getting the subsequent values,
    # we have the useless first value already out of the way.
    next(rgbGen)
    # Create a counter variable for use in the progress bar
    counter = 0
    # Create the IO String that the csv data is temporarily cached to
    writeString = cStringIO.StringIO()
    # Write the file headers that Krakatoa's PRT loader wants
    csvFile.write(
        "float32 Position[0], float32 Position[1], float32 Position[2],"
        " float16 Color[0], float16 Color[1], float16 Color[2]\n")
    # Create a new task for the threader to run.
    task = nuke.ProgressTask("Saving Data...")
    # Loop through the number of points, defined by the first return from
    # the generator functions
    for g in range(1, totalPoints):
        # Set up the cancel behaviour:
        if task.isCancelled():
            csvFile.close()
            nuke.executeInMainThread(nuke.message, args=("Aborted", ))
            return
        # write out the line for this point
        lineToWrite = "{x},{y},{z},{r},{g},{b}\n".format(x=next(xyzGen),
                                                         y=next(xyzGen),
                                                         z=next(xyzGen),
                                                         r=next(rgbGen),
                                                         g=next(rgbGen),
                                                         b=next(rgbGen))
        writeString.write(lineToWrite)
        counter = counter + 1
        # Calculate the progress value.
        task.setProgress(int(100 * (float(counter) / float(totalPoints))))
        # Set a progress message.
        task.setMessage(("Caching point " + str(counter)))
        if (counter % 20000) == 0:
            toc = timeit.default_timer()
            processingTime = str(round((toc - tic), 1))
            print("Time to {} points: {}s - {}%".format(
                str(counter), processingTime,
                str(int(100 * (float(counter) / float(totalPoints))))))
    # Write the output
    print("Writing out .csv File...")
    csvFile.write(writeString.getvalue())
    writeString.close()
    # Close the file to save it.
    csvFile.close()
예제 #39
0
            def copyPrerenders():
                # NOTES _______________________________________________________
                # 1. after aborting, need to delete the files
                #--------------------------------------------------------------
                def copy(src, dst):
                    fsrc = open(src, 'rb').read()
                    with open(dst, 'wb') as fdst:
                        fdst.write(fsrc)

                task = nuke.ProgressTask("Submitting...")
                versionFiles = os.listdir(self.versionFolder.path.local)
                arr = versionFiles
                frames = os.listdir(localPrerenders)
                progIncr = 100.0 / len(frames)
                acceptedFiles = {
                    'Prerenders': 'Prerenders',
                    '360_3DV.mp4': '_360_3DV.mp4',
                    'mocha': '.moc',
                    'ae': '.ae',
                    'shotNotes': 'shotNotes.txt'
                }
                exceptions = []
                for i, f in enumerate(frames):
                    if task.isCancelled():
                        nuke.executeInMainThread(nuke.message,
                                                 args=("Aborted!"))
                        return
                    task.setProgress(int(i * progIncr))
                    task.setMessage(f)
                    for item in acceptedFiles:
                        # copy prerenders folder and contents
                        if item == 'Prerenders':
                            copyFrom = os.path.join(localPrerenders, f)
                            copyTo = os.path.join(remotePrerenders, f)
                            try:
                                copy(copyFrom, copyTo)
                            except:
                                msg = "--> No 'Prerenders' folder found!\n"
                                exceptions.append(msg)
                        # copy mp4 preview
                        elif item == '360_3DV.mp4':
                            copyFrom = os.path.join(
                                self.versionFolder.path.local,
                                (self.filename + '_v' +
                                 str(self.versionFolder.ver.local).zfill(3) +
                                 '_360_3DV.mp4'))
                            copyTo = os.path.join(
                                os.path.join(
                                    self.shotFolder.path.remote,
                                    (self.filename + '_v' +
                                     str(self.versionFolder.ver.remote +
                                         1).zfill(3))),
                                (self.filename + '_360_3DV.mp4'))
                            try:
                                copy(copyFrom, copyTo)
                            except:
                                msg = "--> No '360_3DV.mp4' found!\n"
                                exceptions.append(msg)
                nuke.executeInMainThread(
                    nuke.message,
                    args=('Shot succsessfully submitted to Gladiator as: ' +
                          self.showCode + '_' + newVersionFolderName +
                          '.\n\nGood work! ;p'))
                return
예제 #40
0
        def downloadThread():
            # 1) create localShotFolder
            try:
                localShotFolder = os.path.join(self.user.workingDir,
                                               self.filename)
                os.mkdir(localShotFolder)
                # 2) create subFolderStructure
                c1_tools.createShotFolder('auto', localShotFolder)
            except:
                nuke.executeInMainThread(
                    nuke.message,
                    args=('Shot-folder and version already exists locally!'))
                # split filename into 2 parts: name & version
                fragments = os.path.basename(
                    self.versionFolder.path.local).split('_v')
                newVersionFolder = os.path.join(
                    self.shotFolder.path.local,
                    fragments[0] + '_v' + str(int(fragments[1]) + 1))
                self.versionFolder.path.set('local', newVersionFolder)
                del (self.task)
                return

            # 3) copy Production Stitches
            try:
                remote_productionStitches = os.path.join(
                    self.shotFolder.path.remote, '__ProductionStitches')
                thingsToCopy = os.listdir(remote_productionStitches)
                local_productionStitches = os.path.join(
                    self.shotFolder.path.local, '__ProductionStitches')
                for thing in thingsToCopy:
                    if len(thing.split('Pano-LR')) > 1:
                        continue
                    if os.path.exists(
                            os.path.join(local_productionStitches, thing)):
                        continue
                    self.copyfileobj(
                        os.path.join(remote_productionStitches, thing),
                        os.path.join(local_productionStitches, thing))
            except:
                nuke.executeInMainThread(
                    nuke.message,
                    args=
                    ('No \'__ProductionStitches\' folder found for this shot!'
                     ))
                del (self.task)

            # 5) version up & create new versionFolder
            newVersionFolder = os.path.join(
                self.shotFolder.path.local,
                self.filename + '_v' + str(self.fileversion + 1).zfill(3))
            os.mkdir(newVersionFolder)
            self.versionFolder.path.set('local', newVersionFolder)
            if self.fileversion > 0:
                for thing in os.listdir(self.versionFolder.path.remote):
                    for fragment in self.acceptedFiles:
                        if len(thing.split(fragment)) > 1:
                            target = os.path.join(
                                self.versionFolder.path.remote, thing)
                            shutil.copyfile(
                                target,
                                os.path.join(
                                    newVersionFolder, self.filename + '_v' +
                                    str(self.fileversion + 1).zfill(3) +
                                    '.nk'))
            if self.includes:
                if self.includes['Prerenders']:
                    print('Copy Prerenders')
                elif self.includes['Raw']:
                    print('Copy Raw')
            else:
                os.mkdir(os.path.join(newVersionFolder, 'Prerenders'))
            del (self.task)
            return self.versionFolder.path.local
예제 #41
0
 def threadedAuthenticate(self, config):
     if config['kitsu_url'] != '':
         client = KitsuSession(config)
         if client.tokens is None:
             msg = '<b><font color=\"#cc0000\">' + str(
                 client.status) + '</font></b>'
             nuke.executeInMainThread(self.setStatusL, args=(msg, ))
             nuke.executeInMainThread(self.setUIEnabled, args=(True, ))
         else:
             msg = "<b><font color=\"#00cc44\">success!</font></b>"
             nuke.executeInMainThread(self.setStatusL, args=(msg, ))
             nuke.executeInMainThread(self.setUIEnabled, args=(False, ))
             # print('We got our tokens: ' + str(client.tokens))
             nuke.executeInMainThread(self.success, args=(config, ))
     else:
         nuke.executeInMainThread(self.setUIEnabled, args=(True, ))
예제 #42
0
    def ensureConnection(self, force=False):
        if (self.rvc.connected):
            return

        log("ensureConnection crashed %d force %s" %
            (self.crashFlag.isSet(), force))
        """
	if (self.crashFlag.isSet() and not force) :
	    log ("prev crashed and not force, so returning")
	    return
	"""

        self.crashFlag.unset()

        args = [
            "-flags", "ModeManagerPreload=rvnuke_mode", "-network",
            "-networkPort",
            str(self.port), "-flags",
            "rvnukePortFile=%s" % self.portFile
        ]

        usingBuild = False
        if (self.rvExecPath != ""):
            cmd = [self.rvExecPath]
        else:
            try:
                src = os.environ["SRC_ROOT"]
                usingBuild = True
            except:
                pass

            cmd = [src + "/build/run", "--p", src + "/bin/nsapps/RV64"]

        if (not usingBuild and not os.path.exists(self.rvExecPath)):
            nuke.executeInMainThread(nuke.message, (
                "Sorry '%s' does not exist, please use the 'RV Preferences' menu item or toolbar button to designate the RV executable."
                % self.rvExecPath, ))
            return

        fullcmd = cmd + self.extraArgs.split() + args
        log("starting cmd %s" % str(fullcmd))
        try:
            os.remove(self.portFile)
        except:
            pass

        try:
            self.rvProc = subprocess.Popen(fullcmd)
            self.rvProc.poll()
            if (self.rvProc.returncode):
                log("ERROR: failed to start RV '%s' return: %d" %
                    (cmd[0], self.rvProc.returncode))
                sys.stderr.write(
                    "ERROR: failed to start RV '%s' return: %d\n" %
                    (cmd[0], self.rvProc.returncode))
                return
        except:
            log("ERROR: failed to start RV '%s'" % cmd[0])
            sys.stderr.write("ERROR: failed to start RV '%s'\n" % cmd[0])
            return

        self.port = 0
        for i in range(300):
            if (os.path.exists(self.portFile)):
                f = open(self.portFile)
                self.port = int(f.read())
                f.close()
                break
            else:
                time.sleep(0.1)

        log("got port: %d" % self.port)
        if (self.port == 0):
            log("ERROR: failed to connect to running RV")
            sys.stderr.write("ERROR: failed to connect to running RV\n")
            return

        try:
            os.remove(self.portFile)
        except:
            pass

        if (self.port != 0):
            log("connecting")
            self.rvc.connect("127.0.0.1", self.port)
            if (not self.rvc.connected):
                log("connect failed")

            self.rvc.handlers["remote-python-eval"] = pythonHandler
예제 #43
0
파일: snippet.py 프로젝트: szabo92/gistable
 def _setxy(self, v):
     x, y = v
     nuke.executeInMainThread(self.node.setXYpos, (x, y))
     time.sleep(0.001)
예제 #44
0
def writeThread(write_node, start_frame, end_frame):
    nuke.executeInMainThread(nuke.execute,
                             args=(write_node, start_frame, end_frame, 1),
                             kwargs={'continueOnError': True})