def build_tabs_from_ftrack_tasks(self): self.clearLayout() try: del prog except: pass if len(self.tasks) > 0: prog = nuke.ProgressTask( 'Retrieving available tasks from FTrack...') progIncr = 100.0 / len(self.tasks) for i, task in enumerate(self.tasks): self.result = [] if prog.isCancelled(): #nuke.executeInMainThread(nuke.message, args=('Aborted',)) return #####Start #convert each task into a dictionary task_item = self.ftrack_item_to_dict(task) #use the task_item dictionary to populate TaskTab parameters self.scrollLayout.addRow(TaskTab(task_item)) #####End progMsg = ' '.join([task_item['Task'], task_item['Shot']]) prog.setProgress(int(i * progIncr)) prog.setMessage(progMsg) else: print "No Compositing tasks assigned to Artist. Talk to RJ!"
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
def __init__(self, src, dst, data, includes=None): from init import user as c1_user self.gladiator = data.gladiator self.user = c1_user self.filename = data.filename self.fileversion = data.fileversion self.shotName = data.shotName self.src = src self.dst = dst self.includes = includes # folders self.shotFolder = data.shotFolder self.shotFolder.path.set('local', os.path.join(dst, data.filename)) self.versionFolder = data.versionFolder self.versionFolder.path.set( 'local', os.path.join(self.shotFolder.path.local, data.filename + '_v' + str(self.fileversion).zfill(3))) self.showFolder = data.showFolder self.acceptedFiles = { 'nk': '.nk', '360_3DV.mp4': '_360_3DV.mp4', 'mocha': '.moc', 'ae': '.ae', 'shotNotes': 'shotNotes.txt' } self.fileList = [] self.exceptions = [] self.task = nuke.ProgressTask("Downloading...") self.taskBuffer = 0 return
def copyAllNodes(self, *args): grps = nuke.allNodes("Group") reads = nuke.allNodes("Read") start = nuke.root()['first_frame'].value() end = nuke.root()['last_frame'].value() for grp in grps: for n in grp.nodes(): if n.Class() == "Group": grps.append(n) if n.Class() == "Read": reads.append(n) task = nuke.ProgressTask("getRenders") for i, r in enumerate(reads): serverPath = r['file'].value() localPath = serverPath.replace("P:", self.localDrive) dirPath = os.path.dirname(localPath) task.setMessage('processing %s' % dirPath) task.setProgress(int(float(i) / len(reads) * 100)) try: os.makedirs(dirPath) except: pass incr = int(self.frameNthSize.text()) for i in range(int(start), int(end))[::incr]: serverFramePath = serverPath.replace("%04d", str(i).zfill(4)) localFramePath = localPath.replace("%04d", str(i).zfill(4)) print serverFramePath, localFramePath if os.path.exists(serverFramePath ) and not os.path.exists(localFramePath): print "copying", serverFramePath shutil.copy(serverFramePath, localFramePath) del (task)
def transformstoMatrix(nodes, mode=0): #mode 0 creates a cornerpin node with the extra-matrix on it #mode 1 returns a matrix based on all the transforms fRange = nuke.FrameRange( '%s-%s' % (nuke.root().firstFrame(), nuke.root().lastFrame())) for node in nodes: if node.Class() not in ('Transform', 'CornerPin2D', 'Tracker4', 'Tracker3'): if nuke.GUI: msg = 'Unsupported node type: ' + node.Class( ) + '.\n Selected Node must be Transform, CornerPin, Tracker' nuke.message(msg) else: raise TypeError, 'Unsupported node type.\n Selected Node must be Transform, CornerPin, Tracker' return node.knob('selected').setValue(False) nodes = checkOrdering(nodes) if mode == 0: newCpin = nuke.createNode('CornerPin2D') newCpin['transform_matrix'].setAnimated() frameProgressBar = nuke.ProgressTask('Iterating frames : ') frameProgress = 100.0 / max(1.0, nuke.root().lastFrame()) for f in fRange: if frameProgressBar.isCancelled(): frameProgressBar.setProgress(100) nuke.delete(newCpin) break frameProgressBar.setProgress(int(f * frameProgress)) frameProgressBar.setMessage( str(f) + '/' + str(nuke.root().lastFrame())) mainMatrix = nuke.math.Matrix4() mainMatrix.makeIdentity() f = float(f) for node in nodes: #[::-1]: if node.Class() in ('Transform', 'Tracker4', 'Tracker3'): mainMatrix = mainMatrix * transform2DtoMatrix(f, node) if node.Class() in ('CornerPin2D'): mainMatrix = mainMatrix * cpintomatrix(f, node) if mode == 0: for n in range(0, len(mainMatrix)): newCpin['transform_matrix'].setValueAt(mainMatrix[n], f, n) frameProgressBar.setProgress(int(f * frameProgress)) frameProgressBar.setMessage( str(f) + '/' + str(nuke.root().lastFrame())) if mode == 0: try: newCpin.knob('selected').setValue(True) except: pass if mode == 1: return mainMatrix
def _get_progress_task(self): """ Returns a progress task object if enough time has elapsed. """ # If we've started reporting progress already, just return the progress reporter. if self._progress_task: return self._progress_task # If we're waiting for the progress reporting to start, do nothing. if self._state == self.WAITING: return None # If we're currently running. (someone invoked start()) if self._state == self.RUNNING: # If more than MAXIMUM_HIDDEN_TIME seconds have passed since we started, create the widget # and return it. elapsed = time.time() - self._start_time if elapsed > self.MAXIMUM_HIDDEN_TIME: self._progress_task = nuke.ProgressTask( "Initializing Toolkit...") return self._progress_task else: # Not enough time has elapsed, widget will not be available. return None # State is completed, we're done, nothing to report. return None
def filereferenceTask(uploads, frameiosession): """Nuke task for creating the upload object and inspecting all the files""" totalprogress = len(uploads) * 2 + 1 task = nuke.ProgressTask('Preparing uploads') task.setMessage('Upload to frame.io') foldername = 'Nukeuploads' subfolders = frameiosession.getSubfolderdict( frameiosession.getRootfolderkey()) if foldername in subfolders.values(): for id in subfolders: if subfolders[id] == foldername: folderid = id break else: folderid = frameiosession.createSubfolders([foldername])[0]['id'] upload = frameio.Upload(uploads.keys(), frameiosession, folderid) i = 1 for filepath in uploads.keys(): task.setProgress(100 / totalprogress * i) task.setMessage('Inspecting file: ' + filepath) upload.inspectfile(filepath) i += 1 task.setProgress(100 / totalprogress * i) task.setMessage('Creating filereferences') upload.filereference() i += 1 for filepath in uploads.keys(): task.setProgress(100 / totalprogress * i) task.setMessage('Starting upload: ' + filepath) uploads[filepath]['folderid'].setValue(folderid) threading.Thread(None, uploadTask, args=(upload, filepath, uploads[filepath])).start() i += 1
def copyReadToShot(): s = nuke.selectedNodes() for node in s: if node.Class() == "Read": file = node['file'].getValue() base = os.path.basename(file).split( '.')[0] + "*" + os.path.splitext(file)[1] fileList = glob.glob(os.path.join(os.path.dirname(file), base)) print fileList dest = os.path.join(getPixDir(), os.path.basename(file).split('.')[0]) while os.path.exists(dest): dest += "_1" print dest os.mkdir(dest) print dest task = nuke.ProgressTask("Copying Read To Shot Tree") fileCount = len(fileList) for count, imgfile in enumerate(fileList): task.setMessage("copying file: %d of %d" % (count, fileCount)) task.setProgress(int(100 * (count / float(fileCount)))) shutil.copy(imgfile, dest) node['file'].setValue(os.path.join(dest, os.path.basename(file)))
def resetCompStatus(PROJECT_ID,Sequences): sg = shotgun.Shotgun(SERVER_PATH, SCRIPT_USER, SCRIPT_KEY) task = nuke.ProgressTask('reseting shotgun comp status:') for sq in Sequences: fields = ['id', 'code', 'sg_status_list','shots'] filters = [['project','is', {'type':'Project','id':PROJECT_ID}],['code', 'is',sq]] seq = sg.find_one('Sequence',filters,fields) for shot in seq['shots']: fields = ['id', 'code', 'sg_status_list','open_notes'] filters = [['id', 'is',shot['id']],['sg_status_list', 'is_not','omt']] sh= sg.find_one('Shot',filters,fields) if sh: fields = ['id', 'code', 'sg_status_list'] filters = [ ['entity','is',{'type':'Shot','id':sh['id']}] , ['content','is', 'Composite' ],['sg_status_list', 'is_not','na'],['sg_status_list', 'is_not','wtg']] taskID = sg.find_one('Task',filters,fields) task.setMessage(sh['code']) if taskID: sg.update('Task', taskID['id'], {'sg_status_list': 'cmpt'}) #if notes, change to problem for n in sh['open_notes']: id= n['id'] fields = ['sg_status_list','tasks','name'] filters = [['id', 'is',id]] note = sg.find_one('Note',filters,fields) for t in note['tasks']: if 'Composite' in t['name']: fields = ['id', 'code', 'sg_status_list'] filters = [ ['entity','is',{'type':'Shot','id':sh['id']}] , ['content','is', 'Composite' ]] taskID = sg.find_one('Task',filters,fields) sg.update('Task', taskID['id'], {'sg_status_list': 'fkd'}) del(task)
def copy_files_node(node): source=node['source_file'].getValue() destination=node['destination'].getValue() print 'COPY %s to %s' %(source, destination) if node['sequence'].getValue(): base = os.path.basename(source).split('.')[0] + "*" + os.path.splitext(source)[1] fileList = glob.glob(os.path.join(os.path.dirname(source), base)) else: fileList = [source] print fileList dest = destination if not os.path.exists(dest): os.makedirs(dest) task = nuke.ProgressTask("Copying Files") fileCount = len(fileList) for count, imgfile in enumerate(fileList): task.setMessage("copying file: %d of %d" % (count, fileCount)) task.setProgress(int(100 * (count / float(fileCount)))) shutil.copy(imgfile, dest)
def copyRenderToShot(): s = nuke.selectedNodes() for node in s: if node.Class() == "Write": file = node['file'].getValue() base = os.path.basename(file).split( '.')[0] + "*" + os.path.splitext(file)[1] fileList = glob.glob(os.path.join(os.path.dirname(file), base)) dest = os.path.join(getRenderDir(), os.path.basename(file).split('.')[0]) if not os.path.exists(dest): os.mkdir(dest) task = nuke.ProgressTask("Copying Files") for count, imgfile in enumerate(fileList): shutil.copy(imgfile, dest) task.setProgress(int(count / float(len(fileList)) * 100)) node['file'].setValue(os.path.join(dest, os.path.basename(file))) else: nuke.message( "Selected write nodes will copy to the delivery folder for the shot" )
def copyLocal(self, *args): self.getSelectionDependents() task = nuke.ProgressTask("getRenders") for d in self.dependents: rootPath = self.convertTreePathToServerPath( self.getTreePathFromItem(d)) aovData = self.publishData[self.getTreePathFromItem(d)] for i, aov in enumerate(aovData): path, frameRange = aov.split(" ") start, end = frameRange.split("-") serverPath = rootPath + "/exr/" + path localPath = serverPath.replace("P:", self.localDrive) dirPath = os.path.dirname(localPath) task.setMessage('processing %s' % path) task.setProgress(int(float(i) / len(aovData) * 100)) try: os.makedirs(dirPath) except: pass incr = int(self.frameNthSize.text()) for i in range(int(start), int(end))[::incr]: serverPath = rootPath + "/exr/" + path localPath = serverPath.replace("P:", self.localDrive) serverFramePath = serverPath.replace( "%04d", str(i).zfill(4)) localFramePath = localPath.replace("%04d", str(i).zfill(4)) print serverFramePath, localFramePath if os.path.exists(serverFramePath ) and not os.path.exists(localFramePath): print "copying", serverFramePath shutil.copy(serverFramePath, localFramePath) del (task)
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)
def movieProgress(self, finalMovCmd): task = nuke.ProgressTask("Movie Conversion") task.setMessage("Encoding files") task.setProgress(0) p = subprocess.Popen(finalMovCmd, shell=True, bufsize=64, stderr=subprocess.PIPE) self.updateProgressBar(p, task)
def StickIT(): #Define Variables frameForRef = int(nuke.thisNode().knob("RefrenceFrameInput").value()) StartFrame = int(nuke.thisNode().knob("InputFrom").value()) EndFrame = int(nuke.thisNode().knob("InputTo").value()) if frameForRef > EndFrame or frameForRef < StartFrame: nuke.message("You must set a reference frame inside the active range") else: taskB = nuke.ProgressTask('Calculating Solve, please wait...') NodePin = nuke.toNode("si_sw") #change this to your tracker node! #Grap data from the camera tracker and convert it into a format we can use. PointData = GrabListData() #03: Get a set of reference points. This is the points we want to move. RefPointList = GetAnimtionList(PointData[0], PointData[1], frameForRef, False, True) #04: Go through all of the frames and triangulate best points to move the refpoints with. start = time.clock() finalAnimation = [] for item in RefPointList: zx = item[0][1] zy = item[0][2] tempAnimation = [] tempAnimation.append([frameForRef, item[0][1], item[0][2] ]) #Add a keyframe on the reference frame #Now start from the ref frame and move back for frame in reversed(range(StartFrame, frameForRef)): newOffset = GetNearestPoints( item[0], GetAnimtionList(PointData[0], PointData[1], frame, True)) tempAnimation.append([ frame, item[0][1] + newOffset[0], item[0][2] + newOffset[1] ]) item[0][1] = item[0][1] + newOffset[0] item[0][2] = item[0][2] + newOffset[1] #Now start from the ref frame and move forward for frame in range(frameForRef, EndFrame): newOffset = GetNearestPoints([0, zx, zy], GetAnimtionList( PointData[0], PointData[1], frame)) tempAnimation.append( [frame + 1, zx + newOffset[0], zy + newOffset[1]]) zx = zx + newOffset[0] zy = zy + newOffset[1] #Now add the animation created to the animation list finalAnimation.append(sorted(tempAnimation)) #print finalAnimation end = time.clock() print "%.2gs" % (end - start) CreateWarpPinPair(NodePin, finalAnimation, frameForRef) del (taskB)
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)
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()
def animatedSnapFunc(nodeToSnap, vertexSelection, knobsToAnimate, knobsToVerify, minVertices=1, snapFunc=s3d.translateToPointsVerified): '''A wrapper to call the relevant snap functions within a framerange loop''' temp = None try: s3d.verifyNodeToSnap(nodeToSnap, knobsToVerify) # verify vertex selection once before the loop s3d.verifyVertexSelection(vertexSelection, minVertices) # now ask for a framerange frames = getFrameRange() if not frames: return # Exit eary if cancelled or empty framerange # Add a CurveTool for the forced-evaluation hack temp = nuke.nodes.CurveTool() # Set the anim flag on knobs for knob in [nodeToSnap[x] for x in knobsToAnimate]: # reset animated status if knob.isAnimated(): knob.clearAnimated() knob.setAnimated() # Set up Progress Task task = nuke.ProgressTask("animatedSnap3D") task.setMessage("Matching position of %s to selected vertices" % nodeToSnap.name()) # Loop through the framerange for frame in frames: if task.isCancelled(): break # Execute the CurveTool node to force evaluation of the tree nuke.execute(temp, frame, frame) # this is repetitive, but the vertex selection needs to be computed again # in order to get the vertices at the right context (time) vertexSelection = s3d.getSelection() # this is also repetitive. Selection should be already verified # but checking again in case topology has changed between frames s3d.verifyVertexSelection(vertexSelection, minVertices) # Call the passed snap function from the nukescripts.snap3d module snapFunc(nodeToSnap, vertexSelection) except ValueError, e: nuke.message(str(e))
def reduce_selected_brush_stroke(withDefaults=False): #------------------------ # SETTINGS #------------------------ epsilon = 10 #Your threshold frame = nuke.frame() #The frame to reference... rpNode = nuke.selectedNode() #The node to process makeCopy = False #Since nuke.Undo is broken, we want to make a backup if not withDefaults: #Make a little fancy menu p = nuke.Panel('Reduce Brush Strokes :: Settings') p.addSingleLineInput('Epsilon', '10') p.addBooleanCheckBox('Make Copy of Node?', False) ret = p.show() epsilon = float(p.value('Epsilon')) makeCopy = p.value('Make Copy') if makeCopy: #Make a copy of the selected node. originalNode = rpNode nuke.nodeCopy('%clipboard%') nuke.nodePaste('%clipboard%') rpNode = nuke.selectedNode() rpNode.setInput(0,originalNode.input(0)) solver = DPAlgorithm() #The algorithm object cKnob= rpNode['curves'] selectedShapes = cKnob.getSelected() task = nuke.ProgressTask('Reducing Roto...') task.setProgress(0) for i,shape in enumerate(selectedShapes) : thisShape = [] alen = float(len(selectedShapes)) #Used to calculate progress try: for x,p in enumerate(shape) : #Get a list of all the points in the roto shape tempPosition = p.getPosition(frame) thisShape.append([tempPosition[0],tempPosition[1],x]) reducedShape = solver.rdp(thisShape,epsilon) #Magic happens here.. reduce the shape for x,p in reversed( list( enumerate( shape) ) ) : #Go through all of the points in reversed order and remove the ones that are not in the reduced list slen=float(len(shape)) #Used to calculate progress tempPosition = p.getPosition(frame) #LAZY!!! if not [tempPosition[0],tempPosition[1],x] in reducedShape : shape.remove(x) #Damn, this thing is slow! (could be threaded!?) task.setProgress(int(((float(i)/alen)+((float(slen-x)/slen)/alen))*100.0)) #Update the progress bar task.setMessage("Processing point %s in brush %s (yes, this is slow)" %(x,i)) except: pass #Not a supported item task.setProgress(100)
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)))
def execute_preset(node, startNode='Input1'): ''' takes the export gizmo and renders/runs all the nodes''' def build_list(node): '''recurse through the node tree and build the list of exports that need to be run''' for n in node.dependent(nuke.INPUTS): if 'Write' == n.Class() or 'Pipeline' in n.name(): #if not node['disable'].getValue(): execute_list.append(n) build_list(n) def execute_node(node): if not node['disable'].getValue(): if node.Class() == 'Write': nuke.execute(node, int(node['first'].getValue()), int(node['last'].getValue())) else: try: node['execute'].execute() except KeyError as e: nuke.message('Error: %s' % e) start = node.node(startNode) execute_list = [] maxtries = 1 print "Build Execute list" while len(execute_list) == 0 and maxtries < 5: build_list(start) maxtries += 1 print "Execute List took %d tries" % maxtries task = nuke.ProgressTask("Running: %s Preset" % node.name()) print execute_list task.setProgress(0) taskCount = len(execute_list) for count, n in enumerate(execute_list): print n.name() task.setMessage(n['label'].getValue()) try: execute_node(n) except: task.setProgress(100) nuke.message( 'ERROR: DELIVERY FAILED, check error log for any info') return task.setProgress(int(100 * (count / float(taskCount)))) task.setProgress(100)
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)
def start(self): '''start copying files''' logger.debug('thread limit is: %s' % self.threadLimit) self.start = time.time() self.mainTask = nuke.ProgressTask('LOCALISING %s files' % self.totalFileCount) self.__updateMainTaskMessage() for seqName, fileList in self.fileDict.iteritems(): thread = threading.Thread(name=seqName, target=self.copyFiles, args=(seqName, fileList)) thread.start()
def __init__(self, folder = None, recursive = True, message = True): #set root folder if folder == None: self.root = preferencesNode.knob('hotboxLocation').value() else: self.root = folder #make sure the root ends with '/' while self.root[-1] != '/': self.root += '/' #compose list of folders if folder == None: self.dirList = ['%sAll/'%self.root] else: self.dirList = [] if recursive: self.indexFolders(self.root, folder) else: self.dirList = [self.root] #append every filename with a 'tmp' so no files will be overwritten. for i in self.dirList: self.tempifyFolder(i) #reset dirlist if folder == None: self.dirList = ['%sAll/'%self.root] else: self.dirList = [] if recursive: self.indexFolders(self.root, folder) else: self.dirList = [self.root] #give every file its proper name repairProgress = 100.0 / len(self.dirList) for index, i in enumerate(self.dirList): repairProgressBar = nuke.ProgressTask('Repairing W_hotbox...') repairProgressBar.setProgress(int(index * repairProgress)) repairProgressBar.setMessage(i) self.repairFolder(i) if message: nuke.message('Reparation succesfully')
def createMovie(self): frameRate = self.frameDrop.currentText() self.movieWidget.setFrameRate(frameRate) self.createButton.setDisabled(True) inputFile = self.inputWidget.getFilePath() outputFile = str(self.outputWidget.getFilePath()) slugChoice = self.slugBox.checkState() if 'Select' in inputFile or 'Select' in outputFile or inputFile == '' or outputFile == '': nuke.message("Please select input and output folder") return inputFolder = os.path.dirname(str(inputFile)) imageExt = str(inputFile).split('.')[-1] if not outputFile.endswith('.mov'): outputFile = '%s.mov' % outputFile shotName, firstFrame, lastFrame, date, firstFrameStr = utils.getShotInfo( inputFolder, imageExt) self.movieWidget.setFrameCount(firstFrame, lastFrame) if slugChoice == 2: tmpDir = '%s/tmp' % os.environ['TEMP'] if not os.path.exists(tmpDir): os.mkdir(tmpDir) task = nuke.ProgressTask("Slug Creation") task.setMessage("Creating slug files") slugResult = utils.generateSlugImages(tmpDir, self.slugTextBox.text(), firstFrame, lastFrame, date, firstFrameStr, task) if slugResult != 0: nuke.message("Error while creating slug images!") self.createButton.setEnabled(True) return slugMovResult = utils.generateSlugMovie(tmpDir, firstFrame, firstFrameStr, frameRate) if slugMovResult != 0: nuke.message("Error while creating slug movie!") self.createButton.setEnabled(True) return finalMovCmd = utils.generateFileMovie(inputFolder, tmpDir, outputFile, firstFrame, shotName, imageExt, lastFrame, firstFrameStr, frameRate) else: finalMovCmd = utils.generateFileMovieNoSlug( inputFolder, outputFile, firstFrame, shotName, imageExt, lastFrame, firstFrameStr, frameRate) threading.Thread(None, self.movieProgress, args=[finalMovCmd]).start()
def package_execute_threaded(s_nuke_script_path): progress_bar = nuke.ProgressTask("Packaging Script") progress_bar.setMessage("Initializing...") progress_bar.setProgress(0) s_nuke_exe_path = nuke.env['ExecutablePath'] # package_script.py has NOT been cleaned of show-specific code and hard-coded paths. # To-Do as of 2016-10-28. s_pyscript = os.path.join(os.path.dirname(os.environ['IH_SHOW_ROOT']), "SHARED", "lib", "nuke", "nuke_pipeline", "package_script.py") s_cmd = "%s -i -V 2 -t %s %s" % (s_nuke_exe_path, s_pyscript, s_nuke_script_path) s_err_ar = [] f_progress = 0.0 print "INFO: Beginning: %s" % s_cmd proc = subprocess.Popen(s_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) while proc.poll() is None: try: s_out = proc.stdout.readline() print s_out.rstrip() s_err_ar.append(s_out.rstrip()) if not s_out.find("INFO: copying file") == -1: s_line_ar = s_out.split(" ") (f_frame_cur, f_frame_tot, f_source_cur, f_source_tot) = (float(s_line_ar[3]), float(s_line_ar[5]), float(s_line_ar[8]), float(s_line_ar[10])) f_progress = ((f_frame_cur / f_frame_tot) * (1 / f_source_tot)) + ( (f_source_cur - 1) / f_source_tot) progress_bar.setMessage("Copying: %s" % s_line_ar[-1]) progress_bar.setProgress(int(f_progress * 100)) except IOError: print "IOError Caught!" var = traceback.format_exc() print var if proc.returncode != 0: s_errmsg = "" s_err = '\n'.join(s_err_ar) if s_err.find("FOUNDRY LICENSE ERROR REPORT") != -1: s_errmsg = "Unable to obtain a license for Nuke! Package execution fails, will not proceed!" else: s_errmsg = "An unknown error has occurred. Please check the STDERR log above for more information." nuke.critical(s_errmsg) else: print "INFO: Successfully completed script packaging."
def paintPoints(): ''' Rather experimental but kinda fun. This projects sleected 3D points through a camera ito screen space and draws a dot for each using a paint stroke. ''' # GET THE GEO NODE FROM THE CURRENTLY ACTIVE VIEWER geoNode = nuke.activeViewer().node() # WE EXPECT A CAMERA TO BE SELECTED camera = nuke.selectedNode() if not camera.Class() in ('Camera', 'Camera2'): nuke.message('Please select a camera node first') return # COLLECT ALL OBJECTS IN THE CURRENT GEO KNOB. QUIT IFNONE WERE FOUND geoKnob = geoNode['geo'] objs = geoKnob.getGeometry() if not objs: nuke.message('No geometry found in %s' % geoNode.name()) pts = [] for o in objs: # CYCLE THROUGH ALL OBJECTS objTransform = o.transform() for p in o.points(): # CYCLE THROUGH ALL POINTS OF CURRENT OBJECT worldP = objTransform * nuke.math.Vector4(p.x, p.y, p.z, 1) pts.append([worldP.x, worldP.y, worldP.z]) # CREATE THE NODE THAT WILL HOLD THE PAINT STROKES curvesKnob = nuke.createNode('RotoPaint')['curves'] # PREP THE TASK BAR task = nuke.ProgressTask('painting points') for i, pt in enumerate(pts): if task.isCancelled(): break task.setMessage('painting point %s' % i) # CREATE A NEW STROKE stroke = nuke.rotopaint.Stroke(curvesKnob) # PROJECT THE POINT TO SCREEN SPACE pos = nukescripts.snap3d.projectPoint(camera, pt) # CREATE ANE CONTROL POINT FOR ctrlPoint = nuke.rotopaint.AnimControlPoint(pos) # ASSIGN IT TO THE STROKE stroke.append(ctrlPoint) # ASSIGN TH E STROKE TO THE ROOT LAYER curvesKnob.rootLayer.append(stroke) # UPDARE PROGRESS BAR task.setProgress(int(float(i) / len(pts) * 100))
def show_dialog(app): """ Show the main dialog ui :param app: The parent App """ # defer imports so that the app works gracefully in batch modes from .dialog import AppDialog display_name = sgtk.platform.current_bundle().get_setting("display_name") #print "logger item: " #print sgtk.custom_debug_handler #store publish logs alongside other phosphene logs, enable bug submit logger = sgtk.platform.get_logger(__name__) #try: # #from .Debug import DebugHandler # #phospheneDebugHandler=DebugHandler() # phospheneDebugHandler=sgtk.custom_debug_handler # print "hooking phosphene logs into "+str(logger) # logger.addHandler(phospheneDebugHandler) #except: # print format_exc() #start a progress bar if we're in nuke if app.engine.instance_name == 'tk-nuke': import nuke progressBar = nuke.ProgressTask('Publishing ' + basename(nuke.Root().name())) sleep(.25) logger.info('Phosphene publish loaded') if app.pre_publish_hook.validate(): # start ui if app.modal: app.engine.show_modal(display_name, app, AppDialog) else: app.engine.show_dialog(display_name, app, AppDialog) else: app.logger.debug("%s validate returned False -- abort publish." % app.pre_publish_hook.__class__.__name__) if app.engine.instance_name == 'tk-nuke': try: del (progressBar) except: pass
def unload_manifest(node): source_node = None if node.Class() == "Cryptomatte": source_node = node.input(0) if not source_node: nuke.message('Cryptomatte is not plugged into anything') return else: source_node = node cinfo = CryptomatteInfo(node) if not cinfo.is_valid(): nuke.message( "Gizmo's cryptomatte selection is not valid or no cryptomattes are available. " ) return names_to_IDs = cinfo.parse_manifest() if not names_to_IDs: nuke.message('No Cryptomatte manifest was found in the input. ') return new_keyers = [] if nuke.ask( 'There are %s named mattes in the manifest, are you sure you want to create keyer nodes for all of them?' % len(names_to_IDs)): with nuke.root(): dot = nuke.nodes.Dot() dot.setInput(0, source_node) progress = 0 task = nuke.ProgressTask("Unloading Manifest") for name, metadata_ID in names_to_IDs.iteritems(): if task.isCancelled(): break task.setMessage("Creating Cryptomatte Keyer for %s" % name) task.setProgress( int(float(progress) / float(len(names_to_IDs)) * 100)) keyer = nuke.nodes.Cryptomatte(name="ck_%s" % name, matteList=name, matteOnly=True) keyer.setInput(0, dot) _update_cryptomatte_gizmo(keyer, cinfo) new_keyers.append(keyer) progress = progress + 1 return new_keyers
def _setColors(nodeInfos, formatWeight, analyzeBBox, analyzeLayers, bboxThreshold, layerThreshold): """ Change colors of the node based on the number of layers and size of the bbox Args: nodeInfos (dict of dicts) : bbox size and the number of layers per nuke node formatWeight (int) : number of pixels in Nuke;s root format analyzeBBox (bool) : perform bbox check analyzeLayers (bool) : perform layer check bboxThreshold (float) : bbox limit layerThreshold (int) : layer number limit """ task = nuke.ProgressTask('Setting colors...') increment = 100.0 / len(nodeInfos) progress = 0 for node, nodeInfo, in nodeInfos.iteritems(): progress += 1 task.setProgress(int(progress * increment)) task.setMessage(node.name()) if task.isCancelled(): _revertColors(nodeInfos.keys()) brightness = 1 hue = 1 red = 1 green = 1 blue = 0 if analyzeLayers: brightness = min( 1, (1 - min(1, nodeInfo['layers'] / float(layerThreshold))) + 0.3) if analyzeBBox: hue = min(1, nodeInfo['bbox'] / formatWeight / bboxThreshold) green = 1 - hue red = hue * brightness green *= brightness colorHex = int( '%02x%02x%02x%02x' % (red * 255, green * 255, blue * 255, 1), 16) node['tile_color'].setValue(colorHex) #checkEfficiency.checkEfficiency()