示例#1
0
def main():
    """
    sys.argv[0]: current file
    sys.argv[1]: nuke file path
    sys.argv[2]: write node
    sys.argv[3]: frame range 1001-1002
    sys.argv[4]: output path
    :return:
    """
    file_name = sys.argv[1]
    nuke.scriptOpen(file_name.replace('\\', '/'))

    if not os.path.isdir(os.path.dirname(sys.argv[4])):
        os.makedirs(os.path.dirname(sys.argv[4]))

    nuke.toNode(sys.argv[2])['file'].setValue(sys.argv[4])
    nuke.toNode(sys.argv[2])['disable'].setValue(False)

    frames = sys.argv[3].split('-')
    first_frame, last_frame = int(frames[0]), int(frames[1])

    switch_path()
    #nuke.scriptSave()

    nuke.execute(sys.argv[2], first_frame, last_frame, continueOnError=True)

    nuke.scriptClose(file_name)
    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)
示例#3
0
文件: test_nuke.py 项目: vvzen/kiko
    def export_import_simple_test(self):
        nuke.scriptOpen(get_app_file(KIKO_APP_NAME, 'simple_axis.nk'))
        node1 = nuke.toNode("Axis1")
        node1.setSelected(True)

        self._manager.export_to_file(self._kb_file)

        node2 = nuke.createNode('Axis')
        obj_mapping = {node1.name(): node2.name()}
        self._manager.import_from_file(self._kb_file,
                                       objects=[node2.name()],
                                       obj_mapping=obj_mapping,
                                       ignore_item_chunks=True)

        min, max = self._facade.get_active_frame_range()

        channels = ['translate', 'rotate']

        for i in range(int(min), int(max)):
            self._facade.move_to_frame(i)

            for c in channels:
                k1 = node1.knob(c)
                k2 = node2.knob(c)
                for ci in range(3):
                    assert_true(
                        floats_equal(k1.valueAt(i, ci), k2.valueAt(i, ci)))
 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 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()
示例#6
0
 def openComp(self):
     self.afterOpen()
     if inNuke == True:
         try:
             nuke.scriptOpen("")
         except:
             print "not open"
示例#7
0
    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 openNukeFile(self, filename):
     filename = filename.replace('\\', '/')
     filebase, ext = os.path.splitext(filename)
     if ext == '.nk':
         nuke.scriptOpen(filename)
     else:
         nuke.message('Invalid nuke script. Please open a .nk script only')
示例#9
0
文件: context.py 项目: parimalvfx/ada
    def fuel(template):
        """
        Fuel an empty script with a template and set the basic things
            that are required. Views should be handled here but inherited
            from the template graph file.

        Args:
            template (str): Path to template nuke script.

        """
        getLog().info("Ada: Fuel begin.")

        nuke.scriptOpen(template)
        template = nuke.Ada.template.location

        try:
            getLog().info("Ada: Reading template: {0}".format(template))
            nuke.scriptReadFile(template)

        except RuntimeError as err:
            getLog().warning("Ada: '{0}'".format(err))

        start = nuke.Ada.script_frame_range.start
        end = nuke.Ada.script_frame_range.end

        root = nuke.Root()
        root["first_frame"].setValue(start)
        root["last_frame"].setValue(end)

        getLog().info("Ada: setting root range: start: {0}, end: {1}".format(
            start, end))

        getLog().info("Ada: Fuel end.")
示例#10
0
    def results(self, values):
        selection = str(values[0])

        shot = Project().get_body(selection)
        comp_element = shot.get_element(Department.COMP)
        self.publishes = comp_element.list_publishes()

        os.environ["DCC_NUKE_ASSET_NAME"] = selection
        if not self.publishes:
            # has not been imported. Import it first.
            shot_importer = importer.NukeImporter()
            shot_importer.shot_results([selection])
            return
        else:
            # get the latest publish
            username = Environment().get_current_username()
            try:
                filepath = comp_element.checkout(username)
            except:
                filepath = comp_element.get_last_publish()[3]

            if os.path.exists(filepath):
                qd.info("Opening file, please wait.")
                nuke.scriptOpen(filepath)
            else:
                qd.error("Couldn't find the file.")
    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 load_item_from_path_nuke(self, path):
     
     import nuke
     # fix slashes
     path = path.replace(os.sep, "/")
     # open
     nuke.scriptOpen(path)
	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()
示例#14
0
    def open(self,
             version,
             force=False,
             representation=None,
             reference_depth=0,
             skip_update_check=False):
        """the open action for nuke environment
        """
        nuke.scriptOpen(version.absolute_full_path)

        # set the project_directory
        self.project_directory = os.path.dirname(version.absolute_path)

        # TODO: file paths in different OS's should be replaced with the current one
        # Check if the file paths are starting with a string matching one of the
        # OS's project_directory path and replace them with a relative one
        # matching the current OS

        # replace paths
        self.replace_external_paths()

        # return True to specify everything was ok and an empty list
        # for the versions those needs to be updated
        from anima.env import empty_reference_resolution
        return empty_reference_resolution()
示例#15
0
	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')
示例#16
0
def post_rollback():
    filepath = rollback_window.result

    if filepath is not None:
        nuke.scriptClose()
        print "open file " + filepath
        nuke.scriptOpen(filepath)
示例#17
0
 def open_as(self, path):
     """
     Open file and rename it with a time value
     for keep the source file
     """
     path = self.conform(path)
     nuke.scriptOpen(path)
     nuke.scriptSaveAs(path.replace(".nk", "_{}.nk".format(time.time())))
示例#18
0
 def openSelectedNukescripts(self):
     currents = self.tableWidget.selectedItems()
     currents.sort()
     path = self.getPath(self.sLine.text())
     for current in currents:
         print current.text()
         fullpath = os.path.join(path, str(current.text())).replace("/", "\\")
         nuke.scriptOpen(fullpath)
示例#19
0
def reopen_scene():
    """

    :return:
    """
    scene_name = nuke.root().name()
    nuke.scriptClose(scene_name)
    nuke.scriptOpen(scene_name)
示例#20
0
 def modify_nodes_path(self):
     nuke.scriptSaveAs('{}/{}'.format(self.dest_root,
                                      os.path.basename(nuke.Root().name())),
                       1)
     for node in self.nodes:
         modify_path(node)
     nuke.scriptSave()
     nuke.scriptClear()
     nuke.scriptOpen(self.original_nk)
示例#21
0
 def mouseReleaseEvent(self, event):
     self.setText('<font color = #FFC132 size = %s face = %s>%s</font>' %
                  (self.textSize, self.textFont, self.text))
     self.emit(SIGNAL('openScript()'))
     if inNuke == True:
         try:
             nuke.scriptOpen(self.filePath)
         except:
             print "open error"
示例#22
0
def openComp():
    pfmt = PartialFormatter()
    sn = nuke.getInput('open .nk from mono shotname:').upper()
    if sn:
        shot_dict = parse_shotname(sn)
        path = pfmt.format(os.environ['IH_RAW_PATH_NUKE'], **shot_dict)
        scripts = glob.glob(path)
        print sorted(scripts)
        nuke.scriptOpen(sorted(scripts)[-1])
示例#23
0
 def reload_script():
     """Reloads the current script
     """
     # get the current script
     current_script = nuke.root().knob('name').value()
     # clear the current nuke session
     nuke.scriptClear()
     # reload the script
     nuke.scriptOpen(current_script)
示例#24
0
def nysBuild(team_list):
    report = ''

    # Deliverable name, frame range, matchup?, primetime?
    scenes = [('CFB_E_NYS_TEAM_TRANS_01', '1-75', True, True),
              ('CFB_E_MATCHUP_ENDSTAMP_01_ST', '1-300', True, True),
              ('CFB_S_MATCHUP_FE_01_ST', '1-83', True, False),
              ('CFB_E_TEAM_FE_01_ST', '1-75', False, True),
              ('CFB_E_TEAM_ENDSTAMP_01_ST', '1-300', False, True),
              ('CFB_S_TEAM_FE_01', '1-90', False, False)]

    for scene in scenes:
        # Pull values from the scene list
        deliverable, frange, matchup, primetime = scene
        print deliverable

        # check that the _TOOLKIT.nk file exists for that deliverable
        file_name = '{}_TOOLKIT.nk'.format(deliverable)
        scene_path = join(cfb.ANIMATION_PROJECT_DIR, deliverable, 'nuke',
                          file_name)

        # if it exists, do the business
        if exists(scene_path):
            nuke.scriptClear()
            nuke.scriptOpen(scene_path)
            createTeamScenes(team_list,
                             frange,
                             submit_to_farm=True,
                             matchup=matchup,
                             jumbo=matchup)
            report += '\nCOOL:  Successfully submitted nuke scene for {}'.format(
                deliverable)
        else:
            report += '\nERROR: Could not find toolkit nuke scene for {}'.format(
                deliverable)

        # Repeat the process with a PRIMETIME tag if this is a nighttime scene as well
        if (primetime):
            file_name = '{}_PRIMETIME_TOOLKIT.nk'.format(deliverable)
            scene_path = join(cfb.ANIMATION_PROJECT_DIR, deliverable, 'nuke',
                              file_name)

            if exists(scene_path):
                nuke.scriptClear()
                nuke.scriptOpen(scene_path)
                createTeamScenes(team_list,
                                 frange,
                                 submit_to_farm=True,
                                 matchup=matchup,
                                 jumbo=matchup)
                report += '\nCOOL:  Successfully submitted nuke scene for {}_PRIMETIME'.format(
                    deliverable)
            else:
                report += '\nERROR: Could not find toolkit nuke scene for {}_PRIMETIME'.format(
                    deliverable)

    print report
示例#25
0
def buildCompScript(layerOrderFile, compScriptFile, isRunningFromScript):

    #imported nuke here as importing it outside was breaking argparse
    if not isRunningFromScript:
        import nuke

    #kept here if script is run from the comp itself
    if not os.path.isfile(layerOrderFile):
        print "Could not find layer_order.yml in " + shotDir
        sys.exit()

    if isRunningFromScript:
        # get nuke script to build
        nuke.scriptOpen(compScriptFile)

    # arrange templates in the given nuke script in vertical order
    templates = getTemplateList(layerOrderFile)

    for i, template in enumerate(templates):
        nuke.scriptReadFile(template)
        nuke.selectAll()
        node = nuke.selectedNodes("BackdropNode")[0]
        dotNode = nuke.selectedNodes('Dot')[0]
        if i > 0:
            bdNodes = node.getNodes()
            nodePrevX = node.xpos()
            nodePrevY = node.ypos()
            node.setYpos(previousNode.ypos() + 500)
            node.setXpos(previousNode.xpos())

            for n in bdNodes:
                if n.ypos() > nodePrevY:
                    n.setYpos(node.ypos() + (n.ypos() - nodePrevY))
                else:
                    n.setYpos(node.ypos() + (n.ypos() + nodePrevY))
                if n.xpos() > nodePrevX:
                    n.setXpos(node.xpos() + (n.xpos() - nodePrevX))
                else:
                    n.setXpos(node.xpos() + (n.xpos() + nodePrevX))

            if i > 1:
                dotNode.setInput(0, previousDotNode.dependent()[0])
            else:
                dotNode.setInput(0, previousDotNode)

        previousNode = node
        previousDotNode = dotNode

        if isRunningFromScript:
            #save nuke script
            nuke.scriptSave(compScriptFile)

        # remove temp files
        for template in templates:
            if "temp" in template:
                os.remove(template)
示例#26
0
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
示例#27
0
 def openSelectedNukescripts(self):
     currents = self.listWidget.selectedItems()
     currents.sort()
     path = "W:\\Production\\3D_Shots\\" + self.searchLine.text(
     ) + "\\Composite"
     for current in currents:
         print current.text()
         fullpath = os.path.join(path,
                                 str(current.text())).replace("/", "\\")
         nuke.scriptOpen(fullpath)
示例#28
0
def buildCompScript(layerOrderFile, compScriptFile, isRunningFromScript):
    # kept here if script is run from the comp itself
    if not os.path.isfile(layerOrderFile):
        print "Could not find layer_order.yml in " + shotDir
        sys.exit()

    if not isRunningFromScript:
        nuke.scriptClear()
        # get nuke script to build
        nuke.scriptOpen(compScriptFile)
        nuke.selectAll()
        [nuke.delete(node) for node in nuke.selectedNodes()]

    # arrange templates in the given nuke script in vertical order
    templates = getTemplateList(layerOrderFile)

    for i, template in enumerate(templates):
        nuke.nodePaste(template)
        bdNodes = nuke.selectedNodes()
        node = nuke.selectedNodes("BackdropNode")[0]
        dotNode = nuke.selectedNodes('Dot')[0]

        if i > 0:
            bdNodes.remove(node)
            nodePrevX = node.xpos()
            nodePrevY = node.ypos()
            node.setYpos(previousNode.ypos() + 500)
            node.setXpos(previousNode.xpos())

            for n in bdNodes:
                if n.ypos() > nodePrevY:
                    n.setYpos(node.ypos() + (n.ypos() - nodePrevY))
                else:
                    n.setYpos(node.ypos() + (n.ypos() + nodePrevY))
                if n.xpos() > nodePrevX:
                    n.setXpos(node.xpos() + (n.xpos() - nodePrevX))
                else:
                    n.setXpos(node.xpos() + (n.xpos() + nodePrevX))

            if i > 1:
                dotNode.setInput(0, previousDotNode.dependent()[0])
            else:
                dotNode.setInput(0, previousDotNode)

        previousNode = node
        previousDotNode = dotNode

    if not isRunningFromScript:
        # save nuke script
        nuke.scriptSave(compScriptFile)
        # avoid opening GUI and getting extra nodes from previous script
        nuke.scriptClose()

    # remove temp files
    [os.remove(template) for template in templates if "temp" in template]
示例#29
0
def terminal_render():
    parser = argparse.ArgumentParser(description='Render from Nuke to ffmpeg.')
    parser.add_argument("nuke_script",
                        help="Nuke script to render.")
    parser.add_argument("-X", "--write",
                        help="Name of the WriteFFMPEG node to render.")
    parser.add_argument("-F", "--framerange",
                        help="framerange to render. Please specify <start>-<end>.",
                        required=False)
    parser.add_argument("-o", "--output",
                        help="Output qt to render to. Will use the value of the file knob on the WriteFFMPEG node if not specified.",
                        required=False)
    args = parser.parse_args()
    nuke_script = args.nuke_script
    nuke.scriptOpen(nuke_script)
    node = nuke.toNode(args.write)
    node.begin()
    write = nuke.toNode('write_tmp')
    if args.framerange and "-" in args.framerange:
        fr = nuke.FrameRange()
        fr.setLast(int(args.framerange.split('-')[-1]))
        fr.setFirst(int(args.framerange.split('-')[0]))
    else:
        node_framerange = node['framerange'].getValue()
        if node_framerange and "-" in node_framerange:
            fr = nuke.FrameRange()
            fr.setLast(int(node_framerange.split('-')[-1]))
            fr.setFirst(int(node_framerange.split('-')[0]))
        else:
            fr = node.frameRange()

    tmpimg = tempfile.mkstemp('.tiff', "ffmpeg_temp_")[1]
    write['file'].setValue(tmpimg)
    framerate = node['framerate'].getValue()
    output = node['file'].getValue()
    tc = frames_to_tc(fr.first(), framerate)
    ffmpeg_args = "ffmpeg -hide_banner -loglevel info -y \
        -f rawvideo -pixel_format rgb48le -video_size {0}x{1} \
        -framerate {2} -i pipe:0 -timecode {3} {4} {5}".format(
            node.width(), node.height(), framerate, tc,
            node['ffmpeg_args'].getValue(), output)
    print(ffmpeg_args)
    ffproc = subprocess.Popen(
        shlex.split(ffmpeg_args),
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE
        )
    for i, f in enumerate(fr):
        nuke.execute(write, f, f)
        print("Rendering frame \t{0} of {1}".format(i, fr.frames()))
        img = TIFF.open(tmpimg, mode='r')
        img = img.read_image()
        img.tofile(ffproc.stdin)
        os.remove(tmpimg)
    result, error = ffproc.communicate()
示例#30
0
 def quick_launch_shot_in_nuke(self, _link):
     try:
         #nuke.scriptClear()
         nuke.scriptClose()
         nuke.scriptOpen(_link)
     except:
         pass
     #print self.task_items
     #nuke.scriptClear()
     #nuke.scriptOpen(nk)
     return
示例#31
0
 def launchProject(self, filePath):
     if nuke.scriptClose():
         nuke.scriptOpen(filePath)
         super(NukeProjectLauncher,
               self).save_recents(write_local_config=True)
         # self.nuke_tools.reset_environment()
         self.nuke_tools.set_environment(self.configReader, self.template,
                                         self.get_token_dict())
         return True
     else:
         return False
示例#32
0
        def post_checkout():
            filepath = nuke_checkout_dialog.result

            if filepath is not None:

                if not os.path.exists(filepath):
                    print "new file " + filepath
                    nuke.scriptSaveAs(filepath + ".nk")
                else:
                    print "open file " + filepath
                    nuke.scriptOpen(filepath)
示例#33
0
def _RV_loadNKFile(NK_file, error_logger=None):

    NK_file = NK_file.replace("\\", "/")

    try:
        nuke.scriptOpen(NK_file)
        #nuke.load(NK_file)

    except:
        print "except "
        pass
示例#34
0
	def openScene(self, origin, filepath, force=False):
		if os.path.splitext(filepath)[1] not in self.sceneFormats:
			return False

		cleared = nuke.scriptSaveAndClear()
		if cleared:
			try:
				nuke.scriptOpen(filepath)
			except:
				pass

		return True
示例#35
0
	def openScene(self, origin, filepath):
		if not filepath.endswith(".nk"):
			return False

		cleared = nuke.scriptSaveAndClear()
		if cleared:
			try:
				nuke.scriptOpen(filepath)
			except:
				pass

		return True
示例#36
0
文件: Open.py 项目: hdd/ue
def ueOpen():
    p = nukescripts.registerWidgetAsPanel("ueCommonOpen.Open", "ueOpen",
                                          "ue.panel.ueOpen", create=True)
    p.setMinimumSize(600, 940)
    ueCommonOpen.setClasses(__ueclasses__)

    if p.showModalDialog():
        spec = ueCommonOpen.getValues()
        version = ueAssetUtils.getVersions(spec)[spec.vers-1]
        nuke.scriptOpen(os.path.join(version["path"], version["file_name"]+".nk"))
        nuke.tprint("Opened %s" % spec)

    nukescripts.unregisterPanel("ue.panel.ueOpen", lambda: "return")
def nkPanelHelper():
		# GET ALL NUKE SCRIPTS FOR CURRENT SHOT
		nkScripts = getNukeScripts()
		if not nkScripts:
				# IF THERE ARE NONE DON'T DO ANYTHING
				return
		# CREATE PANEL
		p = NkPanel( nkScripts )
		# ADJUST SIZE
		p.setMinimumSize( 200, 200 )

		# IF PANEL WAS CONFIRMED AND A NUKE SCRIPT WAS SELECTED, OPEN IT
		if p.showModalDialog():
				if p.selectedScript:
						nuke.scriptOpen( p.selectedScript )
示例#38
0
def pmOpenTranslated():
	print('Opening scene with paths map...')

	# Get scene name:
	scenename_server = nuke.getFilename('Select a scene','*.nk')
	if scenename_server is None: return

	tmp_scenes = []
	last_scene = scenename_server
	# Transfer scene paths to server from all patforms:
	for key in PMaps:
		tmp_scenes.append( scenename_server+'.'+key)
		print('Transfering from "%s" to "%s"' % ( key, os.path.basename( tmp_scenes[-1])))
		PMaps[key].toServerFile( last_scene, tmp_scenes[-1], SearchStrings, Verbose = True)
		last_scene = tmp_scenes[-1]

	error_msg = ''
	# Transfer scene paths from server clinet native patform:
	scenename_client = scenename_server + '.' + socket.gethostname() + '.nk'
	if PathMap.initialized:
		print('Transfering from server to "%s"' %  os.path.basename( scenename_client))
		PathMap.toClientFile( last_scene, scenename_client, SearchStrings, Verbose = True)
	else:
		print('No paths map preset. Just copying scene to:')
		print( scenename_client)
		try:
			shutil.copy( last_scene, scenename_client)
		except:
			error_msg = str(sys.exc_info()[1])
			print('File copied with error:')
			print( error_msg)
			error_msg = '\n' + error_msg

	# Remove temp scenes:
	for scene in tmp_scenes:
		try:
			os.remove( scene)
		except:
			print( str(sys.exc_info()[1]))
			print('Error removing "%s"' % scene)

	# Check if new scene exists:
	if not os.path.isfile(scenename_client):
		nuke.message('Client scene was not created.' + error_msg)
		return

	# Open client scene:
	nuke.scriptOpen( scenename_client)
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 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 checkout(self):
     asset_name = str(self.current_item.text())
     toCheckout = os.path.join(os.environ["SHOTS_DIR"], asset_name, "compositing")
     try:
         destpath = amu.checkout(toCheckout, True)
     except Exception as e:
         if not amu.checkedOutByMe(toCheckout):
             nuke.message(str(e))
             return
         else:
             destpath = amu.getCheckoutDest(toCheckout)
     toOpen = os.path.join(destpath, self.get_filename(toCheckout) + ".nk")
     if os.path.exists(toOpen):
         nuke.scriptOpen(toOpen)
         nuke.message("Checkout Successful")
         self.close()
     else:
         nuke.message("No File Found" + toOpen)
示例#42
0
 def open_(self, version, force=False):
     """the open action for nuke environment
     """
     nuke.scriptOpen(version.full_path)
     
     # set the project_directory
     self.project_directory = os.path.dirname(version.path)
     
     # TODO: file paths in different OS'es should be replaced with the current one
     # Check if the file paths are starting with a string matching one of the
     # OS'es project_directory path and replace them with a relative one
     # matching the current OS 
     
     # replace paths
     self.replace_external_paths()
     
     # return True to specify everything was ok and an empty list
     # for the versions those needs to be updated
     return True, []
 def _nuke_execute(self, operation, file_path, **kwargs):
     """
     The Nuke specific scene operations.
     """
     if file_path:
         file_path = file_path.replace("/", os.path.sep)        
     
     if operation == "current_path":
         # return the current script path
         return nuke.root().name().replace("/", os.path.sep)
     elif operation == "open":
         # open the specified script into the current window
         if nuke.root().modified():
             raise TankError("Script is modified!")
         nuke.scriptClear()
         nuke.scriptOpen(file_path)
     elif operation == "save":
         # save the current script:
         nuke.scriptSave()
示例#44
0
def batchReset(src,out):
    print src
    errFlg = 0
    nuke.scriptOpen(src)
    for node in nuke.allNodes('Read'):
        if os.path.dirname(node.knob('file').getValue()) != r'S:/LSC/CGI/Asset/lightset/asset_checklight/nukeimages':
            print os.path.dirname(node.knob('file').getValue())           
            filelist = scanForFiles(os.path.dirname(node.knob('file').getValue()))
            print filelist
            node.knob('file').setValue(os.path.dirname(node.knob('file').getValue())+'/'+filelist[0][0])
            node.knob('first').setValue(filelist[0][1])
            node.knob('last').setValue(filelist[0][2])
            node.knob('origfirst').setValue(filelist[0][1])
            node.knob('origlast').setValue(filelist[0][2])
    if not errFlg:
        print 'All selected Read nodes were reset.'
    nuke.scriptSave(out)
    for allnode in nuke.allNodes():
        nuke.delete(allnode)
示例#45
0
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()
示例#46
0
def openAsset():
    try:
        QtGui.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
        container = sandbox.get(os.getcwd())[0]
    except:
        container = None
    finally:
        QtGui.QApplication.restoreOverrideCursor()

    dialog = BrowserDialog(modal=True)
    dialog.setBrowseType(BrowserDialog.BrowseRevisions)
    dialog.setHintText("Select a revision.")

    if dialog.exec_() == QtGui.QDialog.Accepted:
        revision = dialog.selectedItem()

        if not revision:
            return

        container = revision.container

        work_root = sandbox.get_path(container)

        # create the directory
        if not os.path.exists(work_root):
            os.makedirs(work_root)

        # create subdirectories
        # TODO: move this into a plugin or something
        for subdir in ("scripts", "images", "scenes", "dailies"):
            if not os.path.exists(os.path.join(work_root, subdir)):
                os.makedirs(os.path.join(work_root, subdir))

        # cd
        os.chdir(work_root)

        # get revision path
        tank_path = revision.system.vfs_full_paths[0]

        # open
        nuke.scriptOpen(tank_path)
示例#47
0
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.')
示例#48
0
文件: pathmap.py 项目: Spudster3/cgru
def pmOpenFromServer():
   print 'Opening scene with server paths...'
   pm = PathMap( UnixSeparators = True, Verbose = True)

   # Get server scene name:
   scenename_server = nuke.getFilename('Select a scene with server paths','*.nk')
   if scenename_server is None: return

   # Get client scene name
   scenename_client = scenename_server
   clientname = CLIENT_PATHS_SUFFIX
   clientname += '-' + socket.gethostname()
   if scenename_client.find( SERVER_PATHS_SUFFIX) != -1:
      scenename_client = scenename_client.replace( SERVER_PATHS_SUFFIX, clientname)
   else:
      scenename_client += '.' + clientname + '.nk'

   # Map paths from server to client:
   error_msg = ''
   if pm.initialized:
      pm.toClientFile( scenename_server, scenename_client, SearchStrings, Verbose = True)
   else:
      print 'No paths map preset. Just copying scene to:'
      print scenename_client
      try:
         shutil.copy( scenename_server, scenename_client)
      except:
         error_msg = str(sys.exc_info()[1])
         print 'File copied with error:'
         print error_msg
         error_msg = '\n' + error_msg

   # Check if new scene exists:
   if not os.path.isfile(scenename_client):
      nuke.message('Client scene was not created.' + error_msg)
      return

   # Open client scene:
   nuke.scriptOpen( scenename_client)
示例#49
0
	def testLoadedScriptWithRetime( self ) :

		nuke.scriptOpen("test/IECoreNuke/scripts/sceneCacheTest.nk" )
		w = nuke.toNode("Write1")
		frames = [ 1, 10, 20, 30, 40, 50, 60, 70, 80 ]
		nuke.executeMultiple( [ w ], map( lambda f: (f,f,1), frames ) )
		for f in frames :
			imageA = IECore.Reader.create( "test/IECoreNuke/scripts/data/sceneCacheExpectedResults.%04d.exr" % f )()
			imageB = IECore.Reader.create( "test/IECoreNuke/scripts/data/sceneCacheTestResults.%04d.exr" % f )()
			self.assertEqual( IECore.ImageDiffOp()( imageA = imageA, imageB = imageB, maxError = 0.05 ).value, False )
		
		n = nuke.toNode("ieSceneCacheReader4")
		v = n.knob('sceneView')
		self.assertEqual( set(v.getSelectedItems()), set(['/root/A/a']) )

		# now force loading A+B and test in frame 20
		v.setSelectedItems(['/root/A/a', '/root/B/b', '/root/bezier1', '/root/particle1'])
		self.assertEqual( set(v.getSelectedItems()), set(['/root/A/a', '/root/B/b', '/root/bezier1', '/root/particle1' ]) )
		nuke.executeMultiple( [ w ], [(20,20,1)] )
		imageA = IECore.Reader.create( "test/IECoreNuke/scripts/data/sceneCacheExpectedResultsB.0020.exr" )()
		imageB = IECore.Reader.create( "test/IECoreNuke/scripts/data/sceneCacheTestResults.0020.exr" )()
		self.assertEqual( IECore.ImageDiffOp()( imageA = imageA, imageB = imageB, maxError = 0.05 ).value, False )
示例#50
0
    def openscript(self):
        print 'OPEN SCRIPT'
        print self.job
        print self.shot
        print self.user
        print self.script
        
        if os.path.sep in self.script:
            self.fullpath = jeeves_core.searchJob.searchNukeFullpath(self.job, self.shot, '', self.script)
        else:
            self.fullpath = jeeves_core.searchJob.searchNukeFullpath(self.job, self.shot, self.user, self.script)

        if self.script == 'NEW.NK':
            print 'Dont need to open anything just set vars and enable stuff'
            jeeves_core.setVars.setJob(self.job)
            jeeves_core.setVars.setShot(self.shot)
 
            nukePipe.jeevesConnectUtils.enablemenus()
            nuke.scriptClear()
            #prompt to save now if there is contents in the current script
        
        else:
            if not os.path.isfile(self.fullpath):
                print 'no file'
                return
            jeeves_core.setVars.setJob(self.job)
            jeeves_core.setVars.setShot(self.shot)
            jeeves_core.setVars.setScript(self.script)
            jeeves_core.setVars.setFullpath(self.fullpath)
            #self.enablemenus()
            nukePipe.jeevesConnectUtils.enablemenus()
            #save current scrpt if not root or untitled and open target script

            nuke.scriptClear()
            nuke.scriptOpen(self.fullpath)
        self.update_font()
示例#51
0
	def _doAction( self, entity, arg, ui ):

		path = ''
		if entity['version'] > 0 :
			path = entity['source'][entity['version']]

		if path and Forge.core.System.exists( path ):
			extension = Forge.core.System.getExtension( path )

			newSession = True
			if 'newSession' in arg:
				newSession = arg['newSession']['value']

			if extension == 'nk':
				if newSession:
					Forge.core.Process.launchSoftware( Forge.core.Env().nuke, arg=path )
				else:
					import nuke
					nuke.scriptOpen( path )

			elif extension == 'ma':
				if newSession:
					Forge.core.Process.launchSoftware( Forge.core.Env().maya, arg=path )
				else:
					import maya.cmds
					maya.cmds.file( path, f=True, o=True )

			else :
				import Hammer.ui
				self.popup = Hammer.ui.WindowWarning( info='The extension "%s" is unknow.' %(extension) )
				self.popup.show()

		else:
			import Hammer.ui
			self.popup = Hammer.ui.WindowWarning( info='No file found at this location : %s.' %(path) )
			self.popup.show()
示例#52
0
    def update(self, reload):
        super(Data, self).update(reload)

        if reload:
            nuke.scriptOpen(self.path)
    def execute(self, operation, file_path, context, parent_action, file_version, read_only, **kwargs):
        """
        Main hook entry point

        :param operation:       String
                                Scene operation to perform

        :param file_path:       String
                                File path to use if the operation
                                requires it (e.g. open)

        :param context:         Context
                                The context the file operation is being
                                performed in.

        :param parent_action:   This is the action that this scene operation is
                                being executed for.  This can be one of:
                                - open_file
                                - new_file
                                - save_file_as
                                - version_up

        :param file_version:    The version/revision of the file to be opened.  If this is 'None'
                                then the latest version should be opened.

        :param read_only:       Specifies if the file should be opened read-only or not

        :returns:               Depends on operation:
                                'current_path' - Return the current scene
                                                 file path as a String
                                'reset'        - True if scene was reset to an empty
                                                 state, otherwise False
                                all others     - None
        """

        # AARDMAN ADDITION
        # adds short cuts to file browser
        aaNukeUtils.aaSetupShortCuts()

        if file_path:
            file_path = file_path.replace("/", os.path.sep)

        if operation == "current_path":
            # return the current script path
            return nuke.root().name().replace("/", os.path.sep)

        elif operation == "open":
            # open the specified script
            nuke.scriptOpen(file_path)

            # reset any write node render paths:
            if self._reset_write_node_render_paths():
                # something changed so make sure to save the script again:
                nuke.scriptSave()

        elif operation == "save":
            # save the current script:
            nuke.scriptSave()

        elif operation == "save_as":
            old_path = nuke.root()["name"].value()
            try:
                # rename script:
                nuke.root()["name"].setValue(file_path)

                # reset all write nodes:
                self._reset_write_node_render_paths()

                # save script:
                nuke.scriptSaveAs(file_path, -1)
            except Exception, e:
                # something went wrong so reset to old path:
                nuke.root()["name"].setValue(old_path)
                raise TankError("Failed to save scene %s", e)
示例#54
0
文件: nukeRender.py 项目: sanfx/Batch
if __name__ == "__main__":
   import sys, os
   args = sys.argv

   writeNode=args[1]
   nukeScript=args[2]
   startFrame=args[3]
   endFrame=args[4]
   incr= args[5]
   import nuke
   nuke.scriptOpen(nukeScript)

   nuke.execute(writeNode,int(startFrame),int(endFrame),int(incr))
示例#55
0
def main():
    '''
    This script is meant to be run through the nuke commandline.
    It should receive theses sys.argv's:
    arg[0] :: path to this script
    arg[1] :: path to the nuke script to modify
    arg[2] :: Format [width height aspect name] to set for root
    arg[3] :: Create new version of script before saving? : True or False

    If it isn't run through the commandline, there are no special args passed.
    In this case a popup window opens, where the user is asked to make some choices.
    '''

    Log = nkstCC_init._DebugPrint('nkstCC_cmd.main',True)
    Log.msg("number of args: %s"%(len(sys.argv)))

    # Cancel if number of arguments is invalid
    if not len( sys.argv ) > 1:
        Log.msg( "ERROR: Not enough sys.argv's passed to script 'fix_specialcomp.py'. Args passed: %s"%(len ( sys.argv )))
        sys.exit(-1)

    Log.msg("arg0: %s" % sys.argv[0])
    Log.msg("arg1: %s" % sys.argv[1])
    Log.msg("arg2: %s" % sys.argv[2])
    Log.msg("arg3: %s" % sys.argv[3])
    Log.msg("arg4: %s" % sys.argv[4])
    Log.msg("arg5: %s" % sys.argv[5])
    Log.msg("arg6: %s" % sys.argv[6])
    
    pythonScript      = sys.argv[0]
    nukeScript        = sys.argv[1]
    setPrjFormatBool  = ast.literal_eval(sys.argv[2])
    inpFormat         = ast.literal_eval(sys.argv[3])
    delNodesBool      = ast.literal_eval(sys.argv[4])
    autoWriteNodeBool = ast.literal_eval(sys.argv[5])
    versionUpBool     = ast.literal_eval(sys.argv[6]) # True or False

    # Open the Nuke File
    if not os.path.exists(nukeScript):
        Log.msg("Nuke file doesn't exist: %s"%(nukeScript))
        return

    inScript = nukeScript
    Log.msg("Opening script...")
    nuke.scriptOpen( inScript )
    # RUN FUNCTIONS
    # Set Project Format
    if setPrjFormatBool == True:
        try:
            nkstCC_actions.setRootFormat(inpFormat)
        except:
            Log.msg("Failed to set root format.")
    # Delete nodes
    if delNodesBool == True:
        try:
            nkstCC_actions.deleteNodes()
        except:
            Log.msg("Failed to delete nodes...")
    # AutoWriteFolder
    if autoWriteNodeBool == True:
        try:
            nkstCC_actions.AutoWriteFolder()
        except:
            Log.msg("Failed to fix auto write folder.")
    # Save the script
    if versionUpBool == True:
        Log.msg("Saving Script as new version...")
        nukescripts.script_version_up()
    else:
        Log.msg("Saving Script...")
        nuke.scriptSave( inScript )
    Log.msg("Done.")
示例#56
0
文件: encode.py 项目: AlbertR/cgru170
   if frame_first == -1: frame_first = number
   frame_last = number
if frame_first == -1 or frame_last == -1: errorExit('Error: Invalid input sequence.')

# Correct arguments for Nuke UNIX slaches:
sequence = pathToUNIX( sequence)
output = pathToUNIX( output)
print 'Input:'
print sequence
print os.path.join(inputdir, imagesname) + '.[' + str(frame_first) + ' - ' + str(frame_last) + '].' + imagesext
print 'Output:'
print output

# Try to open scene:
if not os.path.isfile( options.xscene): errorExit('File "%s" not founded.' % options.xscene)
try: nuke.scriptOpen( options.xscene)
except: errorExit('Scene open error:\n' + str(sys.exc_info()[1]))

# Try to process read nodes:
readnodes = options.rnode.split(',')
for nodename in readnodes:
   readnode = nuke.toNode(nodename)
   if readnode is None: errorExit('Read "%s" not founded.' % nodename)
   if readnode.Class() != 'Read': errorExit('Node "%s" class is not "Read".' % nodename)
   readnode['file'].setValue( sequence)
   readnode['first'].setValue( frame_first)
   readnode['last'].setValue( frame_last)
   if options.colorspace != '': readnode['colorspace'].setValue( options.colorspace)

# Try to process write nodes:
writenode = nuke.toNode( options.xnode)
示例#57
0
文件: render.py 项目: sachinpore/cgru
# Transfer scene paths:
if not options.nopathsmap:
    cgrupathmap = __import__("cgrupathmap", globals(), locals(), [])
    pm = cgrupathmap.PathMap(UnixSeparators=True, Verbose=True)
    if pm.initialized:
        pmscene = os.path.basename(xscene)
        pmscene = os.path.join(tmpdir, pmscene)
        pm.toClientFile(xscene, pmscene, SearchStrings=["file ", "font ", "project_directory "], Verbose=False)
        xscene = pmscene
        print('Scene pathes mapped: "%s"' % xscene)

# Try to open scene:
print("Opening " + xscene)
try:
    nuke.scriptOpen(xscene)
except:
    errorExit("Scene open error:\n" + str(sys.exc_info()[1]), True)

# Try to process write node:
writenode = nuke.toNode(xnode)
if writenode is None:
    errorExit('Node "%s" not founded.' % xnode, True)
if writenode.Class() != "Write":
    errorExit('Node "%s" class is not "Write".' % xnode, True)
# Get file knob which can be a proxy:
if nuke.toNode("root").knob("proxy").value():
    fileknob = writenode["proxy"]
else:
    fileknob = writenode["file"]
# Get views and images folders:
示例#58
0
import nuke
import sys

if len ( sys.argv ) != 4:
    print 'Usage: NUKE readToPrecomp.py <nuke_script> <read_path> <precomp_path>'
    sys.exit(-1)

nuke_script = sys.argv[1]
read_path = sys.argv[2].replace('\\','/')
precomp_path = sys.argv[3].replace('\\','/')

nuke.scriptOpen(nuke_script)

readNode=None
for node in nuke.allNodes():
    if node.Class() == 'Read':
        if node['file'].value() == read_path:
            readNode=node

if readNode:
    
    #getting read node data before deletion
    xpos = readNode['xpos'].value()
    ypos = readNode['ypos'].value()

    dependent = readNode.dependent()

    nuke.delete(readNode)
    
    #create and setup precomp
    precomp=nuke.createNode('Precomp')
示例#59
0
    errorExit("Error: Invalid input sequence.")

# Correct arguments for Nuke UNIX slashes:
sequence = pathToUNIX(sequence)
output = pathToUNIX(output)
print("Input:")
print(sequence)
print("%s.[%s - %s].%s" % (os.path.join(inputdir, imagesname), frame_first, frame_last, imagesext))
print("Output:")
print(output)

# Try to open scene:
if not os.path.isfile(options.xscene):
    errorExit('File "%s" not found.' % options.xscene)
try:
    nuke.scriptOpen(options.xscene)
except:
    errorExit("Scene open error:\n" + str(sys.exc_info()[1]))

# Try to process read nodes:
readnodes = options.rnode.split(",")
for nodename in readnodes:
    readnode = nuke.toNode(nodename)
    if readnode is None:
        errorExit('Read "%s" not found.' % nodename)

    if readnode.Class() != "Read":
        errorExit('Node "%s" class is not "Read".' % nodename)

    readnode["file"].setValue(sequence)
    readnode["first"].setValue(frame_first)