def tri_writeGizmo_update(): root = nuke.root() if 'tri_project_scene_id' not in root.knobs(): return if 'tri_project_xml_formats' not in root.knobs(): return (pName, pExt) = os.path.splitext(os.path.basename(root['name'].value())) pData = etree.fromstring(root['tri_project_xml_formats'].value()) for group in nuke.allNodes("Group", nuke.root()): if 'triwrite_gizmo' not in group.knobs(): continue resultNode = group.node('result') dailiesNode = group.node('dailies') #--- update results params filename = pName + pData.find('result').find('file').get('numbers') + pData.find('result').find('file').get('file_type') filename = nukenormpath(filename) oldfilename = os.path.basename(resultNode['file'].value()) resultNode['file'].setValue(resultNode['file'].value().replace(oldfilename, filename)) #--- update dailies params filename = pName + pData.find('dailies').find('file').get('numbers') + pData.find('dailies').find('file').get('file_type') filename = nukenormpath(filename) oldfilename = os.path.basename(dailiesNode['file'].value()) dailiesNode['file'].setValue(dailiesNode['file'].value().replace(oldfilename, filename)) pData = None
def onUserCreateCallback(): """ Populate defaults on creation of a DA_WriteMovieSlices node. """ if (nuke.thisNode().Class().endswith('DA_WriteMovieSlices')): nuke.thisNode().knob('first').setValue(nuke.root().knob('first_frame').value()) nuke.thisNode().knob('last').setValue(nuke.root().knob('last_frame').value())
def _register_version(self,fields,frames_path): """ Helper method to register publish using the specified publish info. """ sg_version_name='v'+str(fields['version']).zfill(3) startTime=int(nuke.root()['first_frame'].value()) endTime=int(nuke.root()['last_frame'].value()) args = { "code": sg_version_name, "project": self.parent.context.project, "entity": self.parent.context.entity, "sg_task": self.parent.context.task, "created_by": self.parent.context.user, "user": self.parent.context.user, "sg_path_to_frames": frames_path, "sg_first_frame": int(startTime), "sg_last_frame": int(endTime), "frame_count": int((endTime - startTime) + 1), "frame_range": "%d-%d" % (startTime,endTime), } # register publish; sg_data = self.parent.shotgun.create("Version", args) return sg_data
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 sendToAvconv(codec = 'dnxhd'): # Configuration renderSlug = False vcodec = { 'x264' : 'libx264 -pre baseline', 'dnxhd' : 'dnxhd -b 36M', } extension = '.mov' # set some variables fps = nuke.root().knob('fps').value() firstFrame = nuke.root().knob('first_frame').value() ss = 0 if renderSlug == True else secondsToStr(firstFrame/fps) # grabs the write node's file value and makes sure the path uses printf style filenames imgSeqPath = nukescripts.replaceHashes(nuke.filename(nuke.thisNode())) # generate mov path base, ext = os.path.splitext(os.path.basename(imgSeqPath)) movPath = os.path.dirname(os.path.dirname(imgSeqPath)) + '/' + re.sub('\.?%0\d+d$', '', base) + extension # make shell command enc = 'avconv -y -r %s -i \'%s\' -s \'hd1080\' -an -ss %s -vcodec %s -threads 0 \'%s\'' % (fps, imgSeqPath, ss, vcodec[codec], movPath) #print enc subprocess.Popen(shlex.split(enc), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def get_current_frame_range(self, engine): if engine == "tk-maya": import pymel.core as pm import maya.cmds as cmds current_in = cmds.playbackOptions(query=True, minTime=True) current_out = cmds.playbackOptions(query=True, maxTime=True) elif engine == "tk-nuke": import nuke current_in = nuke.root()["first_frame"].value() current_out = nuke.root()["last_frame"].value() elif engine == "tk-motionbuilder": from pyfbsdk import FBPlayerControl, FBTime lPlayer = FBPlayerControl() current_in = lPlayer.LoopStart.GetFrame() current_out = lPlayer.LoopStop.GetFrame() elif engine == "tk-softimage": import win32com xsi = win32com.client.Dispatch('XSI.Application') current_in = xsi.GetValue("PlayControl.In") current_out = xsi.GetValue("PlayControl.Out") elif engine == "tk-houdini": import hou current_in, current_out = hou.playbar.playbackRange() else: raise tank.TankError("Don't know how to get current frame range for engine %s!" % engine) return (current_in, current_out)
def __init__(self): scriptData = sb_convertTracker_Data() nukescripts.PythonPanel.__init__(self, '{0} v{1}'.format(scriptData["scriptName"], scriptData["scriptVersion"])) trackerList = getTrackerNames(nuke.selectedNode()) self.bl = nuke.Enumeration_Knob("bl", "bottom left", trackerList) self.br = nuke.Enumeration_Knob("br", "bottom right", trackerList) self.ur = nuke.Enumeration_Knob("ur", "upper right", trackerList) self.ul = nuke.Enumeration_Knob("ul", "upper left", trackerList) self.div1 = nuke.Text_Knob("divider1", "") self.ff = nuke.Int_Knob("ff", "first frame") self.lf = nuke.Int_Knob("lf", "last frame") self.ref = nuke.Int_Knob("rf", "reference frame") self.stf = nuke.PyScript_Knob('stf', "Set frame") self.div2 = nuke.Text_Knob("divider2", "") self.output = nuke.Enumeration_Knob("output", "output", ["CornerPin Match-move (Plane)", "CornerPin Stabilize (Plane)", "CornerPin Match-move (Distort)", "CornerPin Stabilize (Distort)", "RotoPaint", "SplineWarp", "GridWarp"]) self.div3 = nuke.Text_Knob("divider3", "") self.createBtn = nuke.PyScript_Knob("createBtn", "create node") for i in [ self.output, self.div1, self.bl, self.br, self.ur, self.ul, self.div2, self.ff, self.lf, self.ref, self.stf, self.div3, self.createBtn]: self.addKnob(i) # Set values. self.bl.setValue(0) self.br.setValue(1) self.ur.setValue(2) self.ul.setValue(3) self.ff.setValue( int( nuke.root()["first_frame"].value() ) ) self.lf.setValue( int( nuke.root()["last_frame"].value() ) ) self.ref.setValue( int( nuke.root()["frame"].value() ) )
def readFromWrite(): nodes = nuke.selectedNodes() if len(nodes) < 1: print('No nodes selected') else : foundWrites = False writeNodes = [] for node in nodes: if node.Class() == 'Write': writeNodes.append(node) foundWrites = True if foundWrites == True: # we found some writes for node in writeNodes: nodeRead = nuke.nodes.Read() # create a read node nodeRead['file'].setValue(nuke.filename(node)) #set the filename if node['use_limit'].getValue() == 1: #check to see if there is a range and set the values in the read node nodeRead['first'].setValue(int(node['first'].getValue())) nodeRead['last'].setValue(int(node['last'].getValue())) else: # no range on the write? take a stab at using the range from the script value nodeRead['first'].setValue(int(nuke.root()['first_frame'].getValue())) nodeRead['last'].setValue(int(nuke.root()['last_frame'].getValue())) nodeRead.setXpos(node.xpos()) #let's set the position nodeRead.setYpos(node.ypos()+50) nodeRead['premultiplied'].setValue(node['premultiplied'].getValue()) # use premult if checked nodeRead['raw'].setValue(node['raw'].getValue()) # use raw if checked else: print('No Writes Found in Node Selection')
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 bakeExpressions(startFrame = nuke.root().firstFrame(), endFrame = nuke.root().lastFrame()): ''' Bakes all expression-driven knobs/knob components to keyframes over given input range To Do: - Add support for multiple views ''' if not nuke.selectedNodes(): return for node in nuke.selectedNodes(): for knob in node.knobs().values(): if knob.hasExpression(): if knob.singleValue(): aSize = 1 else: aSize = knob.arraySize() for index in range(aSize): if knob.hasExpression(index): anim = knob.animation(index) f = startFrame while f <= endFrame: knob.setValueAt(anim.evaluate(f), f, index) f += 1 knob.setExpression("curve", index) if knob.animation(index).constant(): knob.clearAnimated(index)
def browseDir(action): if (nuke.root().name() == 'Root') and (action != 'Path'): nuke.message('You need to save the Nuke script first!') else: # Get full path to script scriptPath = nuke.callbacks.filenameFilter( nuke.root().name() ) # Divide up the paths scriptPathSplitted = str.split( scriptPath, '/' ) # Reset openMe = '' if action == 'scripts': for i in range(0, (len(scriptPathSplitted)-1) ): openMe = openMe + scriptPathSplitted[i] + '/' elif action == 'sequence': for i in range(0, (len(scriptPathSplitted)-4) ): openMe = openMe + scriptPathSplitted[i] + '/' elif action == 'shot': for i in range(0, (len(scriptPathSplitted)-3) ): openMe = openMe + scriptPathSplitted[i] + '/' launch(openMe)
def imageSaver(): sel = nuke.selectedNodes() if len(sel)<1: nuke.message("please select a node to save an image from") elif len(sel)>1: nuke.message("please select only one node") elif len(sel)==1: p = createPanel() if p.show(): if p.value("render to")=="scriptPath": if nuke.root().name()=="Root" or nuke.root().name() == "": nuke.message("You haven't set up your project. Please make sure to set it up first if you want to save the capture to your script.") return else: renderTo = "/".join(nuke.root().name().split("/")[:-1])+"/" else: renderTo = os.path.expanduser("~/Desktop/") filetype = p.value("filetype") saveImage(sel,renderTo,filetype)
def __init__(self, cameraNode, retimeNode): nukescripts.PythonPanel.__init__(self, 'RetimeCamera', 'org.magpie.retimecamera') # INSTANCE VARIABLES global FIRST_FRAME global LAST_FRAME FIRST_FRAME = nuke.root().firstFrame() LAST_FRAME = nuke.root().lastFrame() # NODE-SPECIFIC INSTANCE VARIABLES self.cameraNode = cameraNode self.cameraNode_Name = cameraNode.name() self.retimeNode = retimeNode self.retimeNode_Name = retimeNode.name() # RETIME METHOD VARIABLE ASSIGNMENT # Depending on type of retime (legacy OFlow vs N9 OFlow and Kronos), these must change if self.retimeNode.Class() == 'OFXuk.co.thefoundry.time.oflow_v100': self.retime_OutputSpeed = 'curve(' + self.retimeNode_Name + '.timingSpeed)' self.retime_Frame = 'curve(' + self.retimeNode_Name + '.timingFrame)' # pulldown selection box self.timingMethodPulldown = nuke.Enumeration_Knob('', '', ['Speed', 'Source Frame']) else: self.retime_OutputSpeed = 'curve(' + self.retimeNode_Name + '.timingOutputSpeed)' self.retime_InputSpeed = 'curve(' + self.retimeNode_Name + '.timingInputSpeed)' self.retime_Frame = 'curve(' + self.retimeNode_Name + '.timingFrame2)' # pulldown selection box self.timingMethodPulldown = nuke.Enumeration_Knob('', '', ['Output Speed', 'Input Speed', 'Frame']) # CREATE KNOBS # DIVIDERS self.div1 = nuke.Text_Knob('div1', '', '') self.div2 = nuke.Text_Knob('div2', '', '') # TEXT self.toolName = nuke.Text_Knob('', '', 'Retime Camera v1.1') self.description = nuke.Text_Knob('', '', 'Creates a new retimed camera from ' + self.retimeNode_Name + ' and ' + self.cameraNode_Name + ' nodes.') self.pulldownText = nuke.Text_Knob('', '', 'Select timing method - ') # PULLDOWN SELECTION BOX # keep pull-downs on same line self.pulldownText.clearFlag(nuke.STARTLINE) self.timingMethodPulldown.clearFlag(nuke.STARTLINE) # add button # self.execute = nuke.PyScript_Knob('', 'Create Retimed Camera', '') # populate knob list # self.knobSet = [self.toolName, self.description, self.div1, self.pulldownText, self.timingMethodPulldown, self.div2, self.execute] # add knobs # for knob in range(len(self.knobSet)): self.addKnob(self.knobSet[knob]) # add cancel button # if self.cancelButton is None: self.cancelButton = nuke.Script_Knob('Cancel') self.addKnob(self.cancelButton)
def process(self, instance): # getting job data job_data = {} if instance.has_data("deadlineData"): job_data = instance.data("deadlineData")["job"].copy() # setting extra info key values extra_info_key_value = {} if "ExtraInfoKeyValue" in job_data: extra_info_key_value = job_data["ExtraInfoKeyValue"] extra_info_key_value["DraftExtraArgs"] = "" extra_info_key_value["DraftVersion"] = "" extra_info_key_value["DraftUsername"] = "" extra_info_key_value["DraftUploadToShotgun"] = "False" extra_info_key_value["DraftEntity"] = "" if "nuke" in pyblish.api.current_host(): import nuke width = nuke.root().format().width() height = nuke.root().format().height() else: width = None height = None extra_info_key_value["DraftFrameWidth"] = width extra_info_key_value["DraftFrameHeight"] = height job_data["ExtraInfoKeyValue"] = extra_info_key_value data = instance.data("deadlineData") data["job"] = job_data instance.set_data("deadlineData", value=data)
def process(self, instance): # getting job data job_data = {} if instance.has_data('deadlineData'): job_data = instance.data('deadlineData')['job'].copy() # setting extra info key values extra_info_key_value = {} if 'ExtraInfoKeyValue' in job_data: extra_info_key_value = job_data['ExtraInfoKeyValue'] extra_info_key_value['DraftExtraArgs'] = '' extra_info_key_value['DraftVersion'] = '' extra_info_key_value['DraftUsername'] = '' extra_info_key_value['DraftUploadToShotgun'] = 'False' extra_info_key_value['DraftEntity'] = '' if 'nuke' in pyblish.api.current_host(): import nuke width = nuke.root().format().width() height = nuke.root().format().height() else: width = None height = None extra_info_key_value['DraftFrameWidth'] = width extra_info_key_value['DraftFrameHeight'] = height job_data['ExtraInfoKeyValue'] = extra_info_key_value data = instance.data('deadlineData') data['job'] = job_data instance.set_data('deadlineData', value=data)
def syncFrameRangeWithShotgun(): '''Gets the current frame range from Shotgun and pushes the data to nuke. Requires that you have certain parameters set (see below for variables) THese parameters are pretty standard in Shotgun but you can customize below. ''' inFrame = 'sg_cut_in' outFrame = 'sg_cut_out' sg = shotgunUtils.genericUtils() scriptName = nuke.root()['name'].value() if scriptName == '' : nuke.message ('You need to save this first!') else: projectText = scriptName.split('/')[2] shotText = scriptName.split('/')[5] project = sg.project(projectText) shot = sg.shot(project, shotText) errorMessage = [] if inFrame not in shot: errorMessage.append('%s is not present in your Shotgun config' % inFrame) if outFrame not in shot: errorMessage.append('%s is not present in your Shotgun config' % outFrame) if len(errorMessage) > 0: errors = '' for message in errorMessage: errors = '%s%s\n' % (errors, message) nuke.message (errors) else: nuke.root()['first_frame'].setValue(shot[inFrame]) nuke.root()['last_frame'].setValue(shot[outFrame]) nuke.message ('Set in and out frames to %s and %s' % (shot[inFrame], shot[outFrame]))
def process(self, context): # storing plugin data plugin_data = {'EnforceRenderOrder': True} plugin_data['NukeX'] = nuke.env['nukex'] plugin_data['Version'] = nuke.NUKE_VERSION_STRING.split('v')[0] # creating instances per write node for node in nuke.allNodes(): if node.Class() == 'Write': instance = context.create_instance(name=node.name()) instance.set_data('family', value='deadline.render') instance.add(node) output = node['file'].getValue() instance.set_data("publish", not node['disable'].getValue()) # setting job data job_data = {} if instance.has_data('deadlineData'): job_data = instance.data('deadlineData')['job'].copy() output_file = output if '%' in output_file: padding = int(output_file.split('%')[1][0:2]) padding_string = '%0{0}d'.format(padding) tmp = '#' * padding output_file = output_file.replace(padding_string, tmp) job_data['OutputFilename0'] = output_file # frame range start_frame = int(nuke.root()['first_frame'].getValue()) end_frame = int(nuke.root()['last_frame'].getValue()) if node['use_limit'].getValue(): start_frame = int(node['first'].getValue()) end_frame = int(node['last'].getValue()) frames = '%s-%s\n' % (start_frame, end_frame) instance.data['firstFrame'] = start_frame instance.data['endFrame'] = end_frame instance.set_data('deadlineFrames', value=frames) # setting plugin data plugin_data = plugin_data.copy() plugin_data['WriteNode'] = node.name() current_file = instance.context.data['currentFile'] data = {'job': job_data, 'plugin': plugin_data, 'order': int(node['render_order'].value()), 'auxiliaryFiles': [current_file]} instance.set_data('deadlineData', value=data) # adding ftrack data to activate processing instance.set_data('ftrackComponents', value={}) instance.set_data('ftrackAssetType', value='img')
def submitNukeCmdline_render(executeNodes=''): '''launch the qubegui submit dialog for nuke''' allNodes = nuke.allNodes() allNodes_Write = [str(i.name()) for i in allNodes if i.Class() == 'Write'] allNodes_Viewer = [str(i.name()) for i in allNodes if i.Class() == 'Viewer'] nuke.tprint(allNodes_Write) nuke.tprint(allNodes_Viewer) range = '%s-%s' % (int(nuke.animationStart()), int(nuke.animationEnd())) rangeInc = int(nuke.animationIncrement()) if rangeInc > 1: range += 'x%s' % rangeInc submitDict = { 'name' : 'nuke '+os.path.basename(str(nuke.root().name())), 'prototype' : 'cmdrange', 'env': {'NUKE_PATH': os.environ['NUKE_PATH']}, 'priority': 500, 'cpus': 10, 'reservations': 'global.nuke=1,host.processors=1', 'groups': 'RENDERBOX', 'package' : { 'simpleCmdType': 'Nuke (cmdline)', 'script': str(nuke.root().name()), 'range' : range, 'executeNodes' : executeNodes, 'allNodes_Write' : ','.join(allNodes_Write), 'allNodes_Viewer' : ','.join(allNodes_Viewer), 'executable': 'C:\\Program Files\\Nuke9.0v5\\Nuke9.0.exe', } } return launchgui(submitDict=submitDict)
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 submitNukeCmdline_render(executeNodes=''): '''launch the qubegui submit dialog for nuke''' allNodes = nuke.allNodes() allNodes_Write = [str(i.name()) for i in allNodes if i.Class() == 'Write'] allNodes_Viewer = [str(i.name()) for i in allNodes if i.Class() == 'Viewer'] scenefile = '[NUKE NOPIPE] %s' % os.path.basename(str(nuke.root().name())) nuke.tprint(allNodes_Write) nuke.tprint(allNodes_Viewer) range = '%s-%s' % (int(nuke.animationStart()), int(nuke.animationEnd())) rangeInc = int(nuke.animationIncrement()) if rangeInc > 1: range += 'x%s' % rangeInc submitDict = { 'name' : scenefile, 'prototype' : 'cmdrange', 'package' : { 'simpleCmdType': 'Nuke (cmdline)', 'script': str(nuke.root().name()), 'range' : range, 'executeNodes' : executeNodes, 'allNodes_Write' : ','.join(allNodes_Write), 'allNodes_Viewer' : ','.join(allNodes_Viewer), 'executable' : '/atomo/apps/linux/x86_64/nuke/8.0v3/Nuke8.0', }, 'reservations' : 'host.processors=1+,license.nuke', 'groups' : 'pipe', 'cpus' : 6, 'omithosts' : 'rhradec.local', 'env': {'FOUNDRY_LICENSE_FILE':'[email protected]','NUKE_PATH':'/atomo/pipeline/tools/nuke/script:/atomo/pipeline/tools/nuke/gizmo','NUKE_TEMP_DIR':'/tmp/nuke_farm'} } return launchgui(submitDict=submitDict)
def testLensDistortAgainstLensDistortOp(self): """Test that the output of the Cortex LensDistortOp and the LensDistort node are the same.\n""" paths = self.__paths() for p in paths.keys(): self.assertTrue(os.path.exists(paths[p])) outputPath = self.__outputPath() if os.path.exists(outputPath): os.remove(outputPath) # Set the default format to be something fun. nuke.root()["format"].fromScript("1144 862 0 0 1144 862 2 CortexTestAlexaProxyAnamorphic(2.66)") r = nuke.createNode("Read") # Create a LensDistort node. l = nuke.createNode("ieLensDistort") l["mode"].setValue(IECore.LensModel.Undistort) l.setInput(0, r) # Set the parameters of the lens distort node. l["lensFileSequence"].fromScript(os.path.abspath("test/IECore/data/StandardRadialLens.cob")) # Create a write node. w = nuke.createNode("Write") w.setInput(0, l) w["file"].setText(outputPath) # Create the op that we will compare the result of the nuke LensDistort node with. lensDistortOp = IECore.LensDistortOp() lensDistortOp["mode"].setValue(IECore.LensModel.Undistort) lensDistortOp["lensModel"].setValue(self.__testLens()) for path in paths.keys(): # Update the read node. r["file"].setText(paths[path]) if path == "path": # When the format is the same as the data window, nuke doesn't create a black border around the image. # As a result, we shouldn't create one using our LensDistortOp either. lensDistortOp["boundMode"].setValue(IECore.WarpOp.BoundMode.Clamp) else: lensDistortOp["boundMode"].setValue(IECore.WarpOp.BoundMode.SetToBlack) # Write out the result of the LensDistort so that we can compare it to the output of the cortex op. nuke.execute(w, 1, 1) img = IECore.Reader.create(paths[path]).read() lensDistortOp["input"].setValue(img) cortexImg = lensDistortOp() nukeImg = IECore.Reader.create(outputPath).read() # Assert that the two images are almost identical. # We expect a little bit of error as the cortex op uses a different sampling filter to the nuke node. imageDiffOp = IECore.ImageDiffOp() imageDiffOp["alignDisplayWindows"].setValue(True) res = imageDiffOp(imageA=cortexImg, imageB=nukeImg) self.assertFalse(res.value)
def exportObj(self, filePy, objects, filePath, objPath): objPathList = [] filePy.write("# importing obj files...\n\n") for node in objects: for i in nuke.allNodes(): i['selected'].setValue(0) print "processing "+node.name()+" ..." node['selected'].setValue(1) writeObj = nuke.createNode('WriteGeo', inpanel=False) writeObj['name'].setValue(node.name()+"_export") writeObj['file'].setValue(objPath+node.name()+".obj") writeObj['file_type'].setValue('obj') # writeObj['views'].setValue('main') objPathList.append(objPath+node.name()+".obj") nuke.execute(writeObj, int(nuke.root()['first_frame'].getValue()), int(nuke.root()['first_frame'].getValue())) for i in nuke.allNodes(): i['selected'].setValue(0) writeObj['selected'].setValue(1) nukescripts.node_delete() for object in objPathList: filePy.write("cmds.file('"+object+"', i = True, type = 'OBJ', ra = True)\n") filePy.write("\n") filePy.write("# make group of all the *_Mesh nodes ...\n\n") filePy.write("cmds.select('*_Mesh')\n") filePy.write("cmds.group(name = 'geo_GRP')\n\n") filePy.write("# renaming the files without '_Mesh' ...\n\n") filePy.write("meshes = cmds.ls('*_Mesh')\n") filePy.write("for node in meshes:\n") filePy.write(" cmds.rename(node, node[-0:-5])\n\n")
def pasteSelected(verbose=False): numViews=len(nuke.views()) offset=getOffset(False) keysList=[] nuke.root().begin() for node in nuke.allNodes(): if node.Class() not in exclusionList: nodeAnimated=isNodeAnimated(node) if nodeAnimated : for knob in node.knobs().values(): if knob.isAnimated(): try: aSize = knob.arraySize() for index in range(aSize): for vues in range(numViews+1): anim = knob.animation(index,vues) numKeys=anim.size() if numKeys: #step through the keys - check if they are selected then paste the values from timebar onwards for i in range(numKeys): keySelected= (anim.keys()[i].selected) if keySelected: keyVals= (anim.keys()[i].x, anim.keys()[i].y) if verbose: print ('keySelected: '+str(keySelected)+' keyvalues: '+str(keyVals)+' offset: '+str(offset)) anim.setKey(keyVals[0]+offset,keyVals[1]) keysList.append((keyVals[0]+offset,keyVals[1])) except: continue
def magicWrite(): #GET CURRENT SCRIPT DIR scriptDir = os.path.dirname ( nuke.root().knob("name").getValue() ) #print scriptDir #GET CURRENT COMPNAME AND COMPPATH compPath, compName = os.path.split(nuke.root().name()) print compPath print compName #USE REG EXPR TO CHECK SCRIPTNAME AND POPULATE match = re.match('^(\w+)_(\w+)_(\w+)_(\w+)_(v\d+)_(\w+)_(\w+)\.nk', compName) if match: projectShort, film, sequenceName, shotName, version, note, initials = match.groups() #print match.groups() #CREATE COMP WRITE NAME folderVersion = version #writeOutName = projectShort + '_' + film + '_' + sequenceName + '_' + shotName + '.' + padding + '.' + fileFormat writeOutName = projectShort + '_' + film + '_' + sequenceName + '_' + shotName #print writeOutName #GET RENDER DIR /compOut renderPath = scriptDir.replace("NukeScript", "compOut") #print renderPath #CREATE COMP OUT PATH AND FOLDER TO BE CREATED BEFORE RENDER AS CALLBACK compOut = renderPath + '/' + folderVersion + '/' + writeOutName #nuke.tprint(compOut) return compOut
def create_projection_alley_panel(): if not ensure_camera_selected(nuke.selectedNode()): return p = nukescripts.panels.PythonPanel("Create projection alley") p.addKnob(nuke.Int_Knob("start", "First frame to project")) p.knobs()["start"].setValue(int(nuke.root()["first_frame"].getValue())) p.addKnob(nuke.Int_Knob("finish", "Last frame to project")) p.knobs()["finish"].setValue(int(nuke.root()["last_frame"].getValue())) p.addKnob(nuke.Int_Knob("step", "Step (project every N frames)")) p.knobs()["step"].setValue(int(nuke.root().fps())) k = nuke.Boolean_Knob("backwards", "Layer last frame to first frame") k.setFlag(nuke.STARTLINE) k.setTooltip( "Projected frames are layered first to last (last frame comes on top). When checked the first frames will come out on top" ) p.addKnob(k) k = nuke.Boolean_Knob("crop", "Crop the projections to bbox") k.setFlag(nuke.STARTLINE) k.setTooltip("Use this with caution if you use lens distortion that stretches outside of the format") p.addKnob(k) k = nuke.Boolean_Knob("link", "Create linked cameras") k.setTooltip("Creates a linked multicam rig that will update if you change the camera path") k.setFlag(nuke.STARTLINE) p.addKnob(k) result = p.showModalDialog() if result == 0: return # Canceled start = p.knobs()["start"].value() finish = p.knobs()["finish"].value() istep = p.knobs()["step"].value() frame_numbers = list(range(start, finish, istep)) link = False crop = False if finish not in frame_numbers: frame_numbers.append(finish) # If the step is higher and we somehow to not get the last frame for sure if p.knobs()["backwards"].value(): frame_numbers.reverse() if p.knobs()["crop"].value(): crop = True if p.knobs()["link"].value(): link = True group = create_projection_alley(nuke.selectedNode(), frame_numbers, crop, link) group["label"].setValue("Cam prj f: %d to: %d every: %d" % (start, finish, istep)) group.setName("ProjectionAlley")
def setShot(self, shot): try: scene = str(shot.split("_")[0])+"_"+str(shot.split("_")[1]) except: scene = 'n/a' if not shot == 'n/a': try: #cameraGrp = self.node.knob("grpS_"+shot) camera = nuke.toNode(self.job+'_'+shot+'_renderCamera') #self.node.knob('cameraName').setValue(shot) except: pass try: version = camera.knob('versionHub').value() except: version = 'n/a' try: self.cameraSwitch.setInput(0, camera) except: pass if shot == 'n/a': version = 'n/a' #self.cameraSwitch.setInput(0) self.node.knob('shotList').setValue(shot) #set the timerange timeRange = hubUtils.getShotTimeRangeInfo(shot, scene, hubUtils.HubShotTimeRange.WORKING)['workFrameRange'] if timeRange in ['n/a', 'n/a ', 'n/a - n/a', 'n/a-n/a']: try: camera = nuke.toNode(self.job+'_'+shot+'_renderCamera') label = camera.knob('label').value() if label: timeRange = str(label) except: pass try: self.node.knob('actualCamera').setValue("<FONT COLOR=\"#7777EE\"> v"+version+" : "+timeRange+"<\FONT>") self.node.knob('txt_'+shot).setValue("handles: <FONT COLOR=\"#7777EE\">"+timeRange+"<\FONT>") except: pass if not timeRange in ['n/a', 'n/a ', 'n/a - n/a', 'n/a-n/a']: firstFrame, lastFrame = timeRange.split('-')[0], timeRange.split('-')[1] if not firstFrame == 'n/a' and not lastFrame == 'n/a': # set root frame range nuke.root().knob('first_frame').setValue(int(firstFrame)) nuke.root().knob('last_frame').setValue(int(lastFrame)) # if the current frame is not in the frame range set frame at the begining of the shot if nuke.frame() not in range(int(firstFrame), int(lastFrame)): nuke.frame(int(firstFrame))
def setFrameRangeFromSel(): """set the timeline with the handles of the selected node.""" sel = nuke.selectedNodes() if sel: nuke.root()['first_frame'].setValue(sel[0]['first'].getValue()) nuke.root()['last_frame'].setValue(sel[0]['last'].getValue()) else: nuke.message("please select one node.")
def bakePivotPoint(self, rotoLayer, trkNode_centerVals): self.firstFrame = nuke.root().firstFrame() self.lastFrame = nuke.root().lastFrame() for frame in range(self.firstFrame, self.lastFrame + 1): self.trkNode_xPpVal = trkNode_centerVals.getValueAt(frame)[0] self.trkNode_yPpVal = trkNode_centerVals.getValueAt(frame)[1] rotoLayer.getTransform().getPivotPointAnimCurve(0).addKey(frame, self.trkNode_xPpVal) rotoLayer.getTransform().getPivotPointAnimCurve(1).addKey(frame, self.trkNode_yPpVal)
def bakeTranslate(self, rotoLayer, trkNode_transVals): self.firstFrame = nuke.root().firstFrame() self.lastFrame = nuke.root().lastFrame() for frame in range(self.firstFrame, self.lastFrame + 1): self.trkNode_xTransVal = trkNode_transVals.getValueAt(frame)[0] self.trkNode_yTransVal = trkNode_transVals.getValueAt(frame)[1] rotoLayer.getTransform().getTranslationAnimCurve(0).addKey(frame, self.trkNode_xTransVal) rotoLayer.getTransform().getTranslationAnimCurve(1).addKey(frame, self.trkNode_yTransVal)
def rrSubmit_fillGlobalSceneInfo(newJob): newJob.version = nuke.NUKE_VERSION_STRING newJob.software = "Nuke" newJob.sceneOS = getOSString() newJob.sceneName = nuke.root().name() newJob.seqStart = nuke.root().firstFrame() newJob.seqEnd = nuke.root().lastFrame() newJob.imageFileName = ""
def submitJob(jobName, priority, frameList, selectedNode): scriptPath = nuke.root().name() if nukeVersion < 13: temporaryDirectory = tempfile.mkdtemp() else: # Create jobInfo and pluginInfo file temporaryDirectory = tempfile.TemporaryDirectory() # Get environment value of deadline path deadlinePath = os.getenv('DEADLINE_PATH') try: # Setting job properties if nukeVersion < 13: jobInfoPath = os.path.join(temporaryDirectory, "job_info.txt") else: jobInfoPath = os.path.join(temporaryDirectory.name, "job_info.txt") jobInfo = open(jobInfoPath, "w+") jobInfo.write('Plugin=Nuke\n' + 'Frames=' + frameList + '\n' + 'Priority=' +str(priority) + '\n' + 'Name=' + jobName + '\n' + 'Department=Compositing' ) jobInfo.seek(0) jobInfo.close() # Setting plugin properties if nukeVersion < 13: pluginInfoPath = os.path.join(temporaryDirectory, "plugin_info.txt") else: pluginInfoPath = os.path.join(temporaryDirectory.name, "plugin_info.txt") pluginInfo = open(pluginInfoPath, "w+") pluginInfo.write('Version=' + str(nukeVersion) + '\n' + 'WriteNode='+ selectedNode + '\n' + 'SceneFile='+ scriptPath ) pluginInfo.seek(0) pluginInfo.close() # Creating deadline command for submission deadlineCommand = "\"" + os.path.join(deadlinePath, 'deadlinecommand') + "\" " + jobInfoPath + " " + pluginInfoPath # Submission to deadline deadlineExecute = check_output(deadlineCommand, shell=True).decode() nuke.message(deadlineExecute) except Exception as exception: nuke.message("An error occured.\n" + str(exception)) # Making sure temp directory is removed finally: if nukeVersion < 13: shutil.rmtree(temporaryDirectory)
def updateVersion(): allReadnodes = nuke.allNodes('Read', group=nuke.root()) for n in allReadnodes: oldf = n['file'].getValue() oldchars = re.findall('_v\d+', oldf) if len(oldchars) >= 1: oldchar = oldchars[0] newchar = oldchar[:-1] + str(int(float(oldchar[-1]) + 1)) newf = oldf.replace(oldchar, newchar) newdir = os.path.dirname(newf) if os.path.isdir(newdir): n['file'].setValue(newf)
def buildCompScriptFromCurrentScript(): currentCompScript = nuke.root().name() currentDir = os.path.dirname(currentCompScript) fileList = [ file for file in os.listdir(currentDir) if "layer_order.yml" in file ] if fileList: layerOrderFile = os.path.join(currentDir, fileList[0]) currentCompScript = os.path.join(currentCompScript, "comp.nk") buildCompScript(layerOrderFile, currentCompScript, True) else: nuke.message( "Could not find layer-order.yml in the current comp directory!")
def logNimRender(writeNode=None): # Use this function by adding the following command to a writeNIM node's afterRender Python hook # # import nim_tools; nim_tools.logNimRender(nuke.thisNode()) # # You will need to set the frame range on the writeNIM node to match that of your output range # Currently this function is hardcoded to a single elementTypeID until a dropdown picker is added to the writeNIM node if writeNode is not None: print "Logging Render to NIM" import nuke import nim_core.nim_api as nimAPI shotID = nuke.root().knob('nim_shotID').getValue() #taskTypeID = nuke.root().knob('nim_taskID').getValue() #taskID = 15221 #tmp - hard coded till elementTypeID can be read from node elementTypeID = 1 #tmp - hard coded till elementTypeID can be read from node nimFolder = writeNode.knob('nimFolder').getValue() nimFileName = writeNode.knob('nimFilename').getValue() nimPath = writeNode.knob('nimPath').getValue() startFrame = writeNode.knob('first').getValue() endFrame = writeNode.knob('last').getValue() handles = 0 isPublished = False folderPath = nimPath + "/" + nimFolder # Below commented out till taskID and elementTypeID can be read from node ''' result = nimAPI.add_render(taskID=taskID, renderName=nimFolder) if result['success'] == 'true': #nimAPI.upload_renderIcon(renderID=result['ID'],img='/path/to/icon.jpeg') nimAPI.add_element( parent='render', parentID=result['ID'], \ path=nimPath, name=nimFileName, \ typeID=elementTypeID, \ startFrame=startFrame, endFrame=endFrame, \ handles=handles, isPublished=isPublished ) else : print "Failed to add Render" ''' nimAPI.add_element( parent='shot', parentID=shotID, \ path=folderPath, name=nimFileName, \ typeID=elementTypeID, \ startFrame=startFrame, endFrame=endFrame, \ handles=handles, isPublished=isPublished ) return
def set_workspace(self, directory): import nuke from construct_ui import resources ctx = construct.get_context() fav_icon = resources.path(':/brand/construct_icon-white-on-black') favs = ['project', 'sequence', 'shot', 'asset', 'workspace'] for fav in favs: fav_name = fav.title() nuke.removeFavoriteDir(fav_name) entry = ctx[fav] if entry: directory = entry.path nuke.addFavoriteDir(fav_name, directory=directory, type=(nuke.IMAGE | nuke.SCRIPT | nuke.GEO), icon=fav_icon, tooltip=directory) os.chdir(directory) nuke.root()['project_directory'].setValue(directory)
def process(self, context): asset_data = io.find_one({"type": "asset", "name": api.Session["AVALON_ASSET"]}) self.log.debug("asset_data: {}".format(asset_data["data"])) instances = [] # creating instances per write node for node in nuke.allNodes(): try: if node["disable"].value(): continue except Exception: continue # get data from avalon knob avalon_knob_data = get_avalon_knob_data(node) if not avalon_knob_data: continue if avalon_knob_data["id"] != "pyblish.avalon.instance": continue subset = avalon_knob_data.get("subset", None) or node["name"].value() # Create instance instance = context.create_instance(subset) instance.add(node) instance.data.update({ "subset": subset, "asset": os.environ["AVALON_ASSET"], "label": node.name(), "name": node.name(), "subset": subset, "family": avalon_knob_data["family"], "avalonKnob": avalon_knob_data, "publish": node.knob('publish').value(), "handles": int(asset_data["data"].get("handles", 0)), "step": 1, "fps": int(nuke.root()['fps'].value()) }) # if node.Class() == "Write": # instance.data["families"] = [avalon_knob_data["families"]] self.log.info("collected instance: {}".format(instance.data)) instances.append(instance) context.data["instances"] = instances self.log.debug("context: {}".format(context))
def set_project_settings(self): """Set nuke project settings based reset sequence and shot """ logging.info( "Setting Project Settings: Seq: {0}, Shot: {1}, First frame: {2}, Last frame: {3}".format ( self.ani_vars.seq_name, self.ani_vars.shot_name, self.ani_vars.first_frame, self.ani_vars.last_frame ) ) nuke.root()['seq'].setValue(self.ani_vars.seq_name) nuke.root()['shot'].setValue(self.ani_vars.shot_name) nuke.root()['first_frame'].setValue(int(self.ani_vars.first_frame)) nuke.root()['last_frame'].setValue(int(self.ani_vars.last_frame))
def shuffleAll(): nuke.root() read = nuke.Root().selectedNode() layer = nuke.layers(read) for i in layer: if i == 'rgb' or 'rgba' or 'alpha': try: layer.remove('rgb') layer.remove('rgba') layer.remove('alpha') except: s = nuke.createNode("Shuffle", inpanel=False) s.knob('in').setValue(i) s.knob('out').setValue('rgba') s.knob('label').setValue('[value in]') s.setInput(0, read) s.knob('postage_stamp').setValue(0) nuke.root().end() return
def __init__(self, node): nukescripts.PythonPanel.__init__(self, 'Get Shape and CV index') self.rpNode = node # GET THE NODES ROOT LAYER AND COLLECT ALL SHAPES IN IT root = node['curves'].rootLayer shapeNames = [c.name for c in root if isinstance(c, rp.Shape)] if not shapeNames: nuke.message('No Shapes found in %s' % node.name()) return # CREATE KOBS self.fRange = nuke.String_Knob( 'fRange', 'Track Range', '%s-%s' % (nuke.root().firstFrame(), nuke.root().lastFrame())) self.shape = nuke.Enumeration_Knob('shape', 'Shape', shapeNames) self.cv = nuke.Int_Knob('pointNumber', 'Point Number') self.warning = nuke.Text_Knob( 'warning', '<span style="color:red">invalid index</span>') self.warning.clearFlag(nuke.STARTLINE) self.warning.setVisible(False) # ADD KOBS for k in (self.fRange, self.shape, self.cv, self.warning): self.addKnob(k)
def get_node_info(self, writeNode): """ Get information from write node""" root_framerange = nuke.root() self.write_name = writeNode['name'].value() self.seqName = writeNode['file'].value().replace('%04d', '@####@') if writeNode['use_limit'].value(): self.write_firstframe = int(writeNode['first'].value()) self.write_lastframe = int(writeNode['last'].value()) else: self.write_firstframe = int(root_framerange['first_frame'].value()) self.write_lastframe = int(root_framerange['last_frame'].value()) return (self.write_name, self.write_firstframe, self.write_lastframe, self.seqName)
def __init__(self, node=nuke.root(), knob="knobChanged"): super(KnobScripterPane, self).__init__() self.btn_layout.removeWidget(self.pin_btn) self.btn_layout.removeWidget(self.close_btn) self.pin_btn.deleteLater() self.close_btn.deleteLater() self.pin_btn = None self.close_btn = None ksSignature = QtGuiWidgets.QLabel( '<a href="http://www.adrianpueyo.com/" style="color:#888;text-decoration:none"><b>KnobScripter </b></a>v'+version) ksSignature.setOpenExternalLinks(True) ksSignature.setStyleSheet('''color:#555;font-size:9px;''') self.btn_layout.addWidget(ksSignature)
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 _send_to_screening_room(self, write_node, write_node_app, review_submission_app, sg_publish, sg_task, comment, thumbnail_path, progress_cb): """ Take a write node's published files and run them through the review_submission app to get a movie and Shotgun Version. """ render_path = write_node_app.get_node_render_path(write_node) render_template = write_node_app.get_node_render_template(write_node) publish_template = write_node_app.get_node_publish_template(write_node) render_path_fields = render_template.get_fields(render_path) review_submission_app.render_and_submit( publish_template, render_path_fields, int(nuke.root()["first_frame"].value()), int(nuke.root()["last_frame"].value()), [sg_publish], sg_task, comment, thumbnail_path, progress_cb, )
def render(write_nodes): # Render only Write nodes and Groups with a Write node inside approved_writes = [] for write_node in write_nodes: if write_node.Class() == 'Group': if 'Write' in [n.Class() for n in write_node.nodes()]: approved_writes.append(write_node) if write_node.Class() == 'Write': approved_writes.append(write_node) if approved_writes: d = RenderDialog(_dstate, nuke.root(), approved_writes, False) if d.showModalDialog() == True: nuke.scriptSave() d.run()
def tri_update_setup(): nuke.tprint(" UPDATE project setup") root = nuke.root() path = tri_path() + "/" + root['tri_comp'].value() # TRI_PATH + _cmp if 'tri_project_scene_id' in nuke.root().knobs(): # create write dis pData = etree.fromstring(root['tri_project_xml_formats'].value()) tri_create_write_path(pData.find('result')) tri_create_write_path(pData.find('dailies')) # add new Write menu shortcut nuke.menu('Nodes').findItem('Image').addCommand("TriWrite", "nuke.createNode(\"TriWrite\")", "w", icon="Write.png") # create cmp dirs try: if not os.path.exists(path): if nuke.ask("Dir: " + path + " not exists. Create?"): pass os.makedirs(path) except: nuke.message("Cannot create\n" + path)
def doLocalise(localiseAll): rootNode = nuke.root() readKnobList = [] nodeList = [] if localiseAll: nodeList = nuke.allNodes(group=rootNode) else: nodeList = nuke.selectedNodes() for n in nodeList: readKnob = nuke.getReadFileKnob(n) if readKnob != None: if nuke.localisationEnabled(readKnob): readKnobList.append(readKnob) nuke.localiseFiles(readKnobList)
def createBackplate(node, far): try: cam = mlScripts.camera.getLatestCamera.main() except: cam = nuke.nodes.Camera2() cam.setXYpos(node.xpos() - 800, node.ypos()) card = nuke.nodes.Card2() card.setXYpos(cam.xpos() + 100, cam.ypos()) ch = nuke.nodes.CheckerBoard2() ch.setXYpos(card.xpos(), card.ypos() - 80) card.setInput(0, ch) fr = nuke.nodes.FrameHold() fr.setInput(0, cam) #fr['disable'].setValue(True) first, last = nuke.root()['first_frame'].value(), nuke.root( )['last_frame'].value() import math mid = math.floor((first + last) / 2) fr['first_frame'].setValue(mid) fr.setXYpos(cam.xpos(), cam.ypos() + 80) trans = nuke.nodes.TransformGeo() trans.setInput(0, card) trans.setInput(1, fr) trans.setXYpos(card.xpos(), card.ypos() + 80) trans['uniform_scale'].setExpression("(" + cam.name() + ".haperture/" + cam.name() + ".focal)*-translate.z") trans['translate'].setValue(float(far) * 10, 2) scan = nuke.nodes.ScanlineRender() scan['MB_channel'].setValue("backward") scan.setXYpos(trans.xpos() + 100, trans.ypos()) scan.setInput(2, cam) scan.setInput(1, trans) vb = nuke.nodes.VectorBlur() vb.setInput(0, scan) vb['uv'].setValue('backward') vb.setXYpos(scan.xpos(), scan.ypos() + 80) return vb
def readFromWrite(): nodes = nuke.selectedNodes() if len(nodes) < 1: print('No nodes selected') else: foundWrites = False writeNodes = [] for node in nodes: if node.Class() == 'Write': writeNodes.append(node) foundWrites = True if foundWrites == True: # we found some writes for node in writeNodes: nodeRead = nuke.nodes.Read() # create a read node nodeRead['file'].setValue( nuke.filename(node)) #set the filename if node['use_limit'].getValue( ) == 1: #check to see if there is a range and set the values in the read node nodeRead['first'].setValue(int(node['first'].getValue())) nodeRead['last'].setValue(int(node['last'].getValue())) else: # no range on the write? take a stab at using the range from the script value nodeRead['first'].setValue( int(nuke.root()['first_frame'].getValue())) nodeRead['last'].setValue( int(nuke.root()['last_frame'].getValue())) nodeRead.setXpos(node.xpos()) #let's set the position nodeRead.setYpos(node.ypos() + 50) nodeRead['premultiplied'].setValue( node['premultiplied'].getValue()) # use premult if checked nodeRead['raw'].setValue( node['raw'].getValue()) # use raw if checked else: print('No Writes Found in Node Selection')
def process(self, instance): grpn = instance[0] # add family to familiess instance.data["families"].insert(0, instance.data["family"]) # make label nicer instance.data["label"] = "{0} ({1} nodes)".format( grpn.name(), len(instance) - 1) # Get frame range handle_start = instance.context.data["handleStart"] handle_end = instance.context.data["handleEnd"] first_frame = int(nuke.root()["first_frame"].getValue()) last_frame = int(nuke.root()["last_frame"].getValue()) # Add version data to instance version_data = { "handles": handle_start, "handleStart": handle_start, "handleEnd": handle_end, "frameStart": first_frame + handle_start, "frameEnd": last_frame - handle_end, "colorspace": nuke.root().knob('workingSpaceLUT').value(), "families": [instance.data["family"]] + instance.data["families"], "subset": instance.data["subset"], "fps": instance.context.data["fps"] } instance.data.update({ "versionData": version_data, "frameStart": first_frame, "frameEnd": last_frame }) self.log.info("Gizmo content collected: `{}`".format(instance[:])) self.log.info("Gizmo instance collected: `{}`".format(instance))
def gq_setLabel(): nuke.root().begin() nodeSel = nuke.root().selectedNodes() if len(nodeSel) > 0: p = nuke.Panel("GQ_SetLabel") p.addSingleLineInput('New Label', nodeSel[0].knob("label").getValue()) p.addBooleanCheckBox('TCL Value?', False) if not p.show(): return label = p.value("New Label") TCLCheck = p.value("TCL Value?") if TCLCheck == True: label = "[ value " + label + " ]" else: pass for node in nodeSel: if node.Class() == "Group": node.begin() groupNodeSel = nuke.selectedNodes() for groupNode in groupNodeSel: groupNode.knob("label").setValue(label) node.knob("label").setValue(label) else: print "Please select a node"
def syncFrameRangeWithShotgun(): '''Gets the current frame range from Shotgun and pushes the data to nuke. Requires that you have certain parameters set (see below for variables) THese parameters are pretty standard in Shotgun but you can customize below. ''' inFrame = 'sg_cut_in' outFrame = 'sg_cut_out' sg = shotgunUtils.genericUtils() scriptName = nuke.root()['name'].value() if scriptName == '': nuke.message('You need to save this first!') else: projectText = scriptName.split('/')[2] shotText = scriptName.split('/')[5] project = sg.project(projectText) shot = sg.shot(project, shotText) errorMessage = [] if inFrame not in shot: errorMessage.append('%s is not present in your Shotgun config' % inFrame) if outFrame not in shot: errorMessage.append('%s is not present in your Shotgun config' % outFrame) if len(errorMessage) > 0: errors = '' for message in errorMessage: errors = '%s%s\n' % (errors, message) nuke.message(errors) else: nuke.root()['first_frame'].setValue(shot[inFrame]) nuke.root()['last_frame'].setValue(shot[outFrame]) nuke.message('Set in and out frames to %s and %s' % (shot[inFrame], shot[outFrame]))
def isTimelineWrite(self): if not nuke.env['studio']: return False if len(self._nodeSelection) > 1 or len(self._nodeSelection) < 1: return False write = self._nodeSelection[0] if write == nuke.root(): ## must be a render of all 'write' nodes, this is tricky as there may be other executable nodes apart from write nodes ## lets assume the write nodes are write, writegeo, particlecache, and diskcache # there is a bug here however as there may be groups they are executable which will be skipped right now writeNodes = nuke.allNodes('Write') writeNodes.extend(nuke.allNodes('WriteGeo')) writeNodes.extend(nuke.allNodes('ParticleCache')) writeNodes.extend(nuke.allNodes('DiskCache')) if len(writeNodes) > 1: return False if len(writeNodes) > 0: write = writeNodes[0] timelineWriteNode = None try: from foundry.frameserver.nuke.workerapplication import GetWriteNode timelineWriteNode = GetWriteNode() except: pass if not timelineWriteNode: return False if timelineWriteNode.name() != write.name(): return False ## double check that this script is actually in a timeline try: from hiero.ui import isInAnyProject return isInAnyProject(nuke.scriptName()) except: pass return False
def bakeExpressions(nodes=None, start=None, end=None, views=None): if nodes is None: nodes = nuke.selectedNodes() if not nodes: nuke.message('No nodes to bake') return scriptRange = nuke.root().frameRange() if start is None: start = scriptRange.first() if end is None: end = scriptRange.last() if views is None: views = nuke.views() elif not views: nuke.message('No views to bake') return elif not set(views).issubset(nuke.views()): nuke.message('Not all views in %s exist in script' % views) return for node in nodes: for knob in node.knobs().itervalues(): if isinstance(knob, nuke.Array_Knob): for view in views: # There's currently no way to ask a knob if it has an # expression at a given view, so we have to check the # AnimationCurve objects for that. However, we can still # use knob.isAnimated() to partially optimize this. if knob.isAnimated(view=view): aSize = 1 if knob.singleValue( view) else knob.arraySize() for index in range(aSize): anim = knob.animation(index, view=view) if anim is None or anim.noExpression(): continue for f in range(start, end + 1): #knob.setValueAt(anim.evaluate(f), f, index) anim.setKey(f, anim.evaluate(f)) knob.setExpression('curve', channel=index, view=view) # Even if the expression would have evaluated to a # constant (flat) curve, we can't tell until after # it has been baked and the expression is gone. if anim.constant(): knob.clearAnimated(index, view=view)
def __init__(self, filePath): #nukeScripts = os.path.dirname ( nuke.root().knob("name").getValue() ) #print renderPath #GET CURRENT COMPNAME AND COMPPATH compPath, compName = os.path.split(nuke.root().name()) filePath = os.path.join(compPath, compName) RenderPath = compPath.replace('nukeScripts', 'compOut') #Set RoyalRenderPath winRoyalRender = r'\\vfx-render-manager\royalrender\bin\win\rrSubmitterconsole.exe' linuxRoyalRender = '/mnt/rrender/bin/lx64/rrSubmitterconsole' self.filePath = filePath self.fileName = compName self.renderPath = RenderPath self.scriptDir = compPath self.compOutName = None self.compOutFolder = None self.writeOutName = None self.product = None self.projectName = None self.vendor = None self.seqName = None self.shotName = None self.version = None self.type = None self.note = None self.farmNum = None self.sig = None self.serverName = 'vfx-data-server\dsPipe' self.serverShare = "P" self.renderServerName = 'vfx-data-server\dsPipe' self.application = None self.firstDir = None self.windowRender = winRoyalRender self.linuxRender = linuxRoyalRender #USE REG EXPR TO CHECK COMPNAME AND POPULATE match = re.match( '^(\w+)_(\w+)_(\w+)_(\w+)_(v\d+)_(\w+)_(\w+)_(\w+)\.nk', self.fileName) if match: self.vendor, self.product, self.seqName, self.shotName, self.version, self.type, self.note, self.sig = match.groups( ) print match.groups()
def last_keyframe_location(k): #Returns the last frame which contains an animated keyframe for the selected node last_frames = [] # Walk all the knobs of the object and check if they are animated. if k.isAnimated(): for tOriginalCurve in k.animations(): tKeys = tOriginalCurve.keys() if len(tKeys): last_frames.append(tKeys[len(tKeys) - 1].x) #print last_frames return int(max(last_frames)) else: return nuke.root().lastFrame()
def updateFromRoot(self): r = nuke.root() if (not r): return somethingMissing = False for k in self.settings.keys(): try: self.settings[k] = r.knob("rvSettings_" + k).value() except: log("value failed for '%s'" % k) somethingMissing = True if (somethingMissing): self.rebuildSettingsKnobs(r)
def saveToRoot(self): r = nuke.root() kd = r.knobs() k = None if (not kd.has_key("RvRenderPrefs")): k = nuke.Text_Knob("RvRenderPrefs", "Rv Render Panel Preferences") r.addKnob(k) else: k = kd["RvRenderPrefs"] s = self.writeKnobs(nuke.TO_SCRIPT | nuke.TO_VALUE | nuke.WRITE_ALL | nuke.WRITE_NON_DEFAULT_ONLY) # log ("saving knobs to Root '%s'" % s) k.setValue(s) k.setVisible(False)
def export_selected_nodes(): path = nuke.getFilename("Export Selected To:") if not path: return nuke.nodeCopy(path) root = nuke.root() rootstring = root.writeKnobs(nuke.TO_SCRIPT | nuke.WRITE_USER_KNOB_DEFS) rootstring = "%s\nfirst_frame %d\nlast_frame %d" % ( rootstring, root['first_frame'].value(), root['last_frame'].value()) rootstring = "%s\nproxy_format \"%s\"" % (rootstring, root['proxy_format'].toScript()) rootstring = "Root {\n%s\n}" % rootstring noroot = open(path).read() with open(path, "w+") as f: f.write((rootstring + "\n" + noroot))
def showFlipbookDialog(node, takeNodeSettings=False): """Present a dialog that flipbooks the given node.""" if node is None: raise RuntimeError("Can't launch flipbook, require a node.") if node.Class() == "Viewer" and node.inputs() == 0: raise RuntimeError( "Can't launch flipbook, there is nothing connected to the viewed input." ) groupContext = nuke.root() e = FlipbookDialog(_gFlipbookDialogState, groupContext, node, takeNodeSettings) if (e.showModalDialog() == True): e.run()
def main(): shotName=nuke.root().name().split('/')[-1].split('_')[0] #get shot fields = ['id', 'code', 'sg_status_list'] filters = [['project','is', {'type':'Project','id':1674}],['code', 'is',shotName]] shot = sg.find_one('Shot',filters,fields) #get tasks fields = ['id', 'code', 'sg_status_list'] filters = [ ['entity','is',{'type':'Shot','id':shot['id']}] , ['content','is', 'Precomp' ]] taskID = sg.find_one('Task',filters,fields) sg.update('Task', taskID['id'], {'sg_status_list': 'cmpt'}) #sg.update('Task', taskID['id'], {'sg_status_list': 'ip'}) if user: sg.update('Task', taskID['id'], users[user]) nuke.message(shotName+' status: complete\n User: '+user)