def setRootFormat(inpFormat):
    # Add new format to root and set it
    projectRoot   = nuke.root()
    width    = inpFormat[0]
    height   = inpFormat[1]
    pxAspect = inpFormat[2]
    name     = inpFormat[3]
    
    # Add new format
    newRootFormat = "%s %s %s %s"%(width,height,pxAspect,name) # width height aspect name : <int> <int> <float> <str>
    nuke.addFormat(newRootFormat)
    projectRoot['format'].setValue(name)
Example #2
0
def reset_resolution():
    """Set resolution to project resolution."""
    project = io.find_one({"type": "project"})
    p_data = project["data"]

    width = p_data.get("resolution_width", p_data.get("resolutionWidth"))
    height = p_data.get("resolution_height", p_data.get("resolutionHeight"))

    if not all([width, height]):
        missing = ", ".join(["width", "height"])
        msg = "No resolution information `{0}` found for '{1}'.".format(
            missing, project["name"])
        log.warning(msg)
        nuke.message(msg)
        return

    current_width = nuke.root()["format"].value().width()
    current_height = nuke.root()["format"].value().height()

    if width != current_width or height != current_height:

        fmt = None
        for f in nuke.formats():
            if f.width() == width and f.height() == height:
                fmt = f.name()

        if not fmt:
            nuke.addFormat("{0} {1} {2}".format(int(width), int(height),
                                                project["name"]))
            fmt = project["name"]

        nuke.root()["format"].setValue(fmt)
Example #3
0
def createNodes(source, w, h, output):  #create read,merge,reformat,write
    global outputFormat
    global flag
    if source != '' and output != '':
        if getExtention(output) in filetypeList:
            r = nuke.nodes.Read()
            r.knob('file').fromUserText(source)
            srcReadNodes.append(r)
            m = nuke.nodes.Merge2()
            m.setInput(0, r)
            mergeNodes.append(m)
            if not settingFormat(w, h):  #create new format
                if 0 < w <= 8192 and 0 < h <= 8192:
                    outputFormat = str(w) + ' ' + str(h) + ' ' + 'newformat'
                    nuke.addFormat(outputFormat)
                    f = nuke.nodes.Reformat()
                    f.setInput(0, m)
                    f.knob('black_outside').setValue(True)
                    f.knob('format').setValue(nuke.formats()[-1])
                else:
                    'illegal format'
            else:
                f = nuke.nodes.Reformat()
                f.setInput(0, m)
                f.knob('black_outside').setValue(True)
                f.knob('format').setValue(outputFormat)
            w = nuke.nodes.Write()
            w.knob('file').fromUserText(outputPath)
            w.setInput(0, f)
            writeNodes.append(w)
            flag = flag + 1
        else:
            print 'unknown output format'
    else:
        print 'please fill all information'
Example #4
0
def reset_resolution():
    """Set resolution to project resolution."""
    project = io.find_one({"type": "project"})

    try:
        width = project["data"].get("resolution_width", 1920)
        height = project["data"].get("resolution_height", 1080)
    except KeyError:
        print("No resolution information found for \"{0}\".".format(
            project["name"]))
        return

    current_width = nuke.root()["format"].value().width()
    current_height = nuke.root()["format"].value().height()

    if width != current_width or height != current_height:

        fmt = None
        for f in nuke.formats():
            if f.width() == width and f.height() == height:
                fmt = f.name()

        if not fmt:
            nuke.addFormat("{0} {1} {2}".format(int(width), int(height),
                                                project["name"]))
            fmt = project["name"]

        nuke.root()["format"].setValue(fmt)
Example #5
0
def ShotConfig():
    '''set startup settins when launch nuke'''

    if slate.SHOW_CONFIG and slate.SHOT_CONFIG != None:
        # Format
        format_name = slate.SHOW_CONFIG['kp_show'] + '-format'
        showFormat = '%s %s %s' % (slate.SHOW_CONFIG['root_format'][0],
                                   slate.SHOW_CONFIG['root_format'][1],
                                   format_name)
        nuke.addFormat(showFormat)

        root = nuke.root()
        root['format'].setValue(format_name)
        root['fps'].setValue(slate.SHOW_CONFIG['fps'])
        root['first_frame'].setValue(slate.SHOT_CONFIG['frameStart'])
        root['last_frame'].setValue(slate.SHOT_CONFIG['frameEnd'])
        root['lock_range'].setValue(True)
        root['frame'].setValue(slate.SHOT_CONFIG['frameStart'])
        os.environ['OCIO'] = slate.SHOW_CONFIG['colorspace']

        if 'NUKE_PATH' in os.environ.keys():
            os.environ['NUKE_PATH'] += ';%s' % slate.SHOW_TOOL_DIR
        else:
            os.environ['NUKE_PATH'] = slate.SHOW_TOOL_DIR

        print("...nuke configured")
Example #6
0
File: __init__.py Project: hdd/ue
def ueNewScriptSetup():
    root = nuke.root()

    context = ueSpec.Context()
    spec = context.spec

    asset = ueAssetUtils.getAsset(spec)

    formatName = "ueProjectRes"

    root.knob("fps").setValue(int(asset["frameRate"]))
    root.knob("first_frame").setValue(int(asset["startFrame"]))
    root.knob("last_frame").setValue(int(asset["endFrame"]))

    x = int(asset["xRes"])+int(asset["xPad"])
    y = int(asset["yRes"])+int(asset["yPad"])

    nuke.addFormat("%i %i %s" % (x, y, formatName))
#    nuke.addFormat("%i %i %i %i %i %i %d %s" % (x, y, int(config["xPad"]), int(config["yPad"]),
#                                                int(config["xRes"]), int(config["yRes"]),
#                                                float(config["aspectRatio"]), formatName))
    root.knob("format").setValue(formatName)

    os.environ["FRAME_RATE"] = asset["frameRate"]
    os.environ["FIRST_FRAME"] = asset["startFrame"]
    os.environ["LAST_FRAME"] = asset["endFrame"]
Example #7
0
    def set_frame_range(self, in_frame=None, out_frame=None, **kwargs):
        """
        set_frame_range will set the frame range using `in_frame` and `out_frame`

        :param int in_frame: in_frame for the current context
            (e.g. the current shot, current asset etc)

        :param int out_frame: out_frame for the current context
            (e.g. the current shot, current asset etc)

        """

        # unlock
        locked = nuke.root()["lock_range"].value()
        if locked:
            nuke.root()["lock_range"].setValue(False)

        # and lock again
        if locked:
            nuke.root()["lock_range"].setValue(True)

        nuke.root()["colorManagement"].setValue("OCIO")
        nuke.root()["OCIO_config"].setValue("aces_1.0.3")
        #nuke.root()["floatLUT"].setValue("ACES - ACES2065-1")

        nuke.root()["fps"].setValue(25)
        format = '4174 2904 1 JAGUAR'
        nuke.addFormat(format)
        nuke.root()["format"].setValue('JAGUAR')
        nuke.root()["lock_range"].setValue(True)
        # set values
        nuke.root()["first_frame"].setValue(in_frame)
        nuke.root()["last_frame"].setValue(out_frame)
Example #8
0
    def set_show_preferences(self, context):
        fields = context.as_template_fields()

        show_prefs = preferences.Preferences(
            pref_file_name="show_preferences.yaml",
            role=fields.get("Step"),
            seq_override=fields.get("Sequence"),
            shot_override=fields.get("Shot"))

        try:
            format_string = "{0} {1} {2}".format(
                show_prefs["show_settings"]["resolution"]["width"],
                show_prefs["show_settings"]["resolution"]["height"],
                SHOW_FORMAT_NAME)
            formats = nuke.formats()
            for nuke_format in formats:
                if nuke_format.name() == SHOW_FORMAT_NAME:
                    nuke_format.setName('')
            nuke.addFormat(format_string)
            nuke.root().knob('format').setValue(SHOW_FORMAT_NAME)
        except KeyError as ke:
            self.parent.logger.warning(
                "Unable to find {} in show preferences. "
                "Not setting root format.".format(ke))

        try:
            nuke.root().knob('fps').setValue(
                show_prefs["show_settings"]["fps"])
        except KeyError as ke:
            self.parent.logger.warning(
                "Unable to find {} in show preferences. "
                "Not setting fps.".format(ke))
Example #9
0
def ueNewScriptSetup():
    root = nuke.root()

    context = ueSpec.Context()
    spec = context.spec

    asset = ueAssetUtils.getAsset(spec)

    formatName = "ueProjectRes"

    root.knob("fps").setValue(int(asset["frameRate"]))
    root.knob("first_frame").setValue(int(asset["startFrame"]))
    root.knob("last_frame").setValue(int(asset["endFrame"]))

    x = int(asset["xRes"]) + int(asset["xPad"])
    y = int(asset["yRes"]) + int(asset["yPad"])

    nuke.addFormat("%i %i %s" % (x, y, formatName))
    #    nuke.addFormat("%i %i %i %i %i %i %d %s" % (x, y, int(config["xPad"]), int(config["yPad"]),
    #                                                int(config["xRes"]), int(config["yRes"]),
    #                                                float(config["aspectRatio"]), formatName))
    root.knob("format").setValue(formatName)

    os.environ["FRAME_RATE"] = asset["frameRate"]
    os.environ["FIRST_FRAME"] = asset["startFrame"]
    os.environ["LAST_FRAME"] = asset["endFrame"]
Example #10
0
def setUpFormat():
    hasFormat = False
    scriptFormats = nuke.formats()
    for f in scriptFormats:
        if f.name() == 'ramshorn' and f.width() == 1280 and f.height() == 692:
            hasFormat = True
    if not hasFormat:
        ramshornFmt = '1280 692 ramshorn'
        nuke.addFormat(ramshornFmt)
Example #11
0
def setFormat():

    height = 50
    width = 50

    projectFormat = "{} {} current".format(height, width)

    nuke.addFormat(test)
    root = nuke.toNode('root')
    root['format'].setValue('current')
Example #12
0
def setFormats():
    # formats
    formats = [
        '1920 1080 1.0 FullHD', '960 540 1.0 HalfHD', '1920 817 cinemaHD'
    ]
    for curFormat in formats:
        nuke.addFormat(curFormat)

    root = nuke.root()
    root['format'].setValue('FullHD')
Example #13
0
def resolution_init():
    """
    Sets the resolution on first launch.

    Extracting a "width" and "height" custom attributes,
    on the parent entity of the task.

    Adds a "ftrackResolutionSet" knob to the root node in Nuke,
    which indicates whether to set the resolution on startup.
    """

    node = nuke.root()

    # Adding/Checking ftrack fps attribute
    resolution_set = False
    if "ftrackResolutionSet" in node.knobs():
        resolution_set = node["ftrackResolutionSet"].getValue()
    else:
        node.addKnob(nuke.Tab_Knob("Ftrack"))
        knob = nuke.Boolean_Knob("ftrackResolutionSet",
                                 "Set Resolution on startup.")
        node.addKnob(knob)
        node["ftrackResolutionSet"].setValue(True)

    if not resolution_set:
        session = ftrack_api.Session()
        task = session.get("Task", os.environ["FTRACK_TASKID"])

        width = None
        if "width" in task["parent"]["custom_attributes"]:
            width = task["parent"]["custom_attributes"]["width"]
        height = None
        if "height" in task["parent"]["custom_attributes"]:
            height = task["parent"]["custom_attributes"]["height"]

        if not width or not height:
            msg = "{0}: Could not find required custom attributes "
            msg += "\"width\" and \"height\" on {1}."
            print msg.format(__file__, task["parent"]["name"])
            return

        msg = "{0}: Setting Resolution to {1}x{2}."
        print msg.format(__file__, width, height)
        fmt = None
        for f in nuke.formats():
            if f.width() == width and f.height() == height:
                fmt = f

        if fmt:
            nuke.root()['format'].setValue(fmt.name())
        else:
            fmt = "{0} {1} FtrackDefault"
            nuke.addFormat(fmt)
            nuke.root()['format'].setValue("FtrackDefault")
Example #14
0
def mosaicer():
    values = getTextureNodes()
    
    if values:
        nodes = values['reads']
        tiles = values['tilesNumber']
        prefix = values['texturePrefix']
        #resolution = getResolutionFromNodes(nodes)
        resolution = values['resolution']
        tileSize = float(resolution)/float(tiles)

        # add format
        formatN = ("mosaicFormat")
        form = ("%s %s 1 %s" % (resolution, resolution, formatN))
        nuke.addFormat(form)
        formatDict = {}
        for item in nuke.formats():
            formatDict[item.name()]=item
        nuke.Root()['format'].setValue(formatDict[formatN])
        
        # create background node
        bg = nuke.createNode('Constant', inpanel=False)
        bg['format'].setValue(formatN)

        merges = []
        deselectAll()

        for node in nodes:
            node.setSelected(True)
            filename = os.path.basename(node['file'].value())
            s, t = filename.split('_')[-3].split('s')[-1].split('t')
            # create reformat
            reformat = nuke.createNode('Reformat', inpanel=False)
            reformat['type'].setValue(1)
            reformat['box_fixed'].setValue(True)
            reformat['box_width'].setValue(tileSize)
            reformat['box_height'].setValue(tileSize)
            # create transform
            transform = nuke.createNode('Transform', inpanel=False)
            transform['center'].setValue([0, 0])
            transform['translate'].setValue([float(s)*tileSize, float(t)*tileSize])
            deselectAll()
            # create merge
            merge = nuke.createNode('Merge', inpanel=False)
            merge.setInput(1, transform)
            merge.setInput(0, bg)
            merges.append(merge)

        #deselectAll()
        #for m in merges:
        #    m.setSelected(True)
        #nuke.createNode('Merge', inpanel=False)
    else:
        print "abort."
Example #15
0
def add_format(W, H, x, y, r, t, pa, format_name):
  '''Add a format based on provided attributes'''
  if not W is None and not H is None and not format_name is None:
      x = 0 if x is None else x
      y = 0 if y is None else y
      r = W if r is None else r
      t = H if t is None else t
      pa = 1 if pa is None else pa
      format_str = u'{0} {1} {2} {3} {4} {5} {6} {7}'.format(W, H, x, y, r, t, pa, format_name)
      nuke.addFormat(format_str)
      msg = u'Added format: {0}'.format(format_str)
      LOG.debug(msg)
Example #16
0
def setFormats():
	# formats 
	formats = [
	    '1920 1080 1.0 FullHD',
	    '960 540 1.0 HalfHD',
	    '1920 817 cinemaHD'
	]
	for curFormat in formats:
	    nuke.addFormat (curFormat)


	root = nuke.root()
	root['format'].setValue( 'FullHD' )
Example #17
0
def stereoVerticalCombineOutput(readNodes, fps=24, outDir = "e:/nuke/mov"):
    
    root = nuke.root()
    rockFormat = "2048 1716 Rock"
    nuke.addFormat(rockFormat)
    root['format'].setValue('Rock')

    mynode = nuke.nodes.StereoVerticalCombination(inputs=readNodes)

    filePath = readNodes[0]['file'].getValue()
    fileName = os.path.basename(filePath).split(".")[0]
    if not os.path.exists(outDir):
        try:
            os.makedirs(outDir)
        except Exception, e:
            raise e, "Create Folder {0} failure!!!".format(outDir)
    def set_frame_range(self, in_frame=None, out_frame=None, **kwargs):
        """
        set_frame_range will set the frame range using `in_frame` and `out_frame`

        :param int in_frame: in_frame for the current context
            (e.g. the current shot, current asset etc)

        :param int out_frame: out_frame for the current context
            (e.g. the current shot, current asset etc)

        """
        read = nuke.selectedNodes()

        if read and len(read) == 1 and read[0].Class() == "Read":
            read = read[0]
            height = read.metadata()['input/height']
            width = read.metadata()['input/width']
            create_format = "{} {} org_format".format(width, height)
            set_format = nuke.addFormat(create_format)
            in_frame = read['first'].getValue()
            out_frame = read['last'].getValue()
            nuke.root()["format"].setValue(set_format)

        # unlock
        locked = nuke.root()["lock_range"].value()
        if locked:
            nuke.root()["lock_range"].setValue(False)
        # set values
        nuke.root()["first_frame"].setValue(in_frame)
        nuke.root()["last_frame"].setValue(out_frame)
        # and lock again
        if locked:
            nuke.root()["lock_range"].setValue(True)
Example #19
0
    def setup(self):
        """Add tag knob to read nodes, then set project framerange."""

        if not nuke.value('root.project_directory'):
            nuke.knob(
                "root.project_directory", r"[python {os.path.join("
                r"nuke.value('root.name', ''), '../'"
                r").replace('\\', '/')}]")

        nodes = nuke.allNodes('Read')
        if not nodes:
            raise FootageError('没有读取节点')

        n = None
        root_format = None
        root = nuke.Root()
        first = None
        last = None
        formats = []

        for n in nodes:
            ReadNode(n)
            format_ = n.format()
            assert isinstance(format_, nuke.Format)
            if not n.hasError():
                formats.append((format_.width(), format_.height()))
            n_first, n_last = n.firstFrame(), n.lastFrame()

            # Ignore single frame.
            if n_first == n_last:
                continue

            # Expand frame range.
            if first is None:
                first = n_first
                last = n_last
            else:
                first = min(last, n.firstFrame())
                last = max(last, n.lastFrame())

        if first is None:
            first = last = 1

        root_format = root_format or n.format()

        root['first_frame'].setValue(first)
        root['last_frame'].setValue(last)
        nuke.frame((first + last) / 2)
        root['lock_range'].setValue(True)
        try:
            format_ = sorted([(formats.count(i), i)
                              for i in set(formats)])[-1][1]
            root['format'].setValue(nuke.addFormat('{} {}'.format(*format_)))
        except IndexError:
            root['format'].setValue('HD_1080')
            LOGGER.warning('不能获取工程格式, 使用默认值HD_1080')

        root['fps'].setValue(self.fps)
Example #20
0
def setScriptFormat(keyPrjData, root):
    prjName = keyPrjData.get('project')

    prjFormat = nuke.addFormat("{} {}".format(mainNkData.get('RESX'),
                                              mainNkData.get('RESY')))
    prjFormat.setName("PRJ_{}".format(prjName))
    prjFormat.setPixelAspect(int(mainNkData.get("PIXEL_APECT")))

    root['format'].setValue(prjFormat)
Example #21
0
def saveRef():

    f = find_upstream_node('Read', nuke.selectedNode())
    file = f['file'].getValue()
    path = os.path.dirname(file)

    filename = os.path.basename(file)
    filename = os.path.splitext(filename)[0]
    ### getting active node
    curViewer = nuke.activeViewer()
    curNode = curViewer.node()
    acticeVinput = curViewer.activeInput()
    curN = curNode.input(acticeVinput)

    ###create a reformat
    nuke.addFormat('1920 1080 tHD')

    re = nuke.createNode("Reformat")
    re.setName("tempReformat")
    re['format'].setValue('tHD')
    re['black_outside'].setValue(1)
    re.setInput(0, curN)

    ### creating temp write
    path = path + '/' + filename + '_' + 'ref.jpg'
    w = nuke.createNode("Write")
    w.setName("tempWrite")
    w.setInput(0, re)
    w['file'].setValue(path)
    w['file_type'].setValue('jpeg')

    ### setting current frame for render
    result = nuke.frame()
    if result == "":
        result = result

    ### execute write node
    nuke.execute(w, (int(result)), result)
    name = w.knob('file').value()
    nukescripts.node_delete(popupOnError=True)
    nuke.delete(re)

    if fileType == "":
        return
Example #22
0
    def set_frame_range(self, in_frame=None, out_frame=None, **kwargs):
        """
        set_frame_range will set the frame range using `in_frame` and `out_frame`

        :param int in_frame: in_frame for the current context
            (e.g. the current shot, current asset etc)

        :param int out_frame: out_frame for the current context
            (e.g. the current shot, current asset etc)

        """

        # unlock
        locked = nuke.root()["lock_range"].value()
        if locked:
            nuke.root()["lock_range"].setValue(False)

        # and lock again
        if locked:
            nuke.root()["lock_range"].setValue(True)

        nuke.root()["colorManagement"].setValue("OCIO")
        nuke.root()["OCIO_config"].setValue("aces_1.0.3")
        #nuke.root()["floatLUT"].setValue("ACES - ACES2065-1")

        nuke.root()["fps"].setValue(25)
        format = '1920 1080 1 DEMO'
        nuke.addFormat(format)
        nuke.root()["format"].setValue('DEMO')
        nuke.root()["lock_range"].setValue(True)

        # Add custom paths
        #shotnkPath = str(sgtk.platform.current_engine().context.filesystem_locations).replace(']', '').replace('[', '').replace("'", "")
        #scenesPath = ('%s/scenes/nuke') % shotnkPath
        #nukePrecompPath = ('%s/scenes/nuke/_elements') % shotnkPath
        #elementsPath = ('%s/elements') % shotnkPath

        #nuke.addFavoriteDir('Current Shot', shotNkPath, nuke.SCRIPT | nuke.IMAGE, icon='slate_icon.png')
        #nuke.addFavoriteDir('Elements', elementsPath, nuke.SCRIPT | nuke.IMAGE, icon='slate_icon.png')
        #nuke.addFavoriteDir('Prerrender (_elements)', nukePrecompPath, nuke.SCRIPT | nuke.IMAGE, icon='slate_icon.png')
        #nuke.addFavoriteDir('Nuke Scenes', scenesPath, nuke.SCRIPT | nuke.IMAGE, icon='slate_icon.png')
        # set values
        nuke.root()["first_frame"].setValue(in_frame)
        nuke.root()["last_frame"].setValue(out_frame)
Example #23
0
def C4dRead(fileNameSeq):
    node = nuke.nodes.Read(xpos=0, ypos=0)
    lastf = int(fileNameSeq.split("-")[-1])
    firstf = int(node['first'].getValue())
    node['last'].setValue(lastf)
    fRange = [firstf, lastf]
    fileName = fileNameSeq.split(" ")
    fileName = fileName[0]
    node['file'].setValue(fileName)
    node['name'].setValue("c4dread")
    c4dreadFormat = node.format()
    c4dreadFormat.setName("C4DFormat")
    w = str(c4dreadFormat.width())
    h = str(c4dreadFormat.height())
    readFt = w + " " + h + " C4D Format"
    scriptFormats = nuke.formats()
    nuke.addFormat(readFt)
    nuke.root()['format'].setValue("C4D Format")
    return fRange
Example #24
0
 def BGdetect():
     for n in nuke.selectedNodes():
         if 'xform_order' not in n.knobs():
             Name = n.name()
             Width = n.width()
             Height = n.height()
             Aspect = n.pixelAspect()
             form = str(Width)+" "+str(Height)+" "+str(Aspect)
             bg = nuke.nodes.Constant(postage_stamp = False)
             bg['format'].setValue(nuke.addFormat(form))
             return bg
Example #25
0
    def set_defaults(self):
        """ Automatically set some defaults from the shot settings for a new
			script.
		"""
        plateFormat = '%s %s %s' % (int(
            os.environ['IC_RESOLUTION_X']), int(
                os.environ['IC_RESOLUTION_Y']), os.environ['IC_SHOT'])
        proxyFormat = '%s %s %s' % (int(os.environ['IC_PROXY_RESOLUTION_X']),
                                    int(os.environ['IC_PROXY_RESOLUTION_Y']),
                                    '%s_proxy' % os.environ['IC_SHOT'])
        nuke.addFormat(plateFormat)
        nuke.addFormat(proxyFormat)

        nuke.knobDefault('Root.format', os.environ['IC_SHOT'])
        nuke.knobDefault('Root.proxy_type', 'format')
        nuke.knobDefault('Root.proxy_format',
                         '%s_proxy' % os.environ['IC_SHOT'])
        nuke.knobDefault('Root.fps', os.environ['IC_FPS'])
        nuke.knobDefault('Root.first_frame', os.environ['IC_STARTFRAME'])
        nuke.knobDefault('Root.last_frame', os.environ['IC_ENDFRAME'])
Example #26
0
    def toMov(self, source):
        """
        Create a standard movie for playback from a fle xml file
        """
        mode = flix.core2.mode.Mode()
        # localize file paths
        compPath   = self.repath.localize(source['compPath'])
        destination = self.validateUnicodeChars(source['destination'])
        scriptName = self.validateUnicodeChars(self.repath.localize(source['scriptName']))

        # set vars for script resolution and frame rate
        xResolution  = source['xResolution']
        yResolution  = source['yResolution']
        frameRate    = source['frameRate']

        # create nukeComp format
        compFormat   = "%d %d %s" % (xResolution, yResolution, "_flix_1_format")
        flixFormat   = nuke.addFormat(compFormat)

        # create read & write node. Define codec and file type
        readNodes     = source['readNodes']
        writeNodeName = self.validateUnicodeChars(source['writeNode'])

        # setup enumeration keys
        kInput1    = 0
        kInputNum  = 0
        kFilePath  = 0
        kReadNode  = 0
        kDuration  = 1
        kDialogue  = 2

        animationKey   = 0
        animationValue = 0
        lastFrame      = 0
        firstFrame     = 1

        # create list for read node objects
        readNodeList = []

        try:
            dialogueHeight = int(mode.get(kDialogueHeight))
        except ValueError, e:
            log("Could not get value for dialogue area height parameter (toMovDialogueHeight), defaulting to 100.", isWarning=True)
            dialogueHeight = 100
Example #27
0
def run(job, shot):
    #thumbnail path, only one per shot - could alter this to one per version
    thumbpath = os.path.join(core.jobsRoot, job, 'vfx', 'nuke', shot,
                             'scripts', 'thumb.jpg')

    ### getting active node
    curViewer = nuke.activeViewer()
    curNode = curViewer.node()
    acticeVinput = curViewer.activeInput()
    curN = curNode.input(acticeVinput)

    #create the reformat
    r = nuke.createNode("Reformat")
    r.setName("tempReformat")
    r.setInput(0, curN)

    newFormat = nuke.addFormat('256 144 thumb')
    r['format'].setValue('thumb')

    ### creating temp write
    w = nuke.createNode("Write")
    w.setName("tempWrite")
    w.setInput(0, r)
    w['file'].setValue(thumbpath)

    ### reformat and write options

    w['_jpeg_sub_sampling'].setValue(2)
    w['_jpeg_quality'].setValue(1)
    w['channels'].setValue('rgba')

    ### setting current frame for render
    result = nuke.frame()
    if result == "":
        result = result

    ### execute write node
    nuke.execute(nuke.selectedNode(), (int(result)), result)
    name = w.knob('file').value()
    nukescripts.node_delete(popupOnError=True)
    name = r.knob('format').value()
    nukescripts.node_delete(popupOnError=True)
Example #28
0
    def set_resolution(self, image_format):
        """Sets the resolution of the current scene

        :param image_format: Stalker ImageFormat instance
        """
        # try to get the format first
        found_format = None
        for f in nuke.formats():
            if f.name() == image_format.name:
                found_format = f
                break

        if not found_format:
            # create a new format
            found_format = nuke.addFormat(
                "%s %s" % (image_format.width, image_format.height))
            found_format.setName(image_format.name)

        # set the current format to that value
        root = self.get_root_node()
        root["format"].setValue("%s" % image_format.name)
Example #29
0
    def setResolution():
        import helix.api.nuke.utils as nkutils
        import nuke
        show = helix.hxenv.getShow()

        if show:
            print 'Setting resolution...',
            formatName = '{} Format'.format(show.alias)
            width = show.resolution_x
            height = show.resolution_y
            overscanX = 0  # TODO: implement this as an option
            overscanY = 0
            x = overscanX
            y = overscanY
            r = width - overscanX
            t = height - overscanY

            format = None

            for f in nuke.formats():
                if f.name() == formatName:
                    format = f
                    break

            if format is not None:
                format.setWidth(width)
                format.setHeight(height)
                format.setX(x)
                format.setY(y)
                format.setR(r)
                format.setT(t)
            else:
                format = nuke.addFormat(
                    '%d %d %d %d %d %d 1.0 %s' %
                    (width, height, x, y, r, t, formatName))

            nkutils.setRootKnobValue('format', format.name())
            print 'Done'
Example #30
0
# 256 pipeline tools
# Add custom plugin paths
# Set knob defaults
# Set custom format

import nuke, os
# Get project root (P:/FUTURAMA/)
rootProject = os.path.dirname(__file__).split('PREP/PIPELINE/DNA/2D')[0]


# Set Path to GIZMOS
gizmo = '{}PREP/PIPELINE/DNA/2D/gizmo'.format(rootProject)
nuke.pluginAddPath(gizmo, addToSysPath = False)

# Set paths DNA to scripts 
python  = '{}PREP/PIPELINE/DNA/2D/scripts/'.format(rootProject)
sys.path.append(python)

# Set FORMAT
nuke.addFormat('1998 1080 1.0 KZMRES')
nuke.knobDefault('Root.format', 'KZMRES')
Example #31
0
def bakeIt(node, filePath, fileSize,  fileType, outcolorspace, framerange, connectToObj, alpha, antialiasing, samples, shutter):
    
    if fileSize == '1K':
        
        formatN = ("bakeUV_1K")
        form = ("1024 1024 1 %s" % (formatN))
        nuke.addFormat(form)
        formatDict = {}
        for item in nuke.formats():
            formatDict[item.name()]=item
        nuke.Root()['format'].setValue(formatDict[formatN])
    
    if fileSize == '2K':
        
        formatN = ("bakeUV_2K")
        form = ("2048 2048 1 %s" % (formatN))
        nuke.addFormat(form)
        formatDict = {}
        for item in nuke.formats():
            formatDict[item.name()]=item
        nuke.Root()['format'].setValue(formatDict[formatN])

    if fileSize == '4K':
        
        formatN = ("bakeUV_4K")
        form = ("4096 4096 1 %s" % (formatN))
        nuke.addFormat(form)
        formatDict = {}
        for item in nuke.formats():
            formatDict[item.name()]=item
        nuke.Root()['format'].setValue(formatDict[formatN])
    
    if fileSize == '8K':
        
        formatN = ("bakeUV_8K")
        form = ("8192 8192 1 %s" % (formatN))
        nuke.addFormat(form)
        formatDict = {}
        for item in nuke.formats():
            formatDict[item.name()]=item
        nuke.Root()['format'].setValue(formatDict[formatN])	
    
    selectReplace(node)
    
    scanlineR = nuke.createNode('ScanlineRender', inpanel = False)
    scanlineR['name'].setValue("Scanline_"+node.name()+"_bake")
    scanlineR['projection_mode'].setValue('uv')
    
    scanlineR['antialiasing'].setValue(antialiasing)
    scanlineR['samples'].setValue(samples)
    scanlineR['shutter'].setValue(shutter)
    
    deselectAll()
    
    reformatBake = nuke.createNode('Reformat', inpanel = False)
    reformatBake['name'].setValue("reformat_"+node.name()+"_bake")
    reformatBake['format'].setValue("bakeUV_"+fileSize)
    
    deselectAll()
    
    scanlineR.setInput(0, reformatBake)
    selectReplace(scanlineR)
    
    mpcCol = nuke.createNode('MPC_ColIO_!MPC_COLIO_VERSION!', inpanel = False)
    mpcCol['inspace'].setValue('Linear')
    mpcCol['output_space'].setValue(outcolorspace)
    
    writeNode = nuke.createNode('Write', inpanel = False)
    try:
        writeNode['views'].setValue('left')
    except:
        pass
        
    writeNode['file_type'].setValue(fileType)
    writeNode['name'].setValue("write_"+node.name()+"_bake")
    writeNode['raw'].setValue(True)

    try:
        startF = int(framerange.split("-")[0])
        endF = int(framerange.split("-")[1])
        if startF == endF:
            writeNode['file'].setValue(filePath+node.name()+"_COL."+fileType)
        else:
            writeNode['file'].setValue(filePath+node.name()+"_COL.%04d."+fileType)
        
    except:
        startF = int(framerange)
        endF = int(framerange)
        writeNode['file'].setValue(filePath+node.name()+"_COL."+fileType)
        
    if alpha == 1:	
        writeNode['channels'].setValue('rgba')
    
    nuke.execute(writeNode, startF, endF)
    
    deselectAll()
    selectAdd(scanlineR)
    selectAdd(reformatBake)
    selectAdd(mpcCol)
    selectAdd(writeNode)
    nukescripts.node_delete()
    deselectAll()
    
    deselectAll()
    readUV = nuke.createNode('Read', inpanel = False)
    readUV['name'].setValue("Read_"+node.name()+"_baked")
    readUV['file'].setValue(filePath+node.name()+"_COL."+fileType)
    readUV['raw'].setValue(True)
    
    lastNode = nuke.createNode('MPC_ColIO_'+MPC_colio, inpanel = False)
    lastNode['inspace'].setValue('Linear')
    lastNode['output_space'].setValue(outcolorspace)
    
    if alpha:
        lastNode = nuke.createNode('Premult', inpanel = False)
    
    if connectToObj:    
        node.setInput(0, lastNode)
Example #32
0
 def createNodes(self): #create read,merge,reformat,write
     global flag
     if self.sourcePath.text() != '' and self.outputPath.text() != '':
         if self.getExtention(self.outputPath.text()) in filetypeList:
             #use custom format
             if self.formatCombo.currentText() == 'Custom':
                 if self.formatName.text()!='' and self.formatw.text()!='' and self.formath.text()!='':
                     try:
                         newWidth = int(self.formatw.text())
                         newHeight = int(self.formath.text())
                         if newWidth > 0 and newHeight > 0 and newWidth <= 8196 and newHeight <= 8196:
                             outputFormat = self.formatw.text()+' '+self.formath.text()+' '+self.formatName.text()
                             nuke.addFormat(outputFormat)
                             readNode = nuke.nodes.Read()
                             readNode['file'].fromUserText(self.sourcePath.text())
                             srcReadNodes.append(readNode)
                             watermarkMergeNode = nuke.nodes.Merge2()
                             watermarkMergeNode.setInput(0,readNode)
                             mergeNodes.append(watermarkMergeNode)
                             writeReformatNode = nuke.nodes.Reformat()
                             writeReformatNode.setInput(0,watermarkMergeNode)
                             writeReformatNode.knob('format').setValue(nuke.formats()[-1])
                             writeReformatNode.knob('black_outside').setValue(True) 
                             watermarkWriteNode = nuke.nodes.Write()
                             watermarkWriteNode.setInput(0,writeReformatNode)
                             watermarkWriteNode.knob('file').fromUserText(self.outputPath.text())
                             writeNodes.append(watermarkWriteNode)
                             nuke.toNode('Viewer1').setInput(flag,watermarkWriteNode)
                             flag = flag + 1
                             self.clipCombo.addItem('Clip '+str(flag))
                             self.clipCombo.setCurrentIndex(flag-1)
                             renderFirst.append(readNode.knob('first').value())
                             renderLast.append(readNode.knob('last').value())
                             self.startFrame.setText(str(readNode.knob('first').value()))
                             self.endFrame.setText(str(readNode.knob('last').value()))
                             self.sourcePath.clear()
                             self.outputPath.clear()
                             self.startFrame.clear()
                             self.endFrame.clear()
                         else:
                             nuke.message('should between 1-8196')
                     except ValueError:
                             nuke.message('width and height should be integer')
                 else:
                     nuke.message('should fill all information')
             #use standard format
             else:
                 readNode = nuke.nodes.Read()
                 readNode['file'].fromUserText(self.sourcePath.text())
                 srcReadNodes.append(readNode)
                 watermarkMergeNode = nuke.nodes.Merge2()
                 watermarkMergeNode.setInput(0,readNode)
                 mergeNodes.append(watermarkMergeNode)
                 writeReformatNode = nuke.nodes.Reformat()
                 writeReformatNode.setInput(0,watermarkMergeNode)
                 writeReformatNode.knob('format').setValue(nuke.formats()[self.formatCombo.currentIndex()])
                 writeReformatNode.knob('black_outside').setValue(True)             
                 watermarkWriteNode = nuke.nodes.Write()
                 watermarkWriteNode.setInput(0,writeReformatNode)
                 watermarkWriteNode.knob('file').fromUserText(self.outputPath.text())
                 writeNodes.append(watermarkWriteNode)
                 nuke.toNode('Viewer1').setInput(flag,watermarkWriteNode)
                 flag = flag + 1
                 self.clipCombo.addItem('Clip '+str(flag))
                 self.clipCombo.setCurrentIndex(flag-1)
                 renderFirst.append(readNode.knob('first').value())
                 renderLast.append(readNode.knob('last').value())
                 self.startFrame.setText(str(readNode.knob('first').value()))
                 self.endFrame.setText(str(readNode.knob('last').value()))
                 self.sourcePath.clear()
                 self.outputPath.clear()
         else:
             nuke.message('unknown output format')
     else:
         nuke.message('should set source and output')
Example #33
0
#from python_thb_dev import templateNode

# import geoffroy_callbacks
# geoffroy_callbacks.register_callbacks()

ToDoList.registerNukePanel()

nuke.addAfterRender(ImageMagick.makeThumbnail)

stores.addStoresMenu()

os.environ['GENEPATH'] = '/usr/home/ggivry/Geoff/NUKE/'
genePath = os.environ['GENEPATH']

fullHD = '2048 1152 0 0 2048 1152 1 2K_178'
nuke.addFormat(fullHD)

fullHD1K = '1024 576 0 0 1024 576 1 1K_178'
nuke.addFormat(fullHD1K)

CGOverscan = '2150 1209 0 0 2150 1209 1 CG_Overscan'
nuke.addFormat(CGOverscan)

ms = nuke.menu('Axis')
ms.addCommand('Snap/Match selected position (animated)',
              lambda: AxisSnapAnim.snapToPointsAnim(mode='t'))
ms.addCommand('Snap/Match selected position, orientation (animated)',
              lambda: AxisSnapAnim.snapToPointsAnim(mode='tr'))
ms.addCommand('Snap/Match selected position, orientation, size (animated)',
              lambda: AxisSnapAnim.snapToPointsAnim(mode='trs'))
Example #34
0
def tri_new_setup():
    nuke.tprint(" NEW project setup")
    
    projectId = os.getenv('TRI_PROJECT_ID')
    projectPath = os.getenv('TRI_PROJECT_PATH')
    projectLocalPath = os.getenv('TRI_PROJECT_LOCAL_PATH', "~")
    projectLocalFlag = os.getenv('TRI_PROJECT_LOCAL_FLAG', "0")
    
    path = projectLocalPath if projectLocalFlag == "1" else projectPath
    path = path + "/" + projectId + ".xml"
    
    try:
        if not os.path.exists(path):
            nuke.message("Path not found\n" + path)
            return
        projectPath = os.path.normpath(path)
        pData = etree.parse(path)
    except:
        nuke.message("Incorrect project setup\n" + path)
        nuke.tprint(" NEW incorrect project setup\n" + path)
        return
    
    root = nuke.root()
    if projectId != pData.getroot().get("id"):
        nuke.message("Incorrect project ID: " + projectId)
        nuke.tprint(" NEW incorrect project ID" + projectId)
        return
    
    root.addKnob(nuke.Tab_Knob('tri_panel', 'TRIGRAPH'))
    root.addKnob(nuke.String_Knob('tri_project_id', 'Project ID', pData.getroot().get("id")))
    root.addKnob(nuke.Boolean_Knob('tri_project_stereo', 'Stereo3D', False))
    root.addKnob(nuke.String_Knob('tri_project_artist', 'Artist', artistName()))
    root['tri_project_stereo'].clearFlag(nuke.STARTLINE)
    root.addKnob(nuke.String_Knob('tri_project_name', 'Project Name', pData.findtext("fullname", "")))
    root.addKnob(nuke.String_Knob('tri_project_path', 'Project Path', nukenormpath(pData.findtext("path", ""))))
    root.addKnob(nuke.String_Knob('tri_project_local_path', 'Local Path', nukenormpath(projectLocalPath)))
    root.addKnob(nuke.Boolean_Knob('tri_project_local_flag', 'work locally', True if projectLocalFlag == "1" else False))
    root.addKnob(nuke.String_Knob('tri_comp', 'comps', "_cmp/" + root['tri_project_id'].value()))
    root.addKnob(nuke.String_Knob('tri_result', 'result', "_res/" + root['tri_project_id'].value()))
    root['tri_result'].clearFlag(nuke.STARTLINE)
    root.addKnob(nuke.String_Knob('tri_dailies', 'dailies', "_dailies/_TODAY"))
    root['tri_dailies'].clearFlag(nuke.STARTLINE)
    
    formats = pData.find("formats")
    output_xml = ''.join([line.strip() for line in etree.tostring(formats).splitlines()])
    root.addKnob(nuke.String_Knob('tri_project_xml_formats', '', output_xml))
    root['tri_project_xml_formats'].setVisible(False)
    root['fps'].setValue([formats.findtext("fps")])
    
    # add new Result and Dailies formats
    size = formats.find("result").find("size")
    nuke.addFormat(size.get('width') + " " + size.get('height') + " " + size.get('aspect') + projectId + " RESULT")
    size = formats.find("dailies").find("size")
    nuke.addFormat(size.get('width') + " " + size.get('height') + " " + size.get('aspect') + projectId + " DAILIES")
    root['format'].setValue(projectId + " RESULT")
    
    # setup stereo flag
    if formats.findtext("stereo") == "true":
        if nuke.ask("Init for stereo view?") is True:
            root['setlr'].execute()
            root['tri_project_stereo'].setValue(True)
    
    # setup additional luts
    #S-Log LUT
    #root['luts'].addCurve("S-Log1", "{pow(10.0, ((t - 0.616596 - 0.03) /0.432699)) - 0.037584}")
    #root['luts'].addCurve("S-Log2", "{pow(10.0,  (x - 0.615971) * 2.698893) - 0.037584}")
    
    # setup project Scene Id and Shot #
    pSceneId = ""
    pShotNumber = ""
    p = nuke.Panel("PROJECT " + root['tri_project_id'].value())
    p.addSingleLineInput("SCENE ID", pSceneId)
    p.addSingleLineInput("SHOT #", pShotNumber)
    p.addButton("Cancel")
    p.addButton("OK")
    if p.show() == 1:
        pSceneId = p.value("SCENE ID").upper()
        pShotNumber = p.value("SHOT #")
        
        scene_name = root['tri_project_id'].value() + "-" + pSceneId           # GP-AZA
        shot_name = pSceneId + "-" + pShotNumber                               #    AZA-010
        root.addKnob(nuke.String_Knob('tri_project_scene_id', 'Scene ID', pSceneId))
        root.addKnob(nuke.String_Knob('tri_project_shot_num', 'Shot #', pShotNumber))
        root['tri_project_shot_num'].clearFlag(nuke.STARTLINE)
        root['tri_comp'].setValue("_cmp/" + scene_name + "/" + shot_name)      # _cmp/GP-AZA/AZA-010
        root['tri_result'].setValue("_res/" + scene_name  + "/" + shot_name)   # _res/GP-AZA/AZA-010
        
        #-- setup scripts name
        mainpath = tri_path() + "/" + root['tri_comp'].value()                 # TRI_PATH + _cmp/GP-AZA/AZA-010
        name = root['tri_project_id'].value() + "-" + shot_name + "_v01.nk"    # GP-AZA-010 + _v01.nk
        
        root['name'].setValue(nukenormpath(mainpath + "/" + name))             # TRI_PATH/_cmp/GP-AZA/AZA-010 + / + GP-AZA-010_v01.nk
        
        # add new Write menu shortcut
        nuke.menu('Nodes').findItem('Image').addCommand("TriWrite", "nuke.createNode(\"TriWrite\")", "w", icon="Write.png")
    
    # add path utilities
    nuke.tcl('addUserKnob {26 "" +STARTLINE}')
    root.addKnob(nuke.PyScript_Knob('tri_env2path', " expand filenames "))
    root['tri_env2path'].setValue("nodes = nuke.selectedNodes()\nif len(nodes) > 0:\n  tri_env2path(nodes)\nelse:\n  nodes = nuke.allNodes()\n  tri_env2path(nodes)\n")
    root['tri_env2path'].setFlag(nuke.STARTLINE)
    root.addKnob(nuke.PyScript_Knob('tri_path2env', " collapse filenames "))
    root['tri_path2env'].setValue("nodes = nuke.selectedNodes()\nif len(nodes) > 0:\n  tri_path2env(nodes)\nelse:\n  nodes = nuke.allNodes()\n  tri_path2env(nodes)\n")
    root.addKnob(nuke.PyScript_Knob('tri_path_check', " check filenames "))
    root['tri_path_check'].setValue("nodes = nuke.selectedNodes()\nif len(nodes) > 0:\n  tri_path_check(nodes)\nelse:\n  nodes = nuke.allNodes()\n  tri_path_check(nodes)\n")
    nuke.tcl('addUserKnob {26 "" +STARTLINE}')
    
    path = tri_path() + "/" + root['tri_comp'].value()                         # TRI_PATH + / + _cmp/GP-AZA/AZA-010
    
    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)
    
    pData = None
Example #35
0
Tank().init_software()

print('SETTINGS')
# FPS ***********************************
try:
    nuke.knobDefault("nuke.Root()['fps'].setValue({})".format(
        project_data['fps']))
    print('  {} ON  - FPS: {}'.format(chr(254), project_data['fps']))
except:
    pass
    LOG.debug('  OFF - FPS: {}'.format(project_data['fps']))
    print('  {} OFF - FPS: {}'.format(chr(254), project_data['fps']))

# RESOLUTION ****************************
try:
    nuke.addFormat(RESOLUTION)
    nuke.knobDefault('Root.format', project_data['name'].replace(' ', ''))
    print('  {} ON  - RES: {}'.format(chr(254), RESOLUTION))
except:
    LOG.debug('  OFF - RES: {}'.format(RESOLUTION))
    print('  {} OFF - RES: {}'.format(chr(254), RESOLUTION))

# createFolder ****************************
try:
    nuke.addBeforeRender(createWriteDir)
    print('  {} ON  - BeR: createWriteDir'.format(chr(254)))
except:
    LOG.error('  OFF - BeR: createWriteDir'.format(chr(254)), exc_info=True)
    print('  {} OFF - BeR: createWriteDir'.format(chr(254)))

print('')  # ********************
Example #36
0
import nuke

from nodes.DA_WriteMovieSlices import DA_WriteMovieSlices

## Custom DA formats

da_mono = '10080 1200 1 Data Arena Mono'
da_stereo = '10080 2400 1 Data Arena Stereo'
da_stereo_movie = '10320 2400 1 Data Arena Stereo Movie'

nuke.addFormat(da_mono)
nuke.addFormat(da_stereo)
nuke.addFormat(da_stereo_movie)

nuke.root()['format'].setValue('Data Arena Mono')
Example #37
0
def install():
    for k, v in NUKE_FORMATS.iteritems():
        nuke.addFormat('{0} {1}'.format(v, k))
import nuke

from AutoProjectSettings import SaveandClose
nuke.addFormat("1920 802 CenoteRes")
#from Reload import reloadMenu
Example #39
0
def convertSequence(input_folder, category_name, thread_count=0, done_callback=None):
    if not os.path.exists("W:\\Categories\\" + category_name):
        print( "Invalid category name ", category_name)
        return None
    if not os.path.exists(input_folder):
        print("Invalid input folder ", input_folder)
        return None
    if thread_count == 0:
        thread_count = multiprocessing.cpu_count()

    # potential sequence files
    unsorted_files = filter(lambda f: os.path.isfile(os.path.join(input_folder, f)) and (os.path.splitext(f)[1][1:] in valid_extensions), os.listdir(input_folder))

    # Sort by extension first to avoid the following failure case in the sequence-finding code below:
    # foo.0001.exr
    # foo.0001.jpg in same folder
    files = sorted(unsorted_files, key=lambda f: os.path.splitext(f)[::-1])

    print "Found ", len(files), " movie/image files"

    # Find all sequences.
    sequences = []
    last_prefix = None
    last_ext    = None
    seq_start = 0
    seq_end   = 0
    counter = len(files)
    for file in files:
        components = file.split(".")
        ext = os.path.splitext(file)[1][1:]
        new_seq = False
        is_movie = False
        is_img = False
        if len(components) >= 3 and ext in image_extensions:
            prefix = ".".join(components[0:-2])
            is_img = True
        elif len(components) == 2 and ext in mov_extensions:
            prefix = components[0]
            is_movie = True

        # new sequence start => insert the last sequence
        if prefix != last_prefix or ext != last_ext:
            if not (last_prefix is None):
                sequences.append(SequenceImg(last_prefix, seq_start, seq_end, last_ext))
            new_seq = True

        # handle the current file
        if is_movie: # movies are treated as single-file sequences
            prefix = components[0]
            sequences.append(SequenceMov(prefix,ext))
        elif is_img:
            frame  = components[-2]
            if new_seq:
                seq_start = int(frame)
                last_prefix = prefix
                last_ext = ext
            seq_end   = int(frame)

            if counter == 1: # last file
                sequences.append(SequenceImg(last_prefix, seq_start, seq_end, last_ext))

        counter -= 1

    print("Found sequences: ")
    for seq in sequences:
        print seq

    # conversion
    nuke.nodePaste("converter.nk")
    reader = nuke.toNode("Read1")
    source_writer = nuke.toNode("Write_Source")
    proxy_writer = nuke.toNode("Write_Proxy")
    thumb_writer = nuke.toNode("Write_Thumb")
    thumb_retime = nuke.toNode("Thumb_Retime")
    thumb_reformat = nuke.toNode("Reformat_Thumb")

    tempfiles = []
    tempdir   = tempfile.mkdtemp()
    print ("tempdir is ", tempdir)

    # contains metadata from conversion process
    results = []

    # Generate Nuke scripts with the correct paths etc in a temporary directory
    nxttmpfile = 0
    for seq in sequences:
        cur_metadata = {}
        reader['file'].fromUserText(os.path.join(input_folder, seq.inputpath()))

        # determine info from Read node
        input_dims = (int(reader.format().width()), int(reader.format().height()))
        aspect_ratio = input_dims[0] / float(input_dims[1])
        thumb_height = int(thumb_width / aspect_ratio)
        input_range = (int(nuke.toNode("Read1")['first'].getValue()), int(nuke.toNode("Read1")['last'].getValue()))
        cur_metadata["name"] = seq.basename()
        cur_metadata["width"] = input_dims[0]
        cur_metadata["height"] = input_dims[1]
        cur_metadata["startFrame"] = input_range[0]
        cur_metadata["numOfFrames"] = input_range[1] - input_range[0]
        nuke_metadata = nuke.toNode("Read1").metadata()
        cur_metadata["fps"] = int(nuke_metadata['input/frame_rate'])
        cur_metadata["extra_metadata"] = nuke_metadata

        # Set thumbnail retiming
        thumb_retime['input.first'].setValue(input_range[0])
        thumb_retime['input.last'].setValue(input_range[1])
        thumb_count = int(thumb_retime['output.last'].value())

        # Set thumbnail format
        thumb_reformat['format'].setValue(nuke.addFormat(str(thumb_width) + " " + str(thumb_height) + " 1"))

        # Generate output dirs
        out_root = os.path.join(outputpath, category_name, seq.basename())
        dirs = (os.path.join(out_root, "Source"), os.path.join(out_root, "Proxy"), os.path.join(out_root, "Thumbnails"))
        for dir in dirs:
            if not os.path.exists(dir):
                os.makedirs(dir)
        (source_dir, proxy_dir, thumb_dir) = dirs

        # Set output names
        source_writer['file'].fromUserText(os.path.join(source_dir, seq.basename() + ".####." + "exr"))
        proxy_writer['file'].fromUserText(os.path.join(proxy_dir, seq.basename() + ".####." + "jpg"))
        thumb_writer['file'].fromUserText(os.path.join(thumb_dir, seq.basename() + ".####." + "jpg"))
        # proxyWriter('_jpeg_quality').setValue(0.9) # not needed since we do this kind of thing in the predefined nuke script itself

        filepath = os.path.join(tempdir, str(nxttmpfile) + ".nk")
        nuke.scriptSaveAs(filepath)
        tempfiles.append((filepath, "Write_Thumb", 1, thumb_count))
        tempfiles.append((filepath, "Write_Proxy", input_range[0], input_range[1]))
        tempfiles.append((filepath, "Write_Source", input_range[0], input_range[1]))
        nxttmpfile += 1

        results.append(cur_metadata)

    print "Starting conversion..."

    do_conversion(tempfiles, tempdir, thread_count)
    print "Finished conversion"

    return results
Example #40
0
		
### add favourite directories
nuke.addFavoriteDir ('Current Script', 
	'[file dirname [value root.name]]', 
	nuke.IMAGE | nuke.SCRIPT, 
	icon='script_folder.png')


# call the function 'my_function' from the my_code.py file
nuke.menu('Nuke').addCommand('Chetan/Lower Settings', 'my_code.lower_settings()')
nuke.menu('Nuke').addCommand('Chetan/Quick 3D', 'my_code.quick_3d()', 'shift+o')
nuke.menu('Nuke').addCommand('Chetan/Open Folder', 'my_code.open_main()', 'shift+o')


### add format resolutions presets - i.e.:    nuke.addFormat ('1920 797 0 0 1920 797 1.0 FullHD_Widescreen')
nuke.addFormat ('1920 797 0 0 1920 797 1.0 FullHD_Widescreen')

### add LUT to the Root - i.e.:    nuke.root().knob('luts').addCurve('nameOfTheLUT', 'formula')    # sLOG formula example: '{pow(10.0, ((t - 0.616596 - 0.03) /0.432699)) - 0.037584}'

### customise menu items from Nodes toolbar - i.e. Shuffle hotkey 'J':    nuke.menu('Nodes').addCommand('Channel/Shuffle', 'nuke.createNode("Shuffle")', 'j', icon='Shuffle.png')
### set hotkey for an existing menu item - i.e. Shuffle hotkey 'J':    nuke.menu('Nodes').findItem('Channel').findItem('Shuffle').setShortcut('j')
nuke.menu('Nodes').addCommand('Channel/Shuffle', 'nuke.createNode("Shuffle")', 'shift+j')
nuke.menu('Nodes').addCommand('Other/Backdrop', 'nukescripts.autoBackdrop()', 'shift+b')
 

### customise node default value - i.e.:    nuke.knobDefault('myNode.myKnob', 'myDefaultValue' )

m = menubar.addMenu("V-Ray")
m.addCommand("Create Camera from EXR", "createExrCamVray.createExrCamVray(nuke.selectedNode())")
 
### add menu item to existing Nuke menu - i.e.:    nodeMenu = nuke.menu('Nuke').findItem('Edit/Node').addCommand('myMenuElement', 'myPythonScript.myFunction()', 'myHotkey')    # Modifiers: Shift= shift+, Alt/Option = alt+, Control/Command = ctrl+
Example #41
0
                else:
                    subMenu = toolbar.addMenu(folder)
            self._recursiveAddGizmoMenuItems(subMenu, data)
                    
if __name__ == '__main__':
    if CUSTOM_GIZMO_LOCATION and os.path.isdir(CUSTOM_GIZMO_LOCATION):
        gizManager = GizmoPathManager(searchPaths=[CUSTOM_GIZMO_LOCATION])
    else:
        gizManager = GizmoPathManager()
    gizManager.addGizmoPaths()
    if not nuke.GUI:
        # We're not gonna need it anymore, cleanup...
        del gizManager


### Read and Write nodes change defaults
nuke.knobDefault("Read.before", "black")
nuke.knobDefault("Read.after", "black")
    

### Image Formats
nuke.addFormat ("2048 1556 2.0 2k_anamorphic")
nuke.addFormat ("4096 3112 2.0 4k_anamorphic")
nuke.addFormat ("2048 1556 1.0 2k_super35_cc")
nuke.addFormat ("2048 1168 1.0 2k_3perf_1168")
nuke.addFormat ("2048 1162 1.0 2k_3perf_1162")
nuke.addFormat ("2048 1156 1.0 2k_3perf_1156")
nuke.addFormat ("2048 1152 1.0 2k_3perf_1152")
nuke.addFormat ("960 540 1.0 half_HD")
nuke.addFormat ("720 405 1.0 email")
Example #42
0
volAssets = ''
if(sys.platform == 'win32'):
	volProjects = 'X:'
	volAssets = 'Y:'
elif(sys.platform == 'darwin'):
	volProjects = '/Volumes/Projects'
	volAssets = '/Volumes/Assets'


# Make these favorites show up in Nuke
nuke.addFavoriteDir('File server', volProjects + '/Projects/')
nuke.addFavoriteDir('Assets', volAssets)
nuke.addFavoriteDir('R&D', volProjects + '/RnD/')

# Formats
nuke.addFormat( '1024 576 PAL Widescreen' )
nuke.addFormat( '1280 720 HD 720p' )

# Set plugin/gizmo sub-folders
nuke.pluginAppendPath(volAssets + '/include/nuke/gizmos')
nuke.pluginAppendPath(volAssets + '/include/nuke/plugins')
nuke.pluginAppendPath(volAssets + '/include/nuke/scripts')
nuke.pluginAppendPath(volAssets + '/include/nuke/icons')

# Load Bokeh
os.environ['RLM_LICENSE'] = '[email protected]'
if nuke.env['WIN32']:
	currentBokeh = 'Bokeh-Nuke6.3-1.2.1-win64'
if nuke.env['MACOS']:
	currentBokeh = 'Bokeh-Nuke6.3-1.2.1-Darwin'
nuke.pluginAppendPath(volAssets + '/include/nuke/plugins/bokeh/' + currentBokeh + '/')
Example #43
0
import sys

# SET TOOLS PATH
global toolsPath
toolsPath = os.path.dirname(__file__)

# RETURN EVERYTHING IN DIRECTORY AND CHECK FOR THE DIRECTORY ONLY
onlyDir = [
    f for f in os.listdir(toolsPath)
    if os.path.isdir(os.path.join(toolsPath, f))
]
for eachDir in onlyDir:
    #ADD THE DIRECTORY AS PLUGIN
    nuke.pluginAddPath(eachDir)

# SET THE ROOT TO USE BOTH BASE AND PROXY FORMATS
# SET ROOT
nuke.addFormat("1280 720 0 0 1280 720 1 CML")
nuke.knobDefault("Root.format", "CML")
nuke.knobDefault("Root.fps", "25")
#nuke.knobDefault("Root.onScriptLoad", "assetScript.onLoad()")

# SET ROTO
nuke.knobDefault("Roto.output", "rgba")

# SET ADDTIMECODE
nuke.knobDefault("AddTimeCode.startcode", "00:00:00:00")
nuke.knobDefault("AddTimeCode.metafps", "false")
nuke.knobDefault("AddTimeCode.useFrame", "true")
nuke.knobDefault("AddTimeCode.fps", "25")
nuke.knobDefault("AddTimeCode.frame", "0")
Example #44
0
def coverageMap():
    
    # get start, end frames
    frameStart = int(nuke.thisNode().knob('frameStart').getValue())
    frameEnd = int(nuke.thisNode().knob('frameEnd').getValue())
    
    # get image
    imageName = nuke.thisNode().knob('coverageMapName').getValue().split('.')[0]
    modelName = ('%s.obj' %(imageName))

    cameraNode = nuke.thisNode().input(0)
    cameraRatio = cameraNode.knob('haperture').getValue()/cameraNode.knob('vaperture').getValue()

    # create 256 pixels format
    imageFormatName = ("coverageMap_projectMap")
    resX = 256
    resY = int (resX/cameraRatio) 
    imageFormat = ("%s %s %s" % (resX, resY, imageFormatName))

    nuke.addFormat(imageFormat)
    nuke.thisNode().node('ConstantProjection').knob('format').setValue(imageFormatName)

    print '### SAVE MODEL ###'
    writeGeoNode = nuke.thisNode().node('WriteGeo_input')

    writeGeoNode.knob('file').setValue(modelName)
    nuke.execute(writeGeoNode, frameStart, frameStart, 1)

    print '### READ MODEL ###'
    readGeoNode = nuke.thisNode().node('ReadGeo_input')
    readGeoNode.knob('file').setValue(modelName)
    readGeoNode.knob('reload').execute()


    print '### WRITE FIRST FRAME ###'
    writeFirstNode = nuke.thisNode().node('WriteFirst')
    writeFirstNode.knob('file').setValue('%s.%s.exr' %(imageName, frameStart-1))
    nuke.execute(writeFirstNode, frameStart, frameStart, 1)

    readLastNode = nuke.thisNode().node('ReadLast')
    readLastNode.knob('file').setValue('%s.####.exr' %(imageName))
    readLastNode.knob('first').setValue(frameStart-1)
    readLastNode.knob('last').setValue(frameEnd)

    readLastNode.knob('reload').execute()

    nuke.thisNode().node('SwitchReadLast').knob('which').setValue(1)

    print '### WRITE SEQUENCE ###'
    writeSequenceNode = nuke.thisNode().node('WriteSequence')
    writeSequenceNode.knob('file').setValue('%s.####.exr' %imageName)
    nuke.execute(writeSequenceNode,frameStart,frameEnd,1)

    os.system ('cp %s.%s.exr %s.exr' %(imageName,frameEnd,imageName))

    readResultNode = nuke.thisNode().node('ReadResult')
    readResultNode.knob('file').setValue('%s.exr' %imageName)
    readResultNode.knob('reload').execute()

    readLastNode.knob('file').setValue('%s.exr' %imageName)
    readLastNode.knob('reload').execute()


    nuke.thisNode().node('SwitchOutput').knob('which').setValue(1)
    nuke.thisNode().node('SwitchReadLast').knob('which').setValue(0)

    # clean unused stuff
    os.system('rm %s.*.exr' %imageName)
    os.system('rm %s' %modelName)
Example #45
0
# 256 pipeline tools
# Add custom plugin paths
# Set knob defaults
# Set custom format

import nuke, os
# Get project root (P:/FUTURAMA/)
rootProject = os.path.dirname(__file__).split('PREP/PIPELINE/DNA/2D')[0]

# Set Path to GIZMOS
gizmo = '{}PREP/PIPELINE/DNA/2D/gizmo'.format(rootProject)
nuke.pluginAddPath(gizmo, addToSysPath=False)

# Set paths DNA to scripts
python = '{}PREP/PIPELINE/DNA/2D/scripts/'.format(rootProject)
sys.path.append(python)

# Set FORMAT
nuke.addFormat('1998 1080 1.0 KZMRES')
nuke.knobDefault('Root.format', 'KZMRES')
Example #46
0
import nuke

'''
Set up the generic formats for most things
'''

formats = [
    '1920 1080 1.0 hd',
    '960 540 1.0 hhd',
    '2048 1556 1.0 2kfa',
    '2048 1556 2.0 2kana',
    '1828 1556 2.0 ana',
    '720 486 1.21 d1',
    '720 405 1 hdvid'
    ]

for curFormat in formats:
    nuke.addFormat (curFormat)
Example #47
-1
# *************************************************************

import nuke

import settings as s

sys.path.append(s.PATH["lib"])
from lib import libFunction


# ************************
# INIT
# ************************
print("\nWelcome " + libFunction.getCurrentUser())
print("\nBREAKINGPOINT: System is setting ...\n")


# #*******************
# # VARIABLES
# #*******************
FPS = "25"
RESOLUTION = "2048 1152 BP_2K"


# #*******************
# # SETTINGS
# #*******************
nuke.knobDefault("Root.fps", FPS)
nuke.addFormat(RESOLUTION)
nuke.knobDefault("Root.format", "BP_2K")