def _nuke_execute(self, operation, file_path, context, parent_action, file_version, read_only, **kwargs): if file_path: file_path = file_path.replace("/", os.path.sep) if operation == "current_path": # return the current script path return nuke.root().name().replace("/", os.path.sep) elif operation == "open": # open the specified script nuke.scriptOpen(file_path) # reset any write node render paths: if self._reset_write_node_render_paths(): # something changed so make sure to save the script again: nuke.scriptSave() elif operation == "save": # save the current script: nuke.scriptSave() elif operation == "save_as": old_path = nuke.root()["name"].value() try: # rename script: nuke.root()["name"].setValue(file_path) # reset all write nodes: self._reset_write_node_render_paths() # save script: nuke.scriptSaveAs(file_path, -1) except Exception, e: # something went wrong so reset to old path: nuke.root()["name"].setValue(old_path) raise TankError("Failed to save scene %s", e)
def advancedSubmission(): nuke.scriptSave() DeadlineNukeClient.main() createArtifact() if nuke.ask('Do you want to version up your script?'): incrementalSave() return
def restartNuke(): if nuke.ask('Are you sure you want to restart Nuke?'): scriptName = nuke.root().knob('name').getValue() subprocess_options = {"shell": True} separate_terminal_options = { "close_fds": True, "preexec_fn": os.setsid } if nuke.env['nukex'] == True: session = '--nukex' else: session = '--nuke' if 'REZ_VOLT_SESSION_ROOT' in os.environ: subprocess_options.update(separate_terminal_options) if os.path.isfile(scriptName): nuke.scriptSave() launch_cmd = '{} {} {}'.format(sys.executable, session, scriptName) subprocess.Popen(launch_cmd, **subprocess_options) nuke.modified(False) nuke.scriptExit() else: nuke.scriptNew('') nuke.modified(False) nuke.scriptExit()
def run(found_file): #check if scene is modified if nuke.Root().modified() == True: #prompt user to save if nuke.ask('Unsaved script\n\nWould you like to save?'): if nuke.Root().name() == 'Root': #run up the save_as module as this script hasnt been saved yet, then clear and open import jnuke.pipeline.save_as jnuke.pipeline.save_as.run() nuke.scriptClear() nuke.scriptOpen(found_file) else: #save the script, clear and open selected script nuke.scriptSave("") nuke.scriptClear() nuke.scriptOpen(found_file) else: #they dont want to save, so just clear the script and open the selected script nuke.scriptClear() nuke.scriptOpen(found_file) else: #not modified, simply clear and open nuke.scriptClear() nuke.scriptOpen(found_file)
def makeBackup(): ''' make backup of script ''' #get script name and make folder if not exist script = nuke.root().name() scriptName = (nuke.root().name().split("/")[-1]).replace(".nk", "") operation = blackboxHelper.getBackupSettings("@operation", backupSettings) backupPath = blackboxHelper.getBackupSettings("@backupPath", backupSettings) numberOfBackups = int( blackboxHelper.getBackupSettings("@numberOfBackups", backupSettings)) if backupMinute == True: t = time.strftime("%y%m%d-%H%M") else: t = time.strftime("%y%m%d-%H%M%S") # global dir if operation == "0.0": if not os.path.isdir(backupPath + "/" + scriptName): os.makedirs(backupPath + "/" + scriptName) try: nuke.removeOnScriptSave(makeBackup) nuke.scriptSave(backupPath + "/" + scriptName + "/bckp_" + t + "_" + scriptName + ".nk") nuke.addOnScriptSave(makeBackup) except Exception, e: nuke.message("couldn't write a backup file") deleteOlderBackupVersions(backupPath + "/" + scriptName)
def execute(self, operation, file_path, **kwargs): """ Main hook entry point :operation: String Scene operation to perform :file_path: String File path to use if the operation requires it (e.g. open) :returns: Depends on operation: 'current_path' - Return the current scene file path as a String all others - None """ if file_path: file_path = file_path.replace("/", os.path.sep) if operation == "current_path": # return the current script path return nuke.root().name().replace("/", os.path.sep) elif operation == "open": # open the specified script into the current window if nuke.root().modified(): raise TankError("Script is modified!") nuke.scriptClear() nuke.scriptOpen(file_path) elif operation == "save": # save the current script: nuke.scriptSave()
def process(self, context): # capture selection state with maintained_selection(): active_node = [ node for inst in context[:] for node in inst[:] if "ak:family" in node.knobs() ] if active_node: self.log.info(active_node) active_node = active_node[0] self.log.info(active_node) active_node['selected'].setValue(True) # select only instance render node output_node = nuke.createNode("Output") # deselect all and select the original selection output_node['selected'].setValue(False) # save script nuke.scriptSave() # add node to instance node list context.data["outputNode"] = output_node
def makeBackup(): ''' make backup of script ''' #get script name and make folder if not exist script = nuke.root().name() scriptName = (nuke.root().name().split("/")[-1]).replace(".nk","") operation=blackboxHelper.getBackupSettings("@operation", backupSettings) backupPath=blackboxHelper.getBackupSettings("@backupPath", backupSettings) numberOfBackups=int(blackboxHelper.getBackupSettings("@numberOfBackups", backupSettings)) if backupMinute == True: t = time.strftime("%y%m%d-%H%M") else: t = time.strftime("%y%m%d-%H%M%S") # global dir if operation=="0.0": if not os.path.isdir(backupPath+"/"+scriptName): os.makedirs(backupPath+"/"+scriptName) try: nuke.removeOnScriptSave(makeBackup) nuke.scriptSave(backupPath+"/"+scriptName+"/bckp_"+t+"_"+scriptName+".nk") nuke.addOnScriptSave(makeBackup) except Exception, e: nuke.message("couldn't write a backup file") deleteOlderBackupVersions(backupPath+"/"+scriptName)
def BatScriptRenderFull(): # Save Script nuke.scriptSave() # Variables of Script nukescript = nuke.value("root.name") start = nuke.knob("first_frame") end = nuke.knob("last_frame") path = nukescript + ".bat" # Cmd Message nuke.tprint("\nBatScriptRender\nSave Script " + nukescript) # Bat File Panel swt = ['-x', '-X'] nfr = ['""', ',2', ',5', ',10', ',15', ',20'] myPanel = nuke.Panel("BatScriptRender - Parameters", 338) myPanel.addSingleLineInput("nuke version: ", "nuke5.1") myPanel.addEnumerationPulldown("switches: ", ' '.join(swt)) myPanel.addSingleLineInput("node: ", "") myPanel.addSingleLineInput("script: ", nukescript) myPanel.addSingleLineInput("start frame: ", start) myPanel.addSingleLineInput("end frame: ", end) myPanel.addEnumerationPulldown("every n frame: ", ' '.join(nfr)) myPanel.addSingleLineInput("file path: ", path) myPanel.addButton("Quit") myPanel.addButton("Create") myPanel.addButton("Execute") result = myPanel.show() # Add Button's action & Cmd Message if result == 0: nuke.tprint("Bat File don't Create") elif result == 1: # Create Bat File curVersion = myPanel.value("nuke version: ") curSwitches = myPanel.value("switches: ") curNode = myPanel.value("node: ") curScript = myPanel.value("script: ") curStart = myPanel.value("start frame: ") curEnd = myPanel.value("end frame: ") curEvery = myPanel.value("every n frame: ") cmdLine = curVersion + " " + curSwitches + " " + curNode + " " + '"' + curScript + '"' + " " + curStart + "," + curEnd + curEvery cmdFile = myPanel.value("file path: ") file = open(cmdFile, 'w') file.write(cmdLine) file.close() nuke.tprint("Create Bat File " + cmdFile) elif result == 2: # Execute Bat File curVersion = myPanel.value("nuke version: ") curSwitches = myPanel.value("switches: ") curNode = myPanel.value("node: ") curScript = myPanel.value("script: ") curStart = myPanel.value("start frame: ") curEnd = myPanel.value("end frame: ") curEvery = myPanel.value("every n frame: ") cmdLine = curVersion + " " + curSwitches + " " + curNode + " " + '"' + curScript + '"' + " " + curStart + "," + curEnd + curEvery cmdFile = myPanel.value("file path: ") file = open(cmdFile, 'w') file.write(cmdLine) file.close() os.startfile(cmdFile) nuke.tprint("Execute Bat File " + cmdFile)
def createNukeFile(seq = 's0060',shName=True,outFile = '/tmp/tmp.tif',task = 'compo_comp'): nbShots = len(findShotsInSequence(seq,False)) intNb = nbShots/5 floatNb = nbShots/5.0 if floatNb-intNb > 0: intNb += 1 sequenceGroupNode = sequenceGroup.create() sequenceGroupNode['sequence'].setValue(seq) sequenceGroupNode['task'].setValue(task) sequenceGroupNode['outputMode'].setValue('contactSheet') sequenceGroupNode['Rebuild'].execute() # a.knob('Rebuild').execute() sequenceGroupNode['RowCol'].setValue([intNb, 5]) sequenceGroupNode['Resolution'].setValue([5*2048,intNb*858]) if shName: sequenceGroupNode['showName'].setValue(True) else: sequenceGroupNode['showName'].setValue(False) colorConvertNode = nuke.nodes.OCIOColorSpace(in_colorspace="Linear", out_colorspace="Lut") #colorConvertNode = nuke.nodes.OCIOColorSpace( out_colorspace="Lut") colorConvertNode.setInput(0,sequenceGroupNode) writeNode = nuke.nodes.Write(name = seq + "WriteLutBurn", colorspace = "linear", file_type = "tiff",file =outFile+'/'+seq+'.tif') writeNode['datatype'].setValue('16 bit') #writeNode['views'].setValue('left left') writeNode.setInput(0,colorConvertNode) nuke.scriptSave('/tmp/tmp.nk') print 'done' nuke.execute(writeNode, 1, 1)
def nk_multithreadedRender(): """ Multithreaded Render """ threads = nuke.env["threads"] - 2 c = nuke.getInput("Number of threads (default %i)" % threads) if c: threads = int(c) THREADCOUNT = threads nuke.scriptSave() renderNode = nuke.selectedNode() use_limit = renderNode["use_limit"].value() first = renderNode["first"].value() if use_limit else nuke.root().firstFrame() last = renderNode["last"].value() if use_limit else nuke.root().lastFrame() frames = [i for i in range(first, last + 1)] threads = [[] for i in range(0, THREADCOUNT)] [threads[i % THREADCOUNT].append(frame) for (i, frame) in enumerate(frames)] THREAD_FRAMES = {} def render(frameList): _maxCache = str(max(nuke.memory("max_usage") / 1097152, 16) * 4) + "M" try: t = nuke.executeBackgroundNuke( nuke.EXE_PATH, [renderNode], nuke.FrameRanges(frameList), nuke.views(), {"maxThreads": 1, "maxCache": _maxCache}, ) THREAD_FRAMES[t] = frameList except Exception as e: print e [render(frameList) for frameList in threads]
def BlackSailRender(): nuke.scriptSave() try: g = nuke.selectedNode() f = nuke.allNodes("Write") + nuke.allNodes("DeepWrite") for a in f: sel = a['selected'].value() names = "" if sel == 1: a['disable'].setValue(0) name = a['name'].value() names = names + name + "\n" #nuke.toNode("Review")['senttorender'].setValue(names) else: a['disable'].setValue(1) BlackSailSubmit.BlackSailSubmit() except: BlackSailSubmit.BlackSailSubmit() try: n = nuke.selectedNodes() for n in n: x = n['xpos'].value() y = n['ypos'].value() b = nuke.allNodes("BackdropNode") for ba in b: xb = ba['xpos'].value() yb = ba['ypos'].value() if xb < x and yb < y and xb > x - 300 and yb > y - 400 and ba[ 'label'].value() == "Precomp": ba['tile_color'].setValue(52479) except: BlackSailSubmit.BlackSailSubmit()
def prep(): nuke.scriptSave() node = nuke.thisNode() ffpy = __file__ ffpy = ffpy.replace('pyc', 'py') node_framerange = node['framerange'].getValue() nk_cmd = "{0} -t {1} {2} --write {3} --output {4}".format( nuke.EXE_PATH, ffpy, nuke.root().knob("name").value(), node.fullName(), node['file'].getValue()) print("RENDER COMMAND:\n\t{0}".format(nk_cmd)) if _platform == "win": nuke.message("Windows not supported.") return if _platform == "osx": cmd = '''osascript 2>/dev/null <<EOF tell application "Terminal" if not (exists window 1) then reopen activate do script "{0}" end tell EOF'''.format(nk_cmd) elif _platform == "linux": # cmd = 'xterm -e "bash {0}"'.format(nk_cmd) cmd = 'gnome-terminal -e "bash -c \\"{0}; exec bash\\""'.format(nk_cmd) #cmd = 'gnome-terminal -e "bash -c \\"{0}\\""'.format(nk_cmd) subprocess.Popen(cmd, shell=True)
def render( self ): frame_range = self.panel.value("Frame Range") thread_count = self.panel.value("Num Threads") chunk_size = self.panel.value("Frames per Chunk") force_fullsize = self.panel.value("Force Fullsize") quiet_mode = self.panel.value("Quiet Mode") render_name = self.panel.value("Render Name") if chunk_size == "None": chunk_size = 0 username = getpass.getuser() timestamp = int( time.time() ) if render_name is None: render_name = "Nuke Render for %s" % username filename = "/tmp/nuke-%s-%s-%s.nk" % ( frame_range, username, timestamp ) try: nuke.scriptSave( filename ) print filename except: nuke.message("ERR-001 Unable to save spool file") nuke_args = { "type":"Nuke", "threads":thread_count, "fullsize":force_fullsize, "quiet":quiet_mode, "file":filename, "nodes":self.writeNodes} render_args = { "range":frame_range, "chunksize":chunk_size, "timestamp":timestamp, "name":render_name, "user":username,} print render_args print nuke_args rr = tractor.Render( render_args, nuke_args ) rr.build() rr.spool()
def run(self): result = nukescripts.PythonPanel.showModalDialog(self) if result: self.farm.parms['queue'] = str(self.queueKnob.value()) self.farm.parms['group'] = str(self.group_list.value()) self.farm.parms['start_frame'] = int(self.start_frame.getValue()) self.farm.parms['end_frame'] = int(self.end_frame.getValue()) self.farm.parms['frame_range_arg'] = ["-F %s-%sx%s", 'start_frame', 'end_frame', int(self.every_of_Knob.getValue())] self.farm.parms['target_list'] = self.write_name.value().split() # First Write node selected will be passed as output_picture varible to render manager # It is used mostly for debuging, previewing etc. write_node = self.farm.parms['target_list'][0] self.farm.parms['output_picture'] = str(nuke.root().node(write_node).knob("file").getEvaluatedValue()) self.farm.parms['job_on_hold'] = bool(self.hold_Knob.value()) self.farm.parms['priority'] = int(self.priorityKnob.value()) if self.email_Knob.value(): self.farm.parms['email_list'] = [utils.get_email_address()] self.farm.parms['email_opt'] = "eas" # Request slots exclusively: if self.requestSlots_Knob.value(): self.farm.parms['req_resources'] = 'procslots=%s' % int(self.slotsKnob.value()) nuke.scriptSave() print self.farm.render() return True return
def submitRender(self): filename = str(self.fileTextBox.text()) nuke.scriptSave() if filename.endswith('.autosave'): nuke.message('Cannot submit .autosave file for render! Please save and try again.') return if filename is '' or not os.path.exists(filename): nuke.message('Please select a valid file to render!') return fileDir, fname = os.path.split(filename) jobName = 'Nuke - %s' % fname renderer = self.jobWidget.getRenderer('Nuke') splitMode = self.jobWidget.getSplitMode() local = self.jobWidget.localCheckbox.isChecked() pool = self.jobWidget.getClientPools() if pool == 'Linux Farm': pool = '' slackUser = self.jobWidget.getSlackUser() rendererParams = self.getRendererParams() priority = self.jobWidget.getPriority() dependent = self.jobWidget.getDependentJob() cmd = '%s %s %s' % (renderer, rendererParams, filename) hq_server = self.jobWidget.getHQProxy() if local: newCmd = cmd.split(';')[-1] self.submitLocalRender(newCmd) nuke.message('Local render started. \nCommand: %s' % newCmd) else: jobIds = self.jobWidget.submitNoChunk(hq_server, jobName, cmd, priority, 0, pool, False, slackUser, dependent) nuke.message('Job Submission Successful. Job Ids = {0}'.format(jobIds))
def createThreads(frameStart, frameEnd, numThreads, writeNodes=None): nuke.scriptSave() if not writeNodes: writeNodes = getWriteNodes() # Create Folders for writeNode in writeNodes: try: createOutfolder(writeNode) except: pass os.environ["DCC"] = "nuke" os.environ["EXE"] = nuke.EXE_PATH os.environ["SCENE"] = nuke.root().name() os.environ["WRITENODES"] = str(writeNodes) os.environ["frameStart"] = str(frameStart) os.environ["frameEnd"] = str(frameEnd) os.environ["numThreads"] = str(numThreads) os.environ["FN_NUKE_DISABLE_GPU_ACCELERATION"] = str(1) # Start setEnvoriment() os.chdir(ROOT_RT) if sys.platform == "win32": print os.startfile("main.bat") else: opener ="open" if sys.platform == "darwin" else "xdg-open" subprocess.call(["bash", "main.sh"])
def create_snapshot_script(scriptPath=None, snapScriptName=None, upversion=None): """ Writes snapshot .nk script :param scriptPath: Path to the snapshot directory where .nk is stored :param snapScriptName: Absolute path to the .nk :param upversion: if True, minor version +1 (e.g v01.00 --> v01.01) """ try: tmpScriptPath = scriptPath if upversion: up_minor_version = int( scriptPath.split("/")[-1].split(".")[-2]) + 1 up_script_name = ".".join(tmpScriptPath.split("/")[-1].split(".")[:-2]) + "." \ + str(up_minor_version).zfill(2) + ".nk" tmpScriptPath = "/".join( tmpScriptPath.split("/")[:-1]) + "/" + up_script_name print "\n~ Writing script: " + str(snapScriptName) nuke.scriptSaveAs(str(snapScriptName)) os.chmod(snapScriptName, 0444) rootNode = nuke.toNode('root') rootNode.knob('name').setValue(tmpScriptPath) nuke.scriptSave() except: nuke.message("\n! Can't save the script, no snapshot created") raise BaseException
def do_backup(): """ Saves script into BACKUP_DIR folder after each save. If more then KEEP_VERSIONS files are present, deletes them Returns: None """ if not os.path.isdir(BACKUP_DIR): try: os.mkdir(BACKUP_DIR) except: nuke.message("Cannot create backup folder {}".format(BACKUP_DIR)) current_time_str = time.strftime("%Y%m%d_%H%M") backup_file_url = "{}/bckp_{}_{}.nknc".format(BACKUP_DIR, get_script_name(), current_time_str) try: import shutil nuke.removeOnScriptSave(do_backup) #remove call on save to limit recursion nuke.scriptSave(backup_file_url) nuke.addOnScriptSave(do_backup) delete_old_version() except IOError as e: nuke.message("Cannot write file {}, {}".format(backup_file_url,e))
def createArtifact(): nuke.scriptSave() script = nuke.value("root.name") filename, file_extension = os.path.splitext(script) artef = '{}_artifact.{}'.format(filename, file_extension) shutil.copyfile(script, artef)
def asd(): nuke.scriptSave() sp.call([ "shutdown", "-f", "-s", "-t", "30", "-c", "\"This is Autoshutdown for Nuke by Mohan pugaz\"" ]) return
def SCrendLinux(): import nuke panel = nuke.Panel("Priority") panel.addEnumerationPulldown("priority:", "medium low high") if panel.show(): priority = panel.value("priority:") try: f = nuke.allNodes() for a in f: if a.Class() == "comp_layers_core" or a.Class() == "Write": sel = a['selected'].value() if sel == 1: a['disable'].setValue(0) else: a['disable'].setValue(1) n = nuke.selectedNodes() for n in n: x = n['xpos'].value() y = n['ypos'].value() b = nuke.allNodes("BackdropNode") for ba in b: xb = ba['xpos'].value() yb = ba['ypos'].value() if xb < x and yb < y and xb > x - 300 and yb > y - 400 and ba[ 'label'].value() == "Precomp": ba['tile_color'].setValue(52479) ScanlineCoreSubmitRendering(priority, True, True) except: nuke.scriptSave() ScanlineCoreSubmitRendering(priority, True, True)
def dutchdevscripts(): global globalprogress global only_enabled_nodes global backup_project_dir global backup_root_dir global handlesize global plemke_version dpan = nuke.Panel( "Where to save?"); dpan.setWidth( 300 ); dpan.setTitle( "plemkes consolidator "+plemke_version ); dpan.addBooleanCheckBox( "backup enabled nodes only" , False ); dpan.addSingleLineInput( "Handle size" , str( handlesize ) ); dpan.addFilenameSearch( "Folder Path" , "Select backup folder" ); dpan.addSingleLineInput( "Backup name" , "NKBK_0001" ); if dpan.show() == 1 : backup_root_dir = dpan.value('Folder Path' ) backup_project_dir = dpan.value('Backup name' ) else: nuke.message('You have to select a backup directory ') return 0 only_enabled_nodes = dpan.value('backup enabled nodes only' ) handlesize = dpan.value('Handle size' ) prepare_current_project() backup_project_name = 'backup_'+ os.path.basename( project_file_name ) open_log_file( backup_project_name ) for items in nuke.allNodes(): bla = items.Class() read_node( bla , items ) #### for some strange reasons it skipped reads new_project_directory = backup_root_dir+'/'+backup_project_dir setting_proj_dir = nuke.root()['project_directory'] setting_proj_dir.setValue( new_project_directory ) out_name = backup_root_dir + '/'+ backup_project_dir + '/' + backup_project_name nuke.scriptSave( out_name ) node_dir = backup_root_dir + '/' + backup_project_dir + '/backup_info.txt' nuke.message( "Backup Done\nThere are "+ str( errorcnt ) + " Errors \nErrors are mostly missing source files\nOpen "+node_dir + " to check the errors ") del globalprogress return 1
def saveBackup(writeName): scriptLocation = nuke.root().name() scriptName = os.path.basename(scriptLocation) fileValue = nuke.toNode(writeName)['file'].getValue() renderPath = os.path.dirname(fileValue) nuke.scriptSave(renderPath + "/backup_" + scriptName)
def run(): if nuke.Root().name() == 'Root': import jnuke.pipeline.save_as jnuke.pipeline.save_as.run() else: nuke.scriptSave("") return nuke.Root().name()
def quickSubmit(*a): nuke.scriptSave() frame_range = '{0}-{1}'.format(nuke.root().firstFrame(), nuke.root().lastFrame()) scene_name = basename(nuke.root().name()) submit.singleNode(scene_name, nuke.root().name(), frame_range, '5000', '8', 'MASTER_WRITE')
def modify_nodes_path(self): nuke.scriptSaveAs('{}/{}'.format(self.dest_root, os.path.basename(nuke.Root().name())), 1) for node in self.nodes: modify_path(node) nuke.scriptSave() nuke.scriptClear() nuke.scriptOpen(self.original_nk)
def _do_nuke_publish(self, task, work_template, comment, thumbnail_path, sg_task, progress_cb): """ Publish the main Nuke script :param task: The primary task to publish :param work_template: The primary work template to use :param comment: The publish description/comment :param thumbnail_path: The path to the thumbnail to associate with the published file :param sg_task: The Shotgun task that this publish should be associated with :param progress_cb: A callback to use when reporting any progress to the UI :returns: The path to the file that has been published """ import nuke progress_cb(0.0, "Finding dependencies", task) dependencies = self._nuke_find_script_dependencies() # get scene path script_path = nuke.root().name().replace("/", os.path.sep) if script_path == "Root": script_path = "" script_path = os.path.abspath(script_path) if not work_template.validate(script_path): raise TankError( "File '%s' is not a valid work path, unable to publish!" % script_path) # use templates to convert to publish path: output = task["output"] fields = work_template.get_fields(script_path) fields["TankType"] = output["tank_type"] publish_template = output["publish_template"] publish_path = publish_template.apply_fields(fields) if os.path.exists(publish_path): raise TankError("The published file named '%s' already exists!" % publish_path) # save the scene: progress_cb(25.0, "Saving the script") self.parent.log_debug("Saving the Script...") nuke.scriptSave() # copy the file: progress_cb(50.0, "Copying the file") try: publish_folder = os.path.dirname(publish_path) self.parent.ensure_folder_exists(publish_folder) self.parent.log_debug("Copying %s --> %s..." % (script_path, publish_path)) self.parent.copy_file(script_path, publish_path, task) except Exception, e: raise TankError("Failed to copy file from %s to %s - %s" % (script_path, publish_path, e))
def saveInitNkScript(nkFile): folder = os.path.dirname(nkFile) if not os.path.exists(folder): os.makedirs(folder) baseNkFile = re.sub(r'(.*)(_v\d{1,5})(\..*$)', '\\1_v{}\\3'.format(baseVer), nkFile) nuke.scriptSave(baseNkFile) nuke.scriptSave(nkFile)
def createScript(self, nukeFile, fileOutNode): FlixNuke().clearScript() cbNode = nuke.createNode("CheckerBoard2") writeNode = nuke.createNode("Write") writeNode["name"].setValue(fileOutNode) writeNode["file"].setValue("/Users/brice/Desktop/testNuke/test.####.jpeg") writeNode.setInput(0, cbNode) nuke.scriptSave(nukeFile)
def file_save(self): """ Save the current file. If saving for first time take over and show custom dialog. """ if self.get_current_name() == 'Root': # Is current file unsaved? self.file_save_dialog() else: nuke.scriptSave()
def render_node(node): '''launch render''' out_path = node['file'].value() out_scriptcopy = node['tx_scriptcopy'].value() startFrame = int(nuke.Root()['first_frame'].value()) endFrame = int(nuke.Root()['last_frame'].value()) def _soloWrite(sel_node, all_enabled_write, mode='solo'): if mode == 'solo': for s in all_enabled_write: if s != sel_node.name(): print('node disabled---' + s) nuke.toNode(s)['disable'].setValue(True) elif mode == 'reverse': for s in all_enabled_write: nuke.toNode(s)['disable'].setValue(False) print('node enabled---' + s) askMessage = "Render Node: %s\nFile: %s\nFramerage: %s-%s\n" % ( node.name(), os.path.basename( node['file'].value()), startFrame, endFrame) c = nuke.ask(askMessage) if c: if not os.path.exists(os.path.dirname(out_path)): p = os.path.dirname(out_path) os.makedirs(p) print("out path created --- %s" % p) if not os.path.exists(os.path.dirname(out_scriptcopy)): s = os.path.dirname(out_scriptcopy) os.makedirs(s) print("out scriptcopy created --- %s" % s) all_enabled_write = [ n.name() for n in nuke.allNodes('Write') if n['disable'].value() == False ] _soloWrite(node, all_enabled_write, mode='solo') nuke.scriptSave() thisScript_path = nuke.scriptName() shutil.copy2(thisScript_path, out_scriptcopy) # nuke.render(node, startFrame, endFrame) exe = joinPath(nuke.EXE_PATH).replace('/', '\\') cmd_str = """start cmd /k "{exe}" -t -m 22 -xi {script} {start}-{end}""".format( exe=exe, node=node.name(), script=thisScript_path, start=startFrame, end=endFrame) subprocess.Popen(cmd_str, shell=True) _soloWrite(node, all_enabled_write, mode='reverse') else: print("user cancelled")
def buildCompScript(layerOrderFile, compScriptFile, isRunningFromScript): #imported nuke here as importing it outside was breaking argparse if not isRunningFromScript: import nuke #kept here if script is run from the comp itself if not os.path.isfile(layerOrderFile): print "Could not find layer_order.yml in " + shotDir sys.exit() if isRunningFromScript: # get nuke script to build nuke.scriptOpen(compScriptFile) # arrange templates in the given nuke script in vertical order templates = getTemplateList(layerOrderFile) for i, template in enumerate(templates): nuke.scriptReadFile(template) nuke.selectAll() node = nuke.selectedNodes("BackdropNode")[0] dotNode = nuke.selectedNodes('Dot')[0] if i > 0: bdNodes = node.getNodes() nodePrevX = node.xpos() nodePrevY = node.ypos() node.setYpos(previousNode.ypos() + 500) node.setXpos(previousNode.xpos()) for n in bdNodes: if n.ypos() > nodePrevY: n.setYpos(node.ypos() + (n.ypos() - nodePrevY)) else: n.setYpos(node.ypos() + (n.ypos() + nodePrevY)) if n.xpos() > nodePrevX: n.setXpos(node.xpos() + (n.xpos() - nodePrevX)) else: n.setXpos(node.xpos() + (n.xpos() + nodePrevX)) if i > 1: dotNode.setInput(0, previousDotNode.dependent()[0]) else: dotNode.setInput(0, previousDotNode) previousNode = node previousDotNode = dotNode if isRunningFromScript: #save nuke script nuke.scriptSave(compScriptFile) # remove temp files for template in templates: if "temp" in template: os.remove(template)
def ueSave(): root = nuke.root() if root.name() == "Root": ueSaveAs() return # if not ueNuke.ueScriptSanityCheck(): # return nuke.scriptSave(root.knob("name").value())
def _do_nuke_publish(self, task, work_template, comment, thumbnail_path, sg_task, progress_cb): """ Publish the main Nuke script :param task: The primary task to publish :param work_template: The primary work template to use :param comment: The publish description/comment :param thumbnail_path: The path to the thumbnail to associate with the published file :param sg_task: The Shotgun task that this publish should be associated with :param progress_cb: A callback to use when reporting any progress to the UI :returns: The path to the file that has been published """ import nuke progress_cb(0.0, "Finding dependencies", task) dependencies = self._nuke_find_script_dependencies() # get scene path script_path = nuke.root().name().replace("/", os.path.sep) if script_path == "Root": script_path = "" script_path = os.path.abspath(script_path) if not work_template.validate(script_path): raise TankError("File '%s' is not a valid work path, unable to publish!" % script_path) # use templates to convert to publish path: output = task["output"] fields = work_template.get_fields(script_path) fields["TankType"] = output["tank_type"] publish_template = output["publish_template"] publish_path = publish_template.apply_fields(fields) if os.path.exists(publish_path): raise TankError("The published file named '%s' already exists!" % publish_path) # save the scene: progress_cb(25.0, "Saving the script") self.parent.log_debug("Saving the Script...") nuke.scriptSave() # copy the file: progress_cb(50.0, "Copying the file") try: publish_folder = os.path.dirname(publish_path) self.parent.ensure_folder_exists(publish_folder) self.parent.log_debug("Copying %s --> %s..." % (script_path, publish_path)) self.parent.copy_file(script_path, publish_path, task) except Exception, e: raise TankError("Failed to copy file from %s to %s - %s" % (script_path, publish_path, e))
def main(): def change_file_knob_to_abs_path(node, knob_name): try: if not node[knob_name] == "": node[knob_name].setValue(get_abs_path(node[knob_name].value())) finally: return def make_collect_folder(): split = os.path.splitext(nuke.scriptName()) dst_path = os.path.join(nuke.script_directory(), split[0] + "_Collected") return make_folder(dst_path) # noinspection PyArgumentList def get_node_tuples_to_collect_by_all(): node_list = [] for dic in node_file_knob_dictionary: for node in nuke.allNodes(dic[0]): node_list.append((node, dic[1])) return node_list collect_folder_path = make_collect_folder() target_node_tuples = get_node_tuples_to_collect_by_all() # fileKnobがあるノードをすべてフルパスに変更 for node_tuple in target_node_tuples: change_file_knob_to_abs_path(node_tuple[0], node_tuple[1]) # collectFolderPathにnkを新規保存 split_script_name = os.path.splitext(os.path.split(nuke.Root()["name"].getValue())[1]) new_script_name = split_script_name[0] + "_collected" + split_script_name[1] new_script_path = os.path.join(collect_folder_path, new_script_name) nuke.scriptSaveAs(new_script_path) # project_directoryを設定 nuke.Root()["project_directory"].setValue("[python {nuke.script_directory()}]") # ファイルコピー&パス書き換え progress_bar = nuke.ProgressTask("collecting...") for node_tuple in target_node_tuples: progress_bar.setProgress( get_int_percent((target_node_tuples.index(node_tuple) + 1.0) / len(target_node_tuples)) ) if progress_bar.isCancelled(): break collect_node(node_tuple, collect_folder_path) # nkを保存 nuke.scriptSave() del progress_bar nuke.message("complete. \n\n( ´ー`)y-~~") return
def alfredRender(self): self.node.end() for node in nuke.allNodes(): node.knob('selected').setValue(0) for write in nuke.allNodes('Write'): write.knob('disable').setValue(1) self.node.begin() writeRender = nuke.toNode('WriteShot') writeRender.knob('selected').setValue(1) #nuke.show(writeRender) # alfred render luncher currTime = str(time.strftime('%d%m%y_%H%M%S')) nuke.scriptSave('') nukeScene = nuke.toNode('root').name() fileDir = os.path.dirname(nukeScene)+'/' panel = nuke.Panel('Alfred batch render') panel.addSingleLineInput('frame range', str(int(nuke.root()['first_frame'].getValue()))+','+str(int(nuke.root()['last_frame'].getValue()))) val = panel.show() if val ==1: frameRange = panel.value('frame range') for write in nuke.allNodes('Write'): write.knob('disable').setValue(1) writeRender.knob('disable').setValue(0) renderScene = fileDir+'.'+os.path.basename(nukeScene).split('.')[0]+'_alfredrender_'+writeRender.name()+'_'+currTime+'.nk' nuke.scriptSaveAs(renderScene, overwrite = 1) print 'sending '+renderScene+' to Alfred ...' #nuke.tcl('exec rnuke "'+renderScene+'" '+frameRange+' &;') os.popen('rnuke '+renderScene+' '+frameRange+' &') for write in nuke.allNodes('Write'): write.knob('disable').setValue(0) nuke.scriptSaveAs(nukeScene, overwrite = 1) else: print 'abort...'
def rrSubmit_Nuke_Node(node): nuke.scriptSave() CompName = nuke.root().name() if (CompName == None) or (len(CompName) == 0): writeError("Nuke comp not saved!") return jobList = [] noLocalSceneCopy = [False] rrSubmit_CreateSingleJobs_Node(jobList, noLocalSceneCopy, node) submitOptions = "" if noLocalSceneCopy[0]: submitOptions = submitOptions + "AllowLocalSceneCopy=0~0 " if rrSubmit_NukeXRequired(): submitOptions = submitOptions + " CONukeX=1~1 " rrSubmit_addPluginLicenses(jobList) submitJobsToRR(jobList, submitOptions)
def rrSubmit_Nuke_Shotgun(): #writeInfo ("rrSubmit v 7.0.24") nuke.scriptSave() CompName = nuke.root().name() if ((CompName==None) or (len(CompName)==0)): writeError("Nuke comp not saved!") return jobList= [] noLocalSceneCopy= [False] rrSubmit_CreateSingleJobs_shotgun(jobList) submitOptions="" #if (noLocalSceneCopy[0]): # submitOptions=submitOptions+"AllowLocalSceneCopy=0~0 " if (rrSubmit_NukeXRequired()): submitOptions=submitOptions+" CONukeX=1~1 " rrSubmit_addPluginLicenses(jobList) submitJobsToRR(jobList,submitOptions)
def replacePath(self): for n in nuke.allNodes(): if n.Class() in ['ReadGeo2','Camera2','Axis2','WriteGeo']: a = n.knob('file').value() a = a.replace( os.path.dirname(a) , self.scriptRoot+'/FBX') n.knob('file').setValue(a) for n in nuke.allNodes('Read'): a = n.knob('file').value() a = a.replace( '/'.join(os.path.dirname(a).split('/')[0:-1]) , self.scriptRoot+'/LAYERS') n.knob('file').setValue(a) for n in nuke.allNodes('Write'): a = n.knob('file').value() a = a.replace( '/'.join(os.path.dirname(a).split('/')[0:-1]) , self.scriptRoot+'/WRITE') n.knob('file').setValue(a) nuke.scriptSave("") if self.log.value(): self.generateLog()
def _nuke_execute(self, operation, file_path, **kwargs): """ The Nuke specific scene operations. """ if file_path: file_path = file_path.replace("/", os.path.sep) if operation == "current_path": # return the current script path return nuke.root().name().replace("/", os.path.sep) elif operation == "open": # open the specified script into the current window if nuke.root().modified(): raise TankError("Script is modified!") nuke.scriptClear() nuke.scriptOpen(file_path) elif operation == "save": # save the current script: nuke.scriptSave()
def batchReset(src,out): print src errFlg = 0 nuke.scriptOpen(src) for node in nuke.allNodes('Read'): if os.path.dirname(node.knob('file').getValue()) != r'S:/LSC/CGI/Asset/lightset/asset_checklight/nukeimages': print os.path.dirname(node.knob('file').getValue()) filelist = scanForFiles(os.path.dirname(node.knob('file').getValue())) print filelist node.knob('file').setValue(os.path.dirname(node.knob('file').getValue())+'/'+filelist[0][0]) node.knob('first').setValue(filelist[0][1]) node.knob('last').setValue(filelist[0][2]) node.knob('origfirst').setValue(filelist[0][1]) node.knob('origlast').setValue(filelist[0][2]) if not errFlg: print 'All selected Read nodes were reset.' nuke.scriptSave(out) for allnode in nuke.allNodes(): nuke.delete(allnode)
def post_publish(): element = nuke_publish_dialog.result if nuke_publish_dialog.published: #save the file nuke.scriptSave() #Publish user = nuke_publish_dialog.user src = nuke_publish_dialog.src comment = nuke_publish_dialog.comment dst = element.publish(user, src, comment) #Ensure file has correct permissions try: os.chmod(dst, 0660) except: pass print "TODO: export playblast" print nuke_publish_dialog.result.get_name()
def checkin(): filePath = nuke.callbacks.filenameFilter( nuke.root().name() ) save = nuke.scriptSave() if save==True: toCheckin = os.path.join(amu.getUserCheckoutDir(), os.path.basename(os.path.dirname(filePath))) if amu.canCheckin(toCheckin): dest = amu.checkin(toCheckin, False) nuke.message('Checkin Successful!') nuke.scriptClose() else: nuke.message('Can not check in')
def checkin(): save = nuke.scriptSave() if save==True: toCheckin = get_checkin_path() if can_checkin(): amu.setComment(toCheckin, 'comment') dest = amu.checkin(toCheckin) nuke.message('Checkin Successful!') nuke.scriptClose() else: nuke.message('Can not check in')
def prepForRender (self, node, renderType) : log ("prepForRender %s %s" % (node.name(), renderType)) baseDir = self.sessionDir + "/" + renderType dateString = time.strftime("%b %d %H:%M:%S") if (renderType == "checkpoint") : dateStringForName = "_" + re.sub (" ", "_", re.sub (":", "_", dateString)) else : dateStringForName = "" nodeDir = baseDir + "/" + node.name() + dateStringForName; if (not os.path.exists (nodeDir)) : log ("making directory '%s'" % nodeDir) os.makedirs (nodeDir) nuke.scriptSave (nodeDir + "/" + renderType + ".nk") return dateString
def createThreads(frameStart, frameEnd, numThreads, writeNodes=None): nuke.scriptSave() if not writeNodes: writeNodes = getWriteNodes() os.environ["DCC"] = "nuke" os.environ["EXE"] = nuke.EXE_PATH os.environ["SCENE"] = nuke.root().name() os.environ["WRITENODES"] = str(writeNodes) os.environ["frameStart"] = str(frameStart) os.environ["frameEnd"] = str(frameEnd) os.environ["numThreads"] = str(numThreads) # Start setEnvoriment() os.chdir(ROOT_RT) print os.startfile("main.bat")
def nk_backburner(): """ Background render Note: this assumes that the nuke executable is in PATH """ nuke.scriptSave() op = nuke.root()['name'].value() name = nuke.selectedNode().name() np = op+"_%s.bburn"%name shutil.copy2(op,np) ranges = "%s-%s" % (nuke.root().firstFrame(),nuke.root().lastFrame()) cmd = """ "%s" -m %i -F %s -X %s -ix %s""" % (nuke.EXE_PATH, int(nuke.env['numCPUs']/2), ranges, name, np) print cmd 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) 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") this = nuke.toNode(name) this['tile_color'].setValue(943405567) this['postage_stamp'].setValue(False) this['reading'].setValue(False) nuke.addKnobChanged(changeNodeColor,name,{},"Write") T = threading.Thread(target=render) T.start()
def custom_execute_panel(_list, exceptOnError = True): """ Override the default way Nuke executes multiple Write nodes to allow each Write node's addBeforeRender and addBeforeFrameRender to execute code *specific to that node* before they are rendered. """ _list = nuke.allNodes("Write") if _list[0] == nuke.root() else _list _list = [n for n in _list if not (n['disable'].value() or n['reading'].value())] if len(_list) == 0: nuke.message("No renderable Write nodes!") return else: _list = sorted(_list,key=lambda x: x['render_order'].value()) nuke.scriptSave("") for n in _list: if n['use_limit'].value(): first,last = n['first'].value(),n['last'].value() else: first,last = nuke.root().firstFrame(),nuke.root().lastFrame() print "Render started: %s" % n.name() nuke.execute(n.name(),int(first),int(last)) print "Render completed: %s" % n.name()
def execute(self, **kwargs): items = [] # get the main scene: scene_name = nuke.root()['name'].value() if not scene_name: raise TankError("Please Save your file before Rendering") items.append({"type": "work_file", "value": scene_name}) #scan scene for starting information items.append({'type':'start','value': nuke.root()['first_frame'].value()}) items.append({'type':'end','value': nuke.root()['last_frame'].value()}) items.append({'type':'limit','value':'nuke_render'}) jobname = '.'.join(os.path.basename(scene_name).split('.')[0:-1]) items.append({'type':'jobname','value':jobname}) #saving scene before dialog nuke.scriptSave() return items
def pmSaveToServer(): print 'Saving scene to server paths...' pm = PathMap( UnixSeparators = True, Verbose = True) nuke.scriptSave() # Get server scene name: scenename = nuke.root().name() scenename_server = scenename + '.' + SERVER_PATHS_SUFFIX + '.nk' # Map paths from client to server: error_msg = '' if pm.initialized: pm.toServerFile( scenename, scenename_server, SearchStrings, Verbose = True) else: print 'No paths map preset. Just copying scene to:' print scenename_server try: shutil.copy( scenename, scenename_server) except: error_msg = str(sys.exc_info()[1]) print 'File copied with error:' print error_msg if error_msg != '': nuke.message('Server scene copy error:\n' + error_msg)
def execute(self, **kwargs): scene_name = nuke.root()["name"].value() if not scene_name: raise TankError("Please Save your file before Rendering") jobname = os.path.splitext(os.path.basename(scene_name))[0] start = nuke.root()["first_frame"].value() end = nuke.root()["last_frame"].value() attrs = [ {"name": "submit_file", "value": str(scene_name), "title": "Submit File", "hidden": True}, {"name": "start", "value": int(start), "title": "Start Frame"}, {"name": "end", "value": int(end), "title": "End Frame"}, {"name": "by", "value": 1, "title": "By Frame"}, {"name": "jobname", "value": str(jobname), "title": "Job Name"}, {"name": "queue", "value": ["high", "mid", "low"], "title": "Queue"}, {"name": "submit", "value": True, "title": "Submit Job"}, ] nuke.scriptSave() return attrs
def save_script(): """ Save the current script under the same name. Return True or False depending on wether or not the operation was successful. """ try: result = nuke.scriptSave() return result except: # log logger.info('Error saving file.') return False
def _collect(localPath): n = nuke.allNodes() seqPads = ['%01d', '%02d', '%03d', '%04d', '%05d', '%06d', '%07d', '%08d', '%d', '%1d'] # Get script name scriptName = os.path.basename(nuke.Root().name()) # Save script to archive path newScriptPath = localPath + scriptName nuke.scriptSaveAs(newScriptPath) # Build lists of nodes (also remove duplicate Read nodes) if nuke.allNodes("Read"): readNodes = _dupReadDestroy(False) readPaths = [nukescripts.replaceHashes(node['file'].value()) for node in readNodes] else: readNodes = None readGeoNodes = nuke.allNodes("ReadGeo2") + nuke.allNodes("ReadGeo") readGeoPaths = [nukescripts.replaceHashes(node['file'].value()) for node in readGeoNodes] fbxNodes = [node for node in nuke.allNodes("Axis2") + nuke.allNodes("Camera2") if node['read_from_file'].value()] # Check to make sure there is something to archive if not readNodes and not readGeoNodes and not fbxNodes: return False # Create log file and write header info to it fOut = open(localPath + 'Archive Log.txt', 'w') fOut.write('Comp archived %s at %s\n\n\n' % (strftime("%m/%d/%Y"), strftime("%H:%M:%S"))) fOut.write('Comp Name: %s\n\n' % scriptName) fOut.write('Files archived to:\n\t%s\n\n\n' % localPath) # Archive Read nodes (if applicable) if readNodes: fOut.write('Read nodes and associated source files:\n') # Create footage directory os.makedirs(localPath + "Footage") footagePath = localPath + "Footage/" for node in readNodes: # Get Read node's footage path currentPath = node['file'].value() seqName = os.path.basename(currentPath) seqTuple = os.path.splitext(seqName) # Build local path to assign to Read node localReadFolder = footagePath + node.name() os.mkdir(localReadFolder) # Check for a sequence and copy if applicable if seqTuple[0].endswith(tuple(seqPads)): curFrame = node.firstFrame() while curFrame <= node.lastFrame(): fileName = seqName % (curFrame, ) shutil.copy2('%s/%s' % (os.path.dirname(currentPath), fileName), localReadFolder) curFrame += 1 # Copy single file else: shutil.copy2(currentPath, localReadFolder) # Re-link Read node to local footage node['file'].setValue('%s/%s' % (localReadFolder, seqName)) # Output Read node info to log file fOut.write('\t%s: %s\n' % (node.name(), seqName)) # Archive Geometry nodes (if applicable) if readGeoNodes: fOut.write('\nReadGeo nodes and associated geometry files:\n') # Create geometry directory os.makedirs(localPath + "Geometry") geoPath = localPath + "Geometry/" for node in readGeoNodes: # Get Geo node's file path currentPath = node['file'].value() seqName = os.path.basename(currentPath) seqTuple = os.path.splitext(seqName) # Build local path to assign to Geo node localGeoFolder = geoPath + node.name() os.mkdir(localGeoFolder) # Check for a geo sequence and copy if applicable # A little different than Read node since ReadGeo nodes have no explicit frame range if seqTuple[0].endswith(tuple(seqPads)): if seqTuple[0].endswith(('%d', '%1d')): padLength = 1 if seqTuple[0].endswith('%d'): baseName = seqTuple[0][:-2] else: baseName = seqTuple[0][:-3] else: padLength = seqPads.index(seqTuple[0][-4:]) + 1 baseName = seqTuple[0][:-4] extMatch = [i for i in os.listdir(os.path.dirname(currentPath)) if os.path.splitext(i)[1] == seqTuple[1]] fnPattern = baseName for i in range(0,padLength): fnPattern += '[0-9]' fnPattern += seqTuple[1] for f in extMatch: if fnmatch(f, fnPattern): shutil.copy2('%s/%s' % (os.path.dirname(currentPath), f), localGeoFolder) # Copy single file else: shutil.copy2(currentPath, localGeoFolder) # Re-link Geo node to local footage node['file'].setValue('%s/%s' % (localGeoFolder, seqName)) # Output Geo node info to log file fOut.write('\t%s: %s\n' % (node.name(), seqName)) # Archive FBX-dependent nodes (if applicable) if fbxNodes: fOut.write('\nFBX-dependent nodes and associated FBX files:\n') # Create FBX directory os.makedirs(localPath + "FBX") fbxPath = localPath + "FBX/" for node in fbxNodes: # Get FBX node's file path currentPath = node['file'].value() fileName = os.path.basename(currentPath) # Build local path to assign to FBX node localFBXFolder = fbxPath + node.name() os.mkdir(localFBXFolder) # Copy FBX file to local path shutil.copy2(currentPath, localFBXFolder) # Re-link FBX node to local footage node['file'].setValue('%s/%s' % (localFBXFolder, fileName)) # Output FBX node info to log file fOut.write('\t%s: %s\n' % (node.name(), fileName)) # Write total number of copied files to log file fOut.write('\n\n%d files total' % (sum((len(f) for _, _, f in os.walk(localPath)))-2, )) fOut.close() # Save script and return successfully nuke.scriptSave() return True
def collectFiles(): panelResult = collectPanel() #copy script to target directory script2Copy = nuke.root()['name'].value() scriptName = os.path.basename(nuke.Root().name()) fileNames = [] paddings = ['%01d', '%02d', '%03d', '%04d', '%05d', '%06d', '%07d', '%08d', '%d', '%1d'] videoExtension = ['mov', 'avi', 'mpeg', 'mpg', 'mp4', 'R3D'] cancelCollect = 0 # hit OK if panelResult[0] == 1 and panelResult[1] != '': targetPath = panelResult[1] # Check to make sure a file path is not passed through if os.path.isfile(targetPath): targetPath = os.path.dirname(targetPath) # Make sure target path ends with a slash (for consistency) if not targetPath.endswith('/'): targetPath += '/' # Check if local directory already exists. Ask to create it if it doesn't if not os.path.exists(targetPath): if nuke.ask("Directory does not exist. Create now?"): try: os.makedirs(targetPath) except: raise Exception, "Something's not working!" return False else: nuke.message("Cannot proceed without valid target directory.") return False # Get script name scriptName = os.path.basename(nuke.Root().name()) footagePath = targetPath + 'footage/' if (os.path.exists(footagePath)): pass else: os.mkdir(footagePath) task = nuke.ProgressTask("Collect Files 1.2") count = 0 for fileNode in nuke.allNodes(): if task.isCancelled(): cancelCollect = 1 break count += 1 task.setMessage("Collecting file: " + str(fileNode)) task.setProgress(count*100/len(nuke.allNodes())) if checkForKnob(fileNode, 'file'): if not checkForKnob(fileNode, 'Render'): fileNodePath = fileNode['file'].value() if (fileNodePath == ''): continue else: readFilename = fileNodePath.split("/")[-1] if checkForKnob(fileNode, 'first'): if (fileNodePath.endswith(tuple(videoExtension))): newFilenamePath = footagePath + fileNodePath.split("/")[-1] if (os.path.exists(newFilenamePath)): print (newFilenamePath + ' DUPLICATED') else: if (os.path.exists(fileNodePath)): shutil.copy2(fileNodePath, newFilenamePath) print (newFilenamePath + ' COPIED') else: print (newFilenamePath + ' MISSING') else: # frame range frameFirst = fileNode['first'].value() frameLast = fileNode['last'].value() framesDur = frameLast - frameFirst if (frameFirst == frameLast): newFilenamePath = footagePath + readFilename if (os.path.exists(newFilenamePath)): print (newFilenamePath + ' DUPLICATED') else: if (os.path.exists(fileNodePath)): shutil.copy2(fileNodePath, newFilenamePath) print (newFilenamePath + ' COPIED') else: print (newFilenamePath + ' MISSING') else: dirSeq = fileNodePath.split("/")[-2] + '/' newFilenamePath = footagePath + dirSeq if (os.path.exists(newFilenamePath)): print (newFilenamePath + ' DUPLICATED') else: os.mkdir(newFilenamePath) # rename sequence for frame in range(framesDur + 1): for pad in paddings: # Copy sequence file if (re.search(pad, fileNodePath.split("/")[-1])): originalSeq = fileNodePath.replace(pad, str(pad % frameFirst)) frameSeq = fileNodePath.split("/")[-1].replace(pad, str(pad % frameFirst)) fileNames.append (frameSeq) newSeq = newFilenamePath + frameSeq frameFirst += 1 task.setMessage("Collecting file: " + frameSeq) if (os.path.exists(newSeq)): print (newSeq + ' DUPLICATED') else: if (os.path.exists(originalSeq)): shutil.copy(originalSeq, newSeq) print (newSeq + ' COPIED') else: print (newSeq + ' MISSING') print ('\n') # Copy single file else: newFilenamePath = footagePath + fileNodePath.split("/")[-1] if (os.path.exists(newFilenamePath)): print (newFilenamePath + ' DUPLICATED') else: if (os.path.exists(fileNodePath)): shutil.copy2(fileNodePath, newFilenamePath) print (newFilenamePath + ' COPIED') else: print (newFilenamePath + ' MISSING') else: pass if (cancelCollect == 0): # Save script to archive path newScriptPath = targetPath + scriptName nuke.scriptSaveAs(newScriptPath) #link files to new path for fileNode in nuke.allNodes(): if checkForKnob(fileNode, 'file'): if not checkForKnob(fileNode, 'Render'): fileNodePath = fileNode['file'].value() if (fileNodePath == ''): continue else: if checkForKnob(fileNode, 'first'): if (fileNodePath.endswith(tuple(videoExtension))): fileNodePath = fileNode['file'].value() readFilename = fileNodePath.split("/")[-1] reloadPath = '[file dirname [value root.name]]/footage/' + readFilename fileNode['file'].setValue(reloadPath) else: # frame range frameFirst = fileNode['first'].value() frameLast = fileNode['last'].value() if (frameFirst == frameLast): fileNodePath = fileNode['file'].value() readFilename = fileNodePath.split("/")[-1] reloadPath = '[file dirname [value root.name]]/footage/' + readFilename fileNode['file'].setValue(reloadPath) else: fileNodePath = fileNode['file'].value() dirSeq = fileNodePath.split("/")[-2] + '/' readFilename = fileNodePath.split("/")[-1] reloadPath = '[file dirname [value root.name]]/footage/' + dirSeq + readFilename fileNode['file'].setValue(reloadPath) else: fileNodePath = fileNode['file'].value() readFilename = fileNodePath.split("/")[-1] reloadPath = '[file dirname [value root.name]]/footage/' + readFilename fileNode['file'].setValue(reloadPath) else: pass else: pass nuke.scriptSave() del task print ('COLLECT DONE!!') nuke.message('COLLECT DONE!!') else: del task print ('COLLECT CANCELLED - Toma Rojo Puto') nuke.message('COLLECT CANCELLED') # If they just hit OK on the default ellipsis... elif panelResult[0] == 1 and panelResult[1] == '': nuke.message("Select a path") return False # hit CANCEL else: print ('COLLECT CANCELLED')
def execute(self, operation, file_path, context, parent_action, file_version, read_only, **kwargs): """ Main hook entry point :param operation: String Scene operation to perform :param file_path: String File path to use if the operation requires it (e.g. open) :param context: Context The context the file operation is being performed in. :param parent_action: This is the action that this scene operation is being executed for. This can be one of: - open_file - new_file - save_file_as - version_up :param file_version: The version/revision of the file to be opened. If this is 'None' then the latest version should be opened. :param read_only: Specifies if the file should be opened read-only or not :returns: Depends on operation: 'current_path' - Return the current scene file path as a String 'reset' - True if scene was reset to an empty state, otherwise False all others - None """ # AARDMAN ADDITION # adds short cuts to file browser aaNukeUtils.aaSetupShortCuts() if file_path: file_path = file_path.replace("/", os.path.sep) if operation == "current_path": # return the current script path return nuke.root().name().replace("/", os.path.sep) elif operation == "open": # open the specified script nuke.scriptOpen(file_path) # reset any write node render paths: if self._reset_write_node_render_paths(): # something changed so make sure to save the script again: nuke.scriptSave() elif operation == "save": # save the current script: nuke.scriptSave() elif operation == "save_as": old_path = nuke.root()["name"].value() try: # rename script: nuke.root()["name"].setValue(file_path) # reset all write nodes: self._reset_write_node_render_paths() # save script: nuke.scriptSaveAs(file_path, -1) except Exception, e: # something went wrong so reset to old path: nuke.root()["name"].setValue(old_path) raise TankError("Failed to save scene %s", e)