def save(): filename = nuke.scriptName() nkDir, nkFile = os.path.split(filename) name, ext = os.path.splitext(nkFile) fileSaved = False components = name.split('_v') shotName = components[0] if len(components)<=1: version = 0 else: version = int(components[1]) while not fileSaved: # CONSTRUCT FILE NAME nkName = '%s_v%02d' % ( shotName, version ) # JOIN DIRECTORY AND NAME TO FORM FULL FILE PATH nkPath = os.path.join( nkDir, '%s.nk' % nkName ) if os.path.isfile(nkPath): version += 1 continue updateWriteNodeVersions(version) # SAVE NUKE SCRIPT nuke.scriptSaveAs(nkPath) fileSaved = True return nkPath
def _doPublish( self, entity, arg, ui ): import Hammer # add new version Hammer.Database().addNewVersion( entity, arg['description']['value'], False ) newVersion = len( entity['approved'] ) # set current version Hammer.Database().editEntity( entity['entityId'], version=newVersion ) folder = '%s/%s/' %( entity['path'], str(newVersion*10).zfill(4) ) path = '%s/scene.nk' %( folder ) Forge.core.System.mkdir( folder ) import nuke entityInfo = Hammer.Hnuke.Actions.GetEntitiesInfoFromScene( entity=entity, arg={'entityId':entity['entityId']}, ui=ui ).returnValue[0] entityInfo.knob('entityVersion').setValue( newVersion ) nuke.scriptSaveAs( filename=path ) # publish done self.popup = Hammer.ui.WindowInfo( info='SaveInc done. New version : %i' %(newVersion) ) self.popup.show()
def saveVersion(): scriptsdir = os.path.join(jeeves_core.jobsRoot, os.getenv('JOB'), 'vfx', 'nuke', os.getenv('SHOT'), 'scripts', jeeves_core.user) if os.path.isdir(scriptsdir): print 'dir exists' else: print 'need to create dir' jeeves_core.make.nuke_user(jeeves_core.user) print 'done' # strip white space from user input description description = nuke.getInput( 'script description', 'slapcomp' ).replace( ' ', '_' ) job = os.environ['JOB'].rsplit('_', 1)[-1] fileSaved = False version = int(1) while not fileSaved: scriptName = '%s_%s_%s_v%02d.nk' % ( os.getenv('SHOT'), description, jeeves_core.getVars.get_initial(), version ) fullPath = os.path.join( scriptsdir, scriptName ) # if file exists, we version up if os.path.isfile(fullPath): version += 1 continue # save the script nuke.scriptSaveAs( fullPath ) fileSaved = True freshLables()
def checkout_button_clicked(self): version = self.rollback_dialog.get_current_item()[1:] filePath = common.get_checkin_path() toCheckout = amu.getCheckinDest(filePath) latestVersion = amu.tempSetVersion(toCheckout, version) amu.discard(filePath) try: destpath = amu.checkout(toCheckout, True) except Exception as e: if not amu.checkedOutByMe(toCheckout): muke.message(str(e)) return else: destpath = amu.getCheckoutDest(toCheckout) amu.tempSetVersion(toCheckout, latestVersion) # move to correct checkout directory correctCheckoutDir = amu.getCheckoutDest(toCheckout) if not destpath == correctCheckoutDir: if os.path.exists(correctCheckoutDir): shutil.rmtree(correctCheckoutDir) os.rename(destpath, correctCheckoutDir) toOpen = os.path.join(correctCheckoutDir, self.get_filename(toCheckout)+'.nk') if not os.path.exists(toOpen): # create new file nuke.scriptNew() nuke.scriptSaveAs(filename=toOpen, overwrite=0) else: nuke.scriptOpen(toOpen) self.rollback_dialog.close()
def save(self, name=None): """ Custom Nuke-based save command """ if name is None: name = nuke.toNode("root").name() nuke.scriptSaveAs(name)
def save_as(self, version): """"the save action for nuke environment uses Nukes own python binding """ # set the extension to '.nk' version.extension = '.nk' # set project_directory self.project_directory = os.path.dirname(version.path) # create the main write node self.create_main_write_node(version) # replace read and write node paths self.replace_external_paths() # create the path before saving try: os.makedirs(version.path) except OSError: # path already exists OSError pass # set frame range if version.type.type_for == 'Shot': self.set_frame_range( version.version_of.start_frame, version.version_of.end_frame ) nuke.scriptSaveAs(version.full_path) return True
def smartSaver(): r=nuke.root()['name'].value() #root if r!="": rArray = r.split("/"); rootLast = rArray[len(rArray)-1] rArray.pop() directoryPath = '/'.join(rArray) nameArray = rootLast.split(".") projectName=nameArray[0] #delete lastTime from project name projectNameZeroDateArr = projectName.split("@") projectNameZeroDate = projectNameZeroDateArr[0] t = getTime() safeTo = directoryPath+"/"+projectNameZeroDate+"@"+t+".nk" nuke.scriptSaveAs(safeTo) #add current script to SmartRecentScripts saveInSmartRecentScripts(safeTo) else: nuke.message("You haven't saved your nuke project. Please make sure to save your project first in order to proceed.")
def checkout(self): asset_name = self.checkout_dialog.get_current_item() toCheckout = os.path.join(os.environ['SHOTS_DIR'], asset_name,'compositing') #nuke.message(toCheckout) try: destpath = amu.checkout(toCheckout, True) #nuke.message(destpath) except Exception as e: if not amu.checkedOutByMe(toCheckout): nuke.message(str(e)) return else: destpath = amu.getCheckoutDest(toCheckout) #nuke.message("destpath = " + destpath) toOpen = os.path.join(destpath,self.get_filename(toCheckout)+'.nk') #nuke.message(toOpen) #nuke.message("toOpen = " + toOpen) #nuke.scriptClose() if not os.path.exists(toOpen): nuke.scriptClear() nuke.scriptSaveAs(filename=toOpen, overwrite=1) else: nuke.scriptClear() nuke.scriptOpen(toOpen) nuke.message('Checkout Successful')
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 script_comp_version_up(): """Adds 1 to the _c## at the end of the script name and saves a new version.""" root_name = nuke.toNode("root").name() (prefix, v) = nukescripts.version_get(root_name, "c") if v is None: return v = int(v) nuke.scriptSaveAs(nukescripts.version_set(root_name, prefix, v, v + 1))
def _do_nuke_post_publish(self, work_template, progress_cb, user_data): """ Do any Nuke post-publish work :param work_template: The primary work template used for the publish :param progress_cb: Callback to be used when reporting progress :param user_data: A dictionary containing any data shared by other hooks run prior to this hook. Additional data may be added to this dictionary that will then be accessible from user_data in any hooks run after this one. """ # If we're in Hiero or Nuke Studio we need to call through to those. engine = self.parent.engine if hasattr(engine, "hiero_enabled") and engine.hiero_enabled: return self._do_hiero_post_publish(work_template, progress_cb, user_data) elif hasattr(engine, "studio_enabled") and engine.studio_enabled: return self._do_nukestudio_post_publish(work_template, progress_cb, user_data) import nuke progress_cb(0, "Versioning up the script") # get the current script path: original_path = nuke.root().name() script_path = os.path.abspath(original_path.replace("/", os.path.sep)) # increment version and construct new name: progress_cb(25, "Finding next version number") fields = work_template.get_fields(script_path) next_version = self._get_next_work_file_version(work_template, fields) fields["version"] = next_version new_path = work_template.apply_fields(fields) # log info self.parent.log_debug("Version up work file %s --> %s..." % (script_path, new_path)) # rename script: nuke.root()["name"].setValue(new_path) # update write nodes: write_node_app = tank.platform.current_engine().apps.get("tk-nuke-writenode") if write_node_app: # only need to forceably reset the write node render paths if the app version # is less than or equal to v0.1.11 from distutils.version import LooseVersion if (write_node_app.version != "Undefined" and LooseVersion(write_node_app.version) <= LooseVersion("v0.1.11")): progress_cb(50, "Resetting render paths for write nodes") # reset render paths for all write nodes: for wn in write_node_app.get_write_nodes(): write_node_app.reset_node_render_path(wn) # save the script: progress_cb(75, "Saving the scene file") nuke.scriptSaveAs(new_path.replace(os.path.sep, "/")) progress_cb(100)
def process(self, context): # saving nuke script file_path = self.get_path(context) file_dir = os.path.dirname(file_path) if not os.path.exists(file_dir): os.makedirs(file_dir) nuke.scriptSaveAs(file_path)
def repair(self, instance): """ Saves the nuke script to the correct path. """ # saving nuke script file_path = self.get_path(instance) file_dir = os.path.dirname(file_path) if not os.path.exists(file_dir): os.makedirs(file_dir) nuke.scriptSaveAs(file_path)
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)
def assembleScript(dstPath=None): log = "" if not dstPath: dstPath = nuke.getFilename("Select Destination Path") addLogLine(log, "--[ Und Los! ]--") # copy Files # Selected Outs for node in nuke.selectedNodes(): if node.Class() == "Write": log = addLogLine(log, copyNodeFileTo(node, dstPath, "outs")) # Reads for node in nuke.allNodes(): if node.Class() != "Write": log = addLogLine(log, copyNodeFileTo(node, dstPath, "source")) for group in nuke.allNodes('Group'): with group: for node in nuke.allNodes(): if node.Class() != "Write": log = addLogLine(log, copyNodeFileTo(node, dstPath, "source")) # Save Script nr = nuke.root() nr["project_directory"].setValue("[python {nuke.script_directory()}]") scriptpath, scriptname = os.path.split(nr["name"].getValue()) if scriptname =="": scriptname = "shotscript_v01.nk" try: os.makedirs(os.path.join(dstPath, "setup")) except: pass nuke.scriptSaveAs(os.path.join(dstPath, "setup", scriptname) ) # Fettig log = addLogLine(log, "--[ fin ]--") nuke.message(log)
def saveNK():# Save Scene and build Nuke scene global saveScene pathNK = '{3}{0}/{1}/SHOT_{2}/'.format(codePart, codeSequence, codeShot, rootComp) sceneNameFull = '{0}{1}'.format(pathNK, sceneName) print 'saveNK [sceneNameFull] = {}'.format(sceneNameFull) if os.path.isdir(pathNK): nuke.scriptSaveAs(sceneNameFull) buildScene() else: os.makedirs(pathNK) nuke.scriptSaveAs(sceneNameFull) buildScene()
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 saveRandomName(): """ Automatically saves comps on launch with a random name to NUKE_TEMP_DIR. To remove a comp from cache, delete all nodes, save, and quit. """ if nuke.root().name() == "Root": path = os.environ["NUKE_TEMP_DIR"]\ + "/" + nuke.randomWord()\ + "-" + nuke.randomWord()\ + "_" + datetime.now().strftime("%d-%B-%Y")\ + "_v1.nk" print "Default saved: " + path nuke.scriptSaveAs(path) nuke.removeOnUserCreate(saveRandomName)
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 save(self): try: try: name = nuke.root().name() if name == "Root": current_path = os.path.join(os.getcwd(), "untitled.nk") else: current_path = name except: # in the PLE, nuke.root() returns None current_path = os.path.join(os.getcwd(), "untitled.nk") nuke.scriptSaveAs(self.path, 1) finally: # restore the original path nuke.root()['name'].setValue(current_path)
def makeLocalRenderOut(orgFilename, locFilename, orgDir, orgDirWinDrive, locDir): writeInfo("") orgDir=orgDir.replace("\\","/") locDir=locDir.replace("\\","/") orgDirWinDrive=orgDirWinDrive.replace("\\","/") writeInfo("Replacing: "+orgDir+" => "+locDir) writeInfo("Replacing: "+orgDirWinDrive+" => "+locDir) writeInfo("") nuke.scriptOpen(orgFilename) #replace all scripted paths in all read nodes #change render path to local render out n = getAllWriteNodes() for writeNode in n: if (writeNode['disable'].value()): continue ## if isGizmo(writeNode): ## with writeNode: ## gList = nuke.allNodes('Write') + nuke.allNodes('DeepWrite') ## for gnode in gList: ## if (gnode['disable'].value()): ## continue ## convertWriteToLocal(gnode, orgDir, orgDirWinDrive, locDir) ## else: convertWriteToLocal(writeNode, orgDir, orgDirWinDrive, locDir) #replace all scripted paths in all read nodes n = nuke.allNodes('Read') + nuke.allNodes('DeepRead') for readNode in n: if (readNode['disable'].value()): continue pathScripted=readNode['file'].value() if ((pathScripted== None) or (len(pathScripted)<3)): continue pathResolved=nuke.filename(readNode) readNode['file'].setValue(pathResolved) writeInfo(readNode['name'].value()+": "+pathScripted+" => "+pathResolved) nuke.scriptSaveAs(locFilename,1) writeInfo("") writeInfo("Done") writeInfo("")
def _do_nuke_post_publish(self, work_template, progress_cb): """ Do any nuke post-publish work :param work_template: The primary work template used for the publish :param progress_cb: Callback to be used when reporting progress """ import nuke progress_cb(0, "Versioning up the script") # get the current script path: original_path = nuke.root().name() script_path = os.path.abspath(original_path.replace("/", os.path.sep)) # increment version and construct new name: progress_cb(25, "Finding next version number") fields = work_template.get_fields(script_path) next_version = self._get_next_work_file_version(work_template, fields) fields["version"] = next_version new_path = work_template.apply_fields(fields) # log info self.parent.log_debug("Version up work file %s --> %s..." % (script_path, new_path)) # rename script: nuke.root()["name"].setValue(new_path) # update write nodes: write_node_app = tank.platform.current_engine().apps.get("tk-nuke-writenode") if write_node_app: # only need to forceably reset the write node render paths if the app version # is less than or equal to v0.1.11 from distutils.version import LooseVersion if (write_node_app.version != "Undefined" and LooseVersion(write_node_app.version) <= LooseVersion("v0.1.11")): progress_cb(50, "Resetting render paths for write nodes") # reset render paths for all write nodes: for wn in write_node_app.get_write_nodes(): write_node_app.reset_node_render_path(wn) # save the script: progress_cb(75, "Saving the scene file") nuke.scriptSaveAs(new_path.replace(os.path.sep, "/")) progress_cb(100)
def post_checkout(): filepath = nuke_checkout_dialog.result #print filepath if filepath is not None: #Find nuke alternative for cmds --> import maya.cmds as cmds # if not cmds.file(q=True, sceneName=True) == '': # cmds.file(save=True, force=True) #save file if not os.path.exists(filepath): # cmds.file(new=True, force=True) # cmds.file(rename=filepath) # cmds.file(save=True, force=True) print "new file "+filepath nuke.scriptSaveAs(filepath+".nk") else: # cmds.file(filepath, open=True, force=True) print "open file "+filepath nuke.scriptOpen(filepath)
def main(): baked = '_baked' (base, ext) = os.path.splitext(nuke.scriptName()) if base.endswith(baked): newfile = base + ext else: newfile = base + baked + ext nukescripts.misc.clear_selection_recursive() for n in nuke.allNodes(): if n.Class() in ('Precomp', 'Group', 'Gizmo'): n.expand() nukescripts.misc.clear_selection_recursive() # for n in nuke.allNodes(): # if n.Class() == 'Write': # n['file'].setValue(n['file'].evaluate().strip()) nuke.scriptSaveAs(filename = newfile, overwrite = 1)
def runScript(filepath): nuke.scriptOpen(filepath) r3d = nuke.toNode('Read1') r3d.setXYpos(730, -451) nuke.toNode('HieroData').setXYpos(730, -359) jpg = nuke.toNode('Read2') if jpg != None: print "has no jpg-read" jpg.setXYpos(840, -457) nuke.toNode('HieroData1').setXYpos(840, -353) first = jpg.knob('first').getValue() last = jpg.knob('last').getValue() proxy = jpg.knob('file').getValue() r3d.knob('first').setValue(first) r3d.knob('origfirst').setValue(first) r3d.knob('last').setValue(last) r3d.knob('origlast').setValue(last) r3d.knob('proxy').setValue(proxy) nuke.toNode('AddTimeCode1').setXYpos(730, 135) nuke.toNode('ModifyMetaData1').setXYpos(730, 159) nuke.toNode('Reformat1').setXYpos(730, 183) nuke.toNode('Reformat2').setXYpos(840, 183) nuke.toNode('Write_preview').setXYpos(730, 217) nuke.toNode('Write_master').setXYpos(840, 217) nuke.toNode('AddTimeCode1').connectInput(0, nuke.toNode('HieroData')) viewer = None for n in nuke.allNodes(): if n.Class() == 'Viewer': viewer = n if viewer == None: print "has no viewer" viewer = nuke.createNode("Viewer") viewer.setXYpos(730, 263) viewer.connectInput(0, nuke.toNode('Write_preview')) nuke.root().knob('proxy_type').setValue('scale') #nuke.scriptSaveAs(filepath.replace(".nk", "_test.nk"), 1) nuke.scriptSaveAs(filepath, 1) nuke.scriptExit()
def easySave(): nkDir = nukeDir() # GET DESCRIPTION FROM USER BUT STRIP ALL WHITE SPACES description = nuke.getInput( 'script description', 'Your Comp name' ).replace( ' ', '' ) fileSaved = False version = 1 while not fileSaved: # CONSTRUCT FILE NAME nkName = '%s_%s_%03d.nk' % (SHOT,description, version) # JOIN DIRECTORY AND NAME TO FORM FULL FILE PATH nkPath = os.path.join( nkDir, nkName ) # IF FILE EXISTS VERSION UP if os.path.isfile( nkPath ): version += 1 continue # SAVE NUKE SCRIPT nuke.scriptSaveAs( nkPath ) fileSaved = True return nkPath
def create_local_scene(original_nuke_file, local_nuke_file): """ Open Nuke file in its original location; convert all SG Write nodes to normal Nuke node; save the file to temp local directory. param original_nuke_file: Path to original Nuke file. Should be valid SG Toolkit project. param local_nuke_file: Path to temp nuke file. Provided by the rrServer. """ # Start SG Nuke engine and convert all SG write node to Nuke Write engine = start_sg_nuke_engime(original_nuke_file) nuke.scriptOpen(original_nuke_file) sg_write_nodes = nuke.allNodes(group=nuke.root(), filter='WriteTank', recurseGroups = True) # Store SG write nodes output paths sg_write_paths = {} for n in sg_write_nodes: sg_write_paths[n.name()] = n.knob('tk_cached_proxy_path').value() convert_sg_write_nodes(engine) # Set original output path to all newly converted write nodes nuke_write_nodes = nuke.allNodes('Write') for n in nuke_write_nodes: n.knob('file').setValue(sg_write_paths[n.name()]) log.info('Render output path: %s' % n.knob('file').value()) # TODO(Kirill): Need to destroy the engine somehow. # Otherwise this error is raised # ERROR: The Shotgun Pipeline Toolkit is disabled: The path '' # does not seem to belong to any known Toolkit project! log.info('Saving nuke script to %s' % local_nuke_file) nuke.scriptSaveAs(local_nuke_file, 1) log.line() log.info('Local scene created successfully.')
def _do_nuke_post_publish(self, work_template, progress_cb): """ Do any nuke post-publish work """ import nuke progress_cb(0, "Versioning up the script") # get the current script path: original_path = nuke.root().name() script_path = os.path.abspath(original_path.replace("/", os.path.sep)) # increment version and construct new name: progress_cb(25, "Finding next version number") fields = work_template.get_fields(script_path) next_version = self._get_next_work_file_version(work_template, fields) fields["version"] = next_version new_path = work_template.apply_fields(fields) # log info self.parent.log_debug("Version up work file %s --> %s..." % (script_path, new_path)) # rename script: nuke.root()["name"].setValue(new_path) # update write nodes: write_node_app = tank.platform.current_engine().apps.get("tk-nuke-writenode") if write_node_app: progress_cb(50, "Resetting render paths for write nodes") # reset render paths for all write nodes: for wn in write_node_app.get_write_nodes(): write_node_app.reset_node_render_path(wn) # save the script: progress_cb(75, "Saving the scene file") nuke.scriptSaveAs(new_path.replace(os.path.sep, "/")) progress_cb(100)
def easySave(): nkDir = nukeDir() # GET DESCRIPTION FROM USER BUT STRIP ALL WHITE SPACES - EASYSAVE description = nuke.getInput( 'script description: ', 'init comp' ).replace( ' ', '') fileSaved = False version = 1 while not fileSaved: # CONSTRUCT FILENAME t = os.getenv('SHOW') t = str(t) t = t.replace(' ', '') nkName = '%s_%s_%s_%s_v%02d.nk' % ( t, 'scene' + os.getenv('SCENE'), 'shot' + os.getenv('SHOT'), description, version ) # JOIN DIRECTORY AND NAME TO FORM FULL FILE PATH nkPath = os.path.join( nkDir, nkName ) # IF FILE EXISTS VERSION UP if os.path.isfile( nkPath ): version += 1 continue # SAVE NUKE SCRIPT nuke.scriptSaveAs( nkPath ) fileSaved = True return nkPath
def process(self, instance): if 'workfile' in instance.context.data: host = pyblish.api.current_host() workfile = instance.context.data['workfile'] self.log.info("workfile '%s'" % workfile) if host == 'nuke': import nuke nuke.scriptSaveAs(workfile) elif host == 'maya': import pymel.core as pm if os.path.exists(workfile): pm.system.openFile(workfile, force=True) else: pm.saveAs(workfile, type='mayaAscii') proj_path = os.path.dirname(workfile) self.log.info("Setting Maya project to '%s'" % proj_path) pm.mel.setProject(proj_path) else: raise pyblish.api.ValidationError( "Can't find workfile in instance.context.")
def OutputMOV(self): self.nodeWrites = nuke.selectedNodes('Write') self.nodeContactSheet = nuke.selectedNodes('ContactSheet') self.nodeReformat = nuke.selectedNodes('Reformat') self.allSelectNode = nuke.selectedNodes() #self.selectRead=nuke.selectedNodes('Read') if not self.nodeWrites: nuke.message( '\xe6\xb2\xa1\xe6\x9c\x89\xe9\x80\x89\xe6\x8b\xa9write\xe8\x8a\x82\xe7\x82\xb9' ) return if not self.nodeContactSheet: nuke.message( '\xe6\xb2\xa1\xe6\x9c\x89\xe9\x80\x89\xe6\x8b\xa9ContactSheet\xe8\x8a\x82\xe7\x82\xb9' ) return if not self.nodeReformat: nuke.message( '\xe6\xb2\xa1\xe6\x9c\x89\xe9\x80\x89\xe6\x8b\xa9Reformat\xe8\x8a\x82\xe7\x82\xb9' ) return writeFile = self.nodeWrites[0]['file'].value() #输出的文件夹 outPutDir = os.path.dirname(writeFile) all = pyseq.getSequences(outPutDir) if not all: nuke.message( "write\xe8\x8a\x82\xe7\x82\xb9\xe6\xb2\xa1\xe6\x9c\x89\xe8\xbe\x93\xe5\x87\xba\xe7\xb4\xa0\xe6\x9d\x90" ) return dirNames = all[0].path() print dirNames dirName = pyseq.getSequences(dirNames) print dirName if dirName and dirName[0].length() == 1: createReadNode = nuke.nodes.Read() ReadPath = dirNames.replace("\\", '/') createReadNode['file'].setValue(ReadPath) createReadNode['origfirst'].setValue(1) createReadNode['origlast'].setValue(1) createReadNode['first'].setValue(1) createReadNode['last'].setValue(1) createReadNode['on_error'].setValue('cheeckerboard') _w = self.nodeContactSheet[0]['width'].value( ) * self.nodeReformat[0]['scale'].value() _h = self.nodeContactSheet[0]['height'].value( ) * self.nodeReformat[0]['scale'].value() _width = int(_w) _height = int(_h) ReadOFormat = createReadNode['format'].value() Flag = True j = 0 if ReadOFormat.width() != _width or ReadOFormat.height( ) != _height: allFormat = nuke.formats() for eachFormat in allFormat: if eachFormat.width() == _width and eachFormat.height( ) == _height: myFormat = eachFormat.name() if myFormat != None: createReadNode['format'].setValue(myFormat) Flag = False break if Flag: #键的名字 mySize = "" while True: mySize = ('my_Size%s' % j) if mySize not in [ eachFormat.name() for eachFormat in allFormat ]: break else: j += 1 widthHeight = str(_width) + " " + str(_height) square = widthHeight + " " + mySize nuke.addFormat(square) createReadNode['format'].setValue(mySize) createNodeWrite = nuke.nodes.Write() mydirName = writeFile.split("/") myFiledirName = os.path.dirname(writeFile) getSequences = pyseq.getSequences(myFiledirName)[0] getStartFrame = getSequences[0]._get_filename().split(".")[1] getLastFrame = getSequences[-1]._get_filename().split(".")[1] myWritePath = '/'.join(mydirName[0:-2]) + "/" + mydirName[ -3] + "(" + getStartFrame + "-" + getLastFrame + ").mov" createNodeWrite['file'].setValue(myWritePath) createNodeWrite.setInput(0, createReadNode) createNodeWrite['file_type'].setValue('mov') createNodeWrite['meta_codec'].setValue('jpeg') createNodeWrite['mov64_quality_min'].setValue(10) createNodeWrite['mov64_quality_max'].setValue(10) self.nukeName = '/'.join( mydirName[0:-2]) + "/" + "mov_" + mydirName[ -3] + "_(" + getStartFrame + "-" + getLastFrame + ").nk" else: createReadNode = nuke.nodes.Read() createReadNode['file'].setValue(writeFile) createReadNode['on_error'].setValue('cheeckerboard') _w = self.nodeContactSheet[0]['width'].value( ) * self.nodeReformat[0]['scale'].value() _h = self.nodeContactSheet[0]['height'].value( ) * self.nodeReformat[0]['scale'].value() _width = int(_w) _height = int(_h) ReadOFormat = createReadNode['format'].value() Flag = True j = 0 if ReadOFormat.width() != _width or ReadOFormat.height( ) != _height: allFormat = nuke.formats() for eachFormat in allFormat: if eachFormat.width() == _width and eachFormat.height( ) == _height: myFormat = eachFormat.name() if myFormat != None: createReadNode['format'].setValue(myFormat) Flag = False break if Flag: #键的名字 mySize = "" while True: mySize = ('my_Size%s' % j) if mySize not in [ eachFormat.name() for eachFormat in allFormat ]: break else: j += 1 widthHeight = str(_width) + " " + str(_height) square = widthHeight + " " + mySize nuke.addFormat(square) createReadNode['format'].setValue(mySize) createNodeWrite = nuke.nodes.Write() mydirName = writeFile.split("/") myFiledirName = os.path.dirname(writeFile) getSequences = pyseq.getSequences(myFiledirName)[0] getStartFrame = getSequences[0]._get_filename().split(".")[1] getLastFrame = getSequences[-1]._get_filename().split(".")[1] print getStartFrame print getLastFrame createReadNode['origfirst'].setValue(int(getStartFrame)) createReadNode['origlast'].setValue(int(getLastFrame)) createReadNode['first'].setValue(int(getStartFrame)) createReadNode['last'].setValue(int(getLastFrame)) myWritePath = '/'.join(mydirName[0:-2]) + "/" + mydirName[ -3] + "(" + getStartFrame + "-" + getLastFrame + ").mov" createNodeWrite['file'].setValue(myWritePath) createNodeWrite.setInput(0, createReadNode) createNodeWrite['file_type'].setValue('mov') createNodeWrite['meta_codec'].setValue('jpeg') createNodeWrite['mov64_quality_min'].setValue(10) createNodeWrite['mov64_quality_max'].setValue(10) self.nukeName = '/'.join( mydirName[0:-2]) + "/" + "mov_" + mydirName[ -3] + "_(" + getStartFrame + "-" + getLastFrame + ").nk" print self.nukeName for nodes in self.allSelectNode: nuke.delete(nodes) nuke.scriptSaveAs(self.nukeName)
def action(self): readList = [] writeList= [] fbxList= [] if os.path.exists(self.file.value() + '/') == False: os.makedirs(self.file.value()) nuke.scriptSaveAs(self.file.value() + '/' + self.scriptName.value()) readToCopy= [] writeToCopy= [] fbxToCopy = [] self.scriptRoot = '''[file dirname [knob root.name]]''' DESTINATION = self.file.value() LAYERS = DESTINATION + 'LAYERS/' FBX = DESTINATION + 'GEO/' WRITE = DESTINATION + 'WRITE/' # Read for n in nuke.allNodes('Read'): if n.knob('file').value() not in readList: if n.knob('disable').value() == False: readList.append(nuke.filenameFilter(n.knob('file').value())) for p in readList: if os.path.exists(os.path.dirname(p)): for f in os.listdir(os.path.dirname(p)): if os.path.splitext(f)[-1] == os.path.splitext(p)[-1]: if len(f.split('.')[0]) == len(os.path.basename(p).split('.')[0]): path = '/'.join([os.path.dirname(p),os.path.basename(f)]) if os.path.isfile(path): readToCopy.append(path) #FBX for n in nuke.allNodes(): if n.Class() in ['ReadGeo2','Camera2','Axis2','WriteGeo']: if n.knob('file').value(): if n.knob('file').value() not in fbxList: if n.knob('disable').value() == False: fbxList.append(nuke.filenameFilter(n.knob('file').value())) for p in fbxList: if os.path.exists(os.path.dirname(p)): for f in os.listdir(os.path.dirname(p)): if os.path.splitext(f)[-1] == os.path.splitext(p)[-1]: if len(f.split('.')[0]) == len(os.path.basename(p).split('.')[0]): path = '/'.join([os.path.dirname(p),os.path.basename(f)]) if os.path.isfile(path): fbxToCopy.append(path) #Write ''' for n in nuke.allNodes('Write'): if n.knob('file').value() not in writeList: if n.knob('disable').value() == False: if n.knob('file').value() != '': if os.path.isdir( os.path.dirname( n.knob('file').value() ) ): writeList.append(nuke.filenameFilter(n.knob('file').value())) ''' for p in writeList: if os.path.exists(os.path.dirname(p)): for f in os.listdir(os.path.dirname(p)): if os.path.splitext(f)[-1] == os.path.splitext(p)[-1]: if f.split('.')[0] == os.path.basename(p).split('.')[0]: path = '/'.join([os.path.dirname(p),os.path.basename(f)]) if os.path.isfile(path): writeToCopy.append(path) self.copyDic = {} for p in readToCopy: folder = os.path.dirname(p).split('/')[-1] + '/' if os.path.exists(LAYERS + folder) == False: os.makedirs(LAYERS + folder) self.copyDic[p] = [LAYERS + folder + os.path.basename(p),os.path.getsize(p)] for p in fbxToCopy: folder = os.path.dirname(p).split('/')[-1] + '/' if os.path.exists(FBX + folder ) == False: os.makedirs(FBX + folder) #shutil.copy( p , FBX + os.path.basename(p) ) self.copyDic[p] = [FBX + folder + os.path.basename(p),os.path.getsize(p)] for p in writeToCopy: folder = os.path.dirname(p).split('/')[-1] + '/' if os.path.exists(WRITE + folder) == False: os.makedirs(WRITE + folder) #shutil.copy( p , WRITE + folder + os.path.basename(p) ) self.copyDic[p] = [WRITE + folder + os.path.basename(p),os.path.getsize(p)] threading.Thread( None, self.action2 ).start()
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')
import os import sys import json import nuke def nuke_template(): t_template_file = sys.argv[1] t_des_file = sys.argv[2] t_write_path = sys.argv[3] t_source = sys.argv[4] t_source_info = json.loads( sys.argv[5] ) try: nuke.scriptOpen( t_template_file.replace("\\","/") ) except Exception,e: pass try: for t_node in nuke.allNodes(): t_node_type = t_node.Class() t_node_name = t_node.name() if t_node_type == "Read": t_node["file"].setValue(t_source.replace("\\","/")) t_node["first"].setValue(1) t_node["last"].setValue(int(t_source_info["FrameCount"])) t_node["origfirst"].setValue(1) t_node["origlast"].setValue(int(t_source_info["FrameCount"])) if t_node_type == "Write": t_node["file"].setValue( t_write_path.replace("\\","/") + "/" + os.path.basename(t_source.replace("\\","/")) ) nuke.scriptSaveAs(filename=t_des_file.replace("\\","/"), overwrite=1) except Exception,e: pass if __name__ == "__main__": nuke_template()
def save_file(self, filePath): nuke.scriptSaveAs(filename=filePath, overwrite=True) super(NukeSaver, self).save_recents(write_local_config=True) self.nuke_tools.set_environment(self.configReader, self.template, self.get_token_dict()) return True
import time import nuke sys.stdout.write((str(sys.argv[1]))) def flush_then_wait(): sys.stdout.flush() sys.stderr.flush() time.sleep(0.1) nuke.scriptOpen(sys.argv[1]) node = [nod for nod in nuke.allNodes() if not nod.Class() == 'Viewer' and not nod.Class() == 'BackdropNode'] total_nodes = len(node) for index, item in enumerate(node): try: progress = int(((index + 1) / total_nodes) * 100) item['disable'].setValue(True) sys.stdout.write('Disabled: ' + (item['name'].value())) sys.stderr.write("Total complete: {}%\n".format(progress)) flush_then_wait() except: pass new_workfile_name = nuke.root().name().split('.')[0] + '_disabled' + '.nk' nuke.scriptSaveAs(new_workfile_name, overwrite=1) sys.stdout.write(('File Saved: ' + new_workfile_name))
def _save(self): try: nuke.scriptSaveAs(overwrite=True) return True except: return False
def knobChanged(self, knob): if knob is self.projKnob: self.refresh_panel_with_project('proj_' + self.projKnob.value()) self.refresh_version_panel(self.projKnob.value(), self.epsKnob.value(), self.shotKnob.value(), self.account) self.version_check(self.projKnob.value(), self.epsKnob.value(), self.shotKnob.value(), self.account, self.verKnob.value()) if knob.name() == 'showPanel': if self.in_task == 'have': ''' Set default value with current task if this script in task ''' # get task info from fileName self.cur_task_info = self.get_task_info_from_file( os.path.basename(self.current_file_path)) # set Project Value self.projKnob.setValue(self.cur_task_info[0]) # refresh Panel self.refresh_panel_with_project('proj_' + self.projKnob.value()) # set default Panels self.epsKnob.setValue(self.cur_task_info[1]) self.shotKnob.setValue(self.cur_task_info[2]) self.refresh_version_panel(self.projKnob.value(), self.epsKnob.value(), self.shotKnob.value(), self.account) self.verKnob.setValue( self.vernum_check.findall(self.current_file_path)[0]) self.version_check(self.projKnob.value(), self.epsKnob.value(), self.shotKnob.value(), self.account, self.verKnob.value()) else: self.refresh_panel_with_project('proj_' + self.projKnob.value()) self.refresh_version_panel(self.projKnob.value(), self.epsKnob.value(), self.shotKnob.value(), self.account) self.version_check(self.projKnob.value(), self.epsKnob.value(), self.shotKnob.value(), self.account, self.verKnob.value()) if knob is self.epsKnob: self.shotKnob.setValues( getData.get_shot_list(self.jsData, 'proj_' + self.projKnob.value(), self.epsKnob.value())) self.refresh_version_panel(self.projKnob.value(), self.epsKnob.value(), self.shotKnob.value(), self.account) if knob is self.shotKnob: self.refresh_version_panel(self.projKnob.value(), self.epsKnob.value(), self.shotKnob.value(), self.account) if knob is self.verKnob or knob is self.shotKnob or knob is self.epsKnob: self.version_check(self.projKnob.value(), self.epsKnob.value(), self.shotKnob.value(), self.account, self.verKnob.value()) if knob is self.openFileButton: nuke.scriptOpen(self.get_filepath_from_knob()) self.hide() if knob is self.createMainVersionButton: self.next_mainversion(self.current_file_path) self.hide() if knob is self.upSubVersionButton: self.next_subversion(self.current_file_path) self.hide() if knob is self.createFirstVersionButton: first_version_path = self.get_filepath_from_knob() nuke.scriptSaveAs(first_version_path) temp_file_match = re.compile( r'^%s_%s_%s_cmp_yourName_v\d{3,6}.nk$' % (self.projKnob.value(), self.epsKnob.value(), self.shotKnob.value())) ver_dict = getData.script_version_info(self.projKnob.value(), self.epsKnob.value(), self.shotKnob.value(), self.account) if ver_dict['nukeScriptList']: # when have script already in this direction for script in ver_dict['nukeScriptList']: # when have template file if temp_file_match.match(script): try: nuke.scriptReadFile( os.path.dirname(first_version_path) + '/' + script) except RuntimeError: pass for node in nuke.allNodes(filter='Write'): if node.Class() == 'Write': temp_file_name = node['file'].getValue() node['file'].setValue( temp_file_name.replace( 'yourName', self.account)) nuke.scriptSave() self.hide() if knob is self.upMainVersionButton: self.next_mainversion(self.current_file_path) self.hide()
def _save_session(path): """ Save the current session to the supplied path. """ nuke.scriptSaveAs(path, True)
aConnection = [ [ 'Read1', 'ColorCorrect1', 'Dot3', 'Dot2', 'Dot1', 'Roto1', 'Premult1', 'Reformat2', 'Write4', 0 ], ['Dot2', 'Reformat3', 'Write5', 0], ['Dot4', 'Transform3', 'Reformat5', 'Write3', 0], [ 'Read2', 'ColorCorrect2', 'Dot6', 'Dot5', 'Transform1', 'Reformat1', 'Write1', 0 ], ['Dot7', 'Transform2', 'Reformat4', 'Write2', 0], ] # Connect the nodes based on the entries of aConnection for connection in aConnection: for i in range(1, len(connection) - 1): dNode[connection[i]].setInput(connection[-1], dNode[connection[i - 1]]) # TODO: Deleting file to create a new file. un comment when modifying nuke tree. import os try: os.unlink(dShot['FilePath']) except: pass nuke.scriptSaveAs(dShot['FilePath']) nuke.scriptExit() sys.exit(0) # Stops running from this point on.
def _convert(fromScript, toScript, overwrite): import nuke nuke.scriptOpen(fromScript) nuke.scriptSaveAs(toScript, overwrite) nuke.scriptClose()
def saveScene(self, origin, filepath): try: return nuke.scriptSaveAs(filename=filepath) except: return ""
def save_as(self, version): """"the save action for nuke environment uses Nukes own python binding """ # get the current version, and store it as the parent of the new version current_version = self.get_current_version() # first initialize the version path version.update_paths() # set the extension to '.nk' version.extension = '.nk' # set created_with to let the UI show Nuke icon in versions list version.created_with = self.name # set project_directory # self.project_directory = os.path.dirname(version.absolute_path) # create the main write node self.create_main_write_node(version) # replace read and write node paths # self.replace_external_paths() # create the path before saving try: os.makedirs(version.absolute_path) except OSError: # path already exists OSError pass # set frame range # if this is a shot related task set it to shots resolution is_shot_related_task = False shot = None from stalker import Shot for task in version.task.parents: if isinstance(task, Shot): is_shot_related_task = True shot = task break # set scene fps project = version.task.project self.set_fps(project.fps) if version.version_number == 1: if is_shot_related_task: # just set if the frame range is not 1-1 if shot.cut_in != 1 and shot.cut_out != 1: self.set_frame_range( shot.cut_in, shot.cut_out ) imf = shot.image_format else: imf = project.image_format # TODO: set the render resolution later # self.set_resolution( # imf.width, # imf.height, # imf.pixel_aspect # ) nuke.scriptSaveAs(version.absolute_full_path) if current_version: # update the parent info version.parent = current_version # update database with new version info DBSession.commit() return True
def saveUtility(spec, dbMeta={}): root = nuke.root() e = ueAssetUtils.getElement(spec) if e == {}: e = ueCreate.createElement(spec, dbMeta=dbMeta) v = ueCreate.createVersion(spec, dbMeta=dbMeta) spec.vers = v["version"] nkPath = v["path"] nkName = v["file_name"] f = os.path.join(nkPath, nkName+".nk") if root.knob("ueproj") == None: root.addKnob(nuke.String_Knob("ueproj", "project", spec.proj)) else: root.knob("ueproj").setValue(spec.proj) if root.knob("uegrp") == None: root.addKnob(nuke.String_Knob("uegrp", "group", spec.grp)) else: root.knob("uegrp").setValue(spec.grp) if root.knob("ueasst") == None: root.addKnob(nuke.String_Knob("ueasst", "asset", spec.asst)) else: root.knob("ueasst").setValue(spec.asst) if root.knob("ueclass") == None: root.addKnob(nuke.String_Knob("ueclass", "class", spec.elclass)) else: root.knob("ueclass").setValue(spec.elclass) if root.knob("uetype") == None: root.addKnob(nuke.String_Knob("uetype", "type", spec.eltype)) else: root.knob("uetype").setValue(spec.eltype) if root.knob("uename") == None: root.addKnob(nuke.String_Knob("uename", "name", spec.elname)) else: root.knob("uename").setValue(spec.elname) if root.knob("uevers") == None: root.addKnob(nuke.Int_Knob("uevers", "vers", spec.vers)) # Nuke bug? Passing a value into Int_Knob doesn't actually set the value # on the knob. Calling setValue explicitly to get around this. root.knob("uevers").setValue(spec.vers) else: root.knob("uevers").setValue(spec.vers) if root.knob("version_path") == None: root.addKnob(nuke.String_Knob("version_path", "version_path", nkPath)) else: root.knob("version_path").setValue(nkPath) nuke.scriptSaveAs(f) if "thumbnail" in v: source = os.path.join(os.getenv("ASST_ROOT"), "tmp", "ueSaveThumbs_"+str(v["thumbnail"])+".png") dest = os.path.join(os.getenv("PROJ_ROOT"), "var", "thumbs", spec.grp, spec.asst, nkName+".png") if not os.path.exists(os.path.dirname(dest)): ueFileUtils.createDir(os.path.dirname(dest)) ueFileUtils.moveFile(source, dest) nuke.tprint("Saved %s" % spec)
def _save_as(self, path): try: nuke.scriptSaveAs(filename=path, overwrite=True) return True except: return False
def publishAsset(n, assetName, content, comment, shot, currentTask): header = getHeaderKnob(n) if not currentTask: header.setMessage('Could not find current task', 'warning') else: publishProgress = nuke.ProgressTask('Publishing assets') publishProgress.setProgress(0) currentTaskId = currentTask.getId() assetType = n['ftrackassettype'].value() publishProgress.setMessage('Validating asset types') try: ftrack.AssetType(assetType) except ftrack.FTrackError: header.setMessage( 'No Asset type with short name "{0}" found. Contact your ' 'system administrator to add it.'.format(assetType), 'warning') return publishProgress.setMessage('Creating new version') asset = shot.createAsset(assetName, assetType) assetVersion = asset.createVersion(comment=comment, taskid=currentTaskId) if assetType in ['img', 'cam', 'geo', 'render']: if assetType == 'img': imgAsset = nukeassets.ImageSequenceAsset() publishedComponents = imgAsset.publishContent( content, assetVersion, progressCallback=publishProgress.setProgress) elif assetType == 'cam': camAsset = nukeassets.CameraAsset() publishedComponents = camAsset.publishContent( content, assetVersion, progressCallback=publishProgress.setProgress) elif assetType == 'geo': geoAsset = nukeassets.GeometryAsset() publishedComponents = geoAsset.publishContent( content, assetVersion, progressCallback=publishProgress.setProgress) elif assetType == 'render': renderAsset = nukeassets.RenderAsset() publishedComponents = renderAsset.publishContent( content, assetVersion, progressCallback=publishProgress.setProgress) if n['fscript'].value(): if n['fcopy'].value(): temporaryPath = HelpFunctions.temporaryFile(suffix='.nk') nuke.scriptSave(temporaryPath) mainPath = temporaryPath else: if nuke.Root().name() == 'Root': tmp_script = tempfile.NamedTemporaryFile(suffix='.nk') curScript = nuke.toNode("root").name() nuke.scriptSaveAs(tmp_script.name) mainAbsPath = tmp_script.name else: mainAbsPath = nuke.root()['name'].value() mainPath = mainAbsPath publishedComponents.append( FTComponent(componentname='nukescript', path=mainPath)) if publishedComponents: pubObj = FTAssetObject(assetVersionId=assetVersion.getId()) connector.Connector.publishAssetFiles( publishedComponents, assetVersion, pubObj, copyFiles=n['fcopy'].value(), progressCallback=publishProgress.setProgress) else: header.setMessage("Can't publish this assettype yet", 'info') return publishProgress.setMessage('Setting up version dependencies') dependencies = get_dependencies() if dependencies: for name, version in dependencies.items(): assetVersion.addUsesVersions(versions=version) assetVersion.publish() publishProgress.setProgress(100) header.setMessage('Asset published!')
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 """ # We need to see which mode of Nuke we're in. If this is Hiero or # Nuke Studio, then we have a separate scene operation routine to # use. We're checking that the "hiero_enabled" attribute exists # to ensure that this works properly with pre-v0.4.x versions of # the tk-nuke engine. If that one attribute exists, then we can be # confident that the "studio_enabled" attribute is also available, # so there's no need to check that. # # If there is ever a situation where Hiero- or Nuke Studio-specific # logic is required that doesn't also apply to the other, then this # conditional could be broken up between hiero_enabled and # studio_enabled cases that call through to Nuke Studio and Hiero # specific methods. engine = self.parent.engine if hasattr(engine, "hiero_enabled") and (engine.hiero_enabled or engine.studio_enabled): return self._scene_operation_hiero_nukestudio( operation, file_path, context, parent_action, file_version, read_only, **kwargs) # If we didn't hit the Hiero or Nuke Studio case above, we can # continue with the typical Nuke scene operation logic. 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 self.set_show_preferences(context) 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 execute(self, operation, file_path, context, parent_action, **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) :context: Context The context the file operation is being performed in. :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 :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 """ 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 == "prepare_new": #post setup--- commands = sgtk.platform.current_engine().commands #setting frame range with sync app sync_cmd = commands["Sync Frame Range with Shotgun"]["callback"] sync_cmd() #prompting for an initial save as save_as_cmd = commands["Shotgun Save As..."]["callback"] save_as_cmd() 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) #updating shotgun status print 'updating shotgun status' taskId=context.task['id'] sg=self.parent.shotgun data = {'sg_status_list':'ip' } sg.update("Task",taskId,data)
def _saveAs(self, filePath, format=None, *args, **kwargs): nuke.scriptSaveAs(filePath)