コード例 #1
0
    def _import_image_seq(self, path, sg_publish_data):
        """
        Import and image sequence and assign it to the selected cameras.

        :param str path: The file path to load.
        :param dict sg_publish_data: Shotgun data dictionary with all the standard publish fields.
        """
        app = self.parent
        path, start, end, step = get_hash_path_and_range_info_from_seq(path)
        name = app.engine.context.entity["name"]

        if tde4.getNoCameras():
            selected_cameras = filter(is_sequence_camera,
                                      tde4.getCameraList(True))
            if selected_cameras:
                app.logger.info(
                    "%d sequence cameras selected, assigning to all",
                    len(selected_cameras))
                for cam_id in selected_cameras:
                    current_name = tde4.getCameraName(cam_id)
                    app.logger.debug("Current camera: '%s'", current_name)
                    if current_name.startswith(name):
                        app.logger.info(
                            "'%s' already has name referring to Shot",
                            current_name)
                    else:
                        cam_name = name
                        count = 0
                        while tde4.findCameraByName(cam_name):
                            count += 1
                            cam_name = "{}__{:02}".format(name, count)
                        app.logger.info("Renaming '%s' to '%s'", current_name,
                                        cam_name)
                        tde4.setCameraName(cam_id, cam_name)
                    app.logger.debug("setCameraSequenceAttr: %s, %d, %d, %d",
                                     cam_id, start, end, step)
                    tde4.setCameraSequenceAttr(cam_id, start, end, step)
                    app.logger.debug("setCameraFrameOffset: %s, %d", cam_id,
                                     start)
                    tde4.setCameraFrameOffset(cam_id, start)
                    app.logger.debug(
                        "setCameraFrameRangeCalculationFlag: %s, 1", cam_id)
                    tde4.setCameraFrameRangeCalculationFlag(cam_id, 1)
                    app.logger.debug("setCameraPath: %s, %s", cam_id, path)
                    tde4.setCameraPath(cam_id, path)
            else:
                QtGui.QMessageBox.warning(
                    None, "No sequence cameras selected",
                    "Please select a sequence camera and try again")
        else:
            QtGui.QMessageBox.warning(
                None, "No cameras exist",
                "Please create a sequence camera and try again")
コード例 #2
0
def buildUINotSupported(req, cameraIndex, cameraTmp):
    message = ''
    '''
    if not tools.isClassicModel(cameraTmp):
        message += "Model not suported"
    '''
    if not tools.correctCameraPath(cameraTmp):
        message += "Worng format padding, it should be imageName.padding.ext"

    tde4.addTextFieldWidget(req, "noExport" + str(cameraIndex),
                            "Camera " + str(tde4.getCameraName(cameraTmp)),
                            message)
コード例 #3
0
ファイル: tools.py プロジェクト: Rotomator/noid
 def getInfoCam(self):
     cam = self.cam
     index = self.index
     self.offset = tde4.getCameraFrameOffset(cam)
     self.cameraPath = tde4.getCameraPath(cam).replace('\\', '/')
     self.camType = tde4.getCameraType(cam)
     self.noframes = tde4.getCameraNoFrames(cam)
     self.lens = tde4.getCameraLens(cam)
     self.rez_x = tde4.getCameraImageWidth(cam)
     self.rez_y = tde4.getCameraImageHeight(cam)
     self.model = tde4.getLensLDModel(self.lens)
     self.firstFrame = tde4.getCameraSequenceAttr(cam)[0]
     self.name = "%s_%s_1" % (validName(tde4.getCameraName(cam)), index)
     self.lastFrame = '%d' % (self.firstFrame + self.noframes - 1)
     self.firstFrame = '%d' % self.firstFrame
     self.focal_cm = tde4.getCameraFocalLength(cam, 1)
コード例 #4
0
    def scan_scene(self):
        """
        The scan scene method is executed once at startup and its purpose is
        to analyze the current scene and return a list of references that are
        to be potentially operated on.

        The return data structure is a list of dictionaries. Each scene reference
        that is returned should be represented by a dictionary with three keys:

        - "node": The name of the 'node' that is to be operated on. Most DCCs have
          a concept of a node, path or some other way to address a particular
          object in the scene.
        - "type": The object type that this is. This is later passed to the
          update method so that it knows how to handle the object.
        - "path": Path on disk to the referenced object.

        Toolkit will scan the list of items, see if any of the objects matches
        any templates and try to determine if there is a more recent version
        available. Any such versions are then displayed in the UI as out of date.

        """
        reads = []

        # let's look at the camera nodes
        for camera_id in tde4.getCameraList():
            path = tde4.getCameraPath(camera_id)
            name = tde4.getCameraName(camera_id)
            reads.append({"node": name, "type": "camera", "path": path})

        # also at 3D models in all point groups:
        for pgroup_id in tde4.getPGroupList():
            for model_id in tde4.get3DModelList(pgroup_id):
                path = tde4.get3DModelFilepath(pgroup_id, model_id)
                name = tde4.get3DModelName(pgroup_id, model_id)
                # internal 3D objects (eg. cube, sphere) will not have a path
                if path:
                    # there is no find_model_by_name as of 3de r6.b2
                    reads.append({
                        "node": (name, pgroup_id, model_id),
                        "type": "model",
                        "path": path
                    })

        return reads
コード例 #5
0
def buildUICamera(req, cameraIndex, cameraTmp):
    imageHeightOuttmp, imageWidthOuttmp = getOutSize(req, cameraIndex,
                                                     cameraTmp)

    nametmp = "exportCamera" + str(cameraIndex)
    texttmp = "Export Camera " + str(tde4.getCameraName(cameraTmp))
    tde4.addToggleWidget(req, nametmp, texttmp, 1)
    tde4.setWidgetCallbackFunction(req, nametmp, "callBackExportCamera")

    firstFrame = tde4.getCameraSequenceAttr(cameraTmp)[0]

    strRes = camWidgetFormat.format(imageWidth=str(imageWidthOuttmp),
                                    sep=resSpliter,
                                    imageHeight=str(imageHeightOuttmp),
                                    firstFrame=firstFrame)

    camResWidgetName = camWidgetPrefix + str(cameraIndex)
    log.debug('camResWidgetName (creation): ' + camResWidgetName)

    tde4.addTextFieldWidget(req, camResWidgetName, camResWidgetText, strRes)

    tde4.addSeparatorWidget(req, "sep" + str(cameraIndex))
コード例 #6
0
def exportNukeDewarpNode(id_cam,offset,nuke_path):
	id_lens 	= tde4.getCameraLens(id_cam)
	model 	= tde4.getLensLDModel(id_lens)
	num_frames 	= tde4.getCameraNoFrames(id_cam)
	w_fb_cm = tde4.getLensFBackWidth(id_lens)
	h_fb_cm = tde4.getLensFBackHeight(id_lens)
	lco_x_cm = tde4.getLensLensCenterX(id_lens)
	lco_y_cm = tde4.getLensLensCenterY(id_lens)
	pxa = tde4.getLensPixelAspect(id_lens)
# xa,xb,ya,yb in unit coordinates, in this order.
	xa_unit,xb_unit,ya_unit,yb_unit = tde4.getCameraFOV(id_cam)
		
	f = open(nuke_path,"w")
	try:
		f.write('# Created by 3DEqualizer4 using Export Nuke Distortion Nodes export script\n')
		f.write("LD" + nukify_name(model) + ' {\n')
		f.write(' direction undistort\n')
################################
# focal length                 #
################################
		if is_focal_length_dynamic(id_cam):
# write focal length curve if dynamic
#			print 'dynamic focal length'
			f.write(' tde4_focal_length_cm {{curve ')	
			for frame in range(num_frames):
# Internally, frames start at 1.
				focal = tde4.getCameraFocalLength(id_cam,frame + 1)
				f.write ('x%i %.7f ' % (frame + offset,focal))
			f.write('}}\n')
		else:
# write static focal length otherwise
#			print 'static focal length'
			f.write(' tde4_focal_length_cm %.7f \n' % tde4.getCameraFocalLength(id_cam,1))
################################
# focus distance               #
################################
# For Release 1 this function return False, so no problem with getCameraFocus.
		if is_focus_distance_dynamic(id_cam):
# write focus distance curve if dynamic
#			print 'dynamic focus distance'
			f.write(' tde4_custom_focus_distance_cm {{curve ')	
			for frame in range(num_frames):
# Internally, frames start at 1.
				focus = tde4.getCameraFocus(id_cam,frame + 1)
				f.write ('x%i %.7f ' % (frame + offset,focus))
			f.write('}}\n')
		else:
			try:
# write static focus distance otherwise
				f.write(' tde4_custom_focus_distance_cm %.7f \n' % tde4.getCameraFocus(id_cam,1))
			except:
# For Release 1 we simply write out the default value to Nuke.
				f.write(' tde4_custom_focus_distance_cm 100.0 \n')
################################
# built-in parameters          #
################################
# the remaining five built-in parameters
		f.write(' tde4_filmback_width_cm %.7f \n' % w_fb_cm)
		f.write(' tde4_filmback_height_cm %.7f \n' % h_fb_cm)
		f.write(' tde4_lens_center_offset_x_cm %.7f \n' % lco_x_cm)
		f.write(' tde4_lens_center_offset_y_cm %.7f \n' % lco_y_cm)
		f.write(' tde4_pixel_aspect %.7f \n' % pxa)
################################
# field-of-view                #
################################
		f.write(' field_of_view_xa_unit %.7f \n' % xa_unit)
		f.write(' field_of_view_xb_unit %.7f \n' % xb_unit)
		f.write(' field_of_view_ya_unit %.7f \n' % ya_unit)
		f.write(' field_of_view_yb_unit %.7f \n' % yb_unit)
		
# write distortion parameters
#
# dynamic distortion
		dyndistmode = get_dynamic_distortion_mode(id_lens)

		old_api = True
		try:
			for para in getLDmodelParameterList(model):
				tde4.getLensLDAdjustableParameter(id_lens, para, 1)
				break
		except:
			old_api = False

		if old_api:
# dynamic focal length (zoom)
			if dyndistmode=="DISTORTION_DYNAMIC_FOCAL_LENGTH":
#				print 'dynamic lens distortion, focal length'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' {{curve ')	
					for frame in range(num_frames):
# Internally, frames start at 1.
						focal = tde4.getCameraFocalLength(id_cam,frame + 1)
						f.write ('x%i %.7f ' % (frame + offset,tde4.getLensLDAdjustableParameter(id_lens,para,focal)))
					f.write('}}\n')
# dynamic focus distance
			if dyndistmode=="DISTORTION_DYNAMIC_FOCUS_DISTANCE":
#				print 'dynamic lens distortion, focus distance'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' {{curve ')	
					for frame in range(num_frames):
# Older Releases do not have Focus-methods.
						try:
# Internally, frames start at 1.
							focus = tde4.getCameraFocus(id_cam,frame + 1)
						except:
							focus = 100.0
						f.write('x%i %.7f ' % (frame + offset,tde4.getLensLDAdjustableParameter(id_lens,para,focus)))
					f.write('}}\n')
# static distortion
			if dyndistmode=="DISTORTION_STATIC":
#				print 'static lens distortion'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' %.7f \n'%tde4.getLensLDAdjustableParameter(id_lens,para,1))
		else:
# new API
			if dyndistmode=="DISTORTION_STATIC":
#				print 'static lens distortion'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' %.7f \n'%tde4.getLensLDAdjustableParameter(id_lens,para,1,1))
			else:
#				print 'dynamic lens distortion,'
# dynamic
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' {{curve ')	
					for frame in range(num_frames):
# Internally, frames start at 1.
						focal = tde4.getCameraFocalLength(id_cam,frame + 1)
						focus = tde4.getCameraFocus(id_cam,frame + 1)
						f.write('x%i %.7f ' % (frame + offset,tde4.getLensLDAdjustableParameter(id_lens,para,focal,focus)))
#						print "%i[3DE4] -> %i[Nuke]" % (frame + tde4.getCameraFrameOffset(id_cam),frame + offset)
					f.write('}}\n')


		
		f.write(' name LD_3DE4_' + decode_entities(tde4.getCameraName(id_cam)) + '\n')
		f.write('}\n')

	finally:	
		f.close()	
コード例 #7
0
		we_have_set_widget_callback_function = False

# For older releases we cannot do the smart guessing...
	if we_have_set_widget_callback_function:
		widget_default_initial_frame = tde4.addOptionMenuWidget(nuke_node_req,"option_menu_default_initial_frame","Startframe is based on","Nuke Read Node Default","3DE4 Initial Frame","User-defined")
		tde4.setWidgetValue(nuke_node_req,"option_menu_default_initial_frame",str(value_option_menu_default_initial_frame))
		tde4.setWidgetCallbackFunction(nuke_node_req,"option_menu_default_initial_frame","set_initial_frame_widget")
# Without / before smart-guessing we mimick Nuke's Read Node default behaviour.
	tde4.addTextFieldWidget(nuke_node_req,"text_initial_frame_nuke","Startframe in Nuke",str(tde4.getCameraSequenceAttr(id_cam)[0]))

# After creating all widgets we invoke the Callback once explicitly in order to initialize the text widget.
	if we_have_set_widget_callback_function:
		set_initial_frame_widget(widget_default_initial_frame,None,None)

# post requester
	ret	= tde4.postCustomRequester(nuke_node_req,'Export nuke distortion node for camera ' + tde4.getCameraName(id_cam)+' ',700,0,'Ok','Cancel ')
	if ret != 1:
		raise CancelException('Cancelled')
# At this point we know that user has pressed "Ok". Check path and suffix
	nuke_path = tde4.getWidgetValue(nuke_node_req,'file_nuke_path')
	if not nuke_path:
		raise Exception('No path specified')
	if not nuke_path.endswith('.nk'):
		nuke_path += '.nk'
# Update frame values and calculate offset between 3DE4 and Nuke.
	initial_frame_nuke = int(tde4.getWidgetValue(nuke_node_req,"text_initial_frame_nuke"))
# export
	exportNukeDewarpNode(id_cam,initial_frame_nuke,nuke_path)

except CancelException, e:
	pass
コード例 #8
0
        tde4.setWidgetCallbackFunction(nuke_node_req,
                                       "option_menu_default_initial_frame",
                                       "set_initial_frame_widget")
# Without / before smart-guessing we mimick Nuke's Read Node default behaviour.
    tde4.addTextFieldWidget(nuke_node_req, "text_initial_frame_nuke",
                            "Startframe in Nuke",
                            str(tde4.getCameraSequenceAttr(id_cam)[0]))

    # After creating all widgets we invoke the Callback once explicitly in order to initialize the text widget.
    if we_have_set_widget_callback_function:
        set_initial_frame_widget(widget_default_initial_frame, None, None)

# post requester
    ret = tde4.postCustomRequester(
        nuke_node_req, 'Export nuke distortion node for camera ' +
        tde4.getCameraName(id_cam) + ' ', 700, 0, 'Ok', 'Cancel ')
    if ret != 1:
        raise CancelException('Cancelled')
# At this point we know that user has pressed "Ok". Check path and suffix
    nuke_path = tde4.getWidgetValue(nuke_node_req, 'file_nuke_path')
    if not nuke_path:
        raise Exception('No path specified')
    if not nuke_path.endswith('.nk'):
        nuke_path += '.nk'
# Update frame values and calculate offset between 3DE4 and Nuke.
    initial_frame_nuke = int(
        tde4.getWidgetValue(nuke_node_req, "text_initial_frame_nuke"))
    # export
    exportNukeDewarpNode(id_cam, initial_frame_nuke, nuke_path)

except CancelException, e:
コード例 #9
0
            f.write("setAttr -lock true (\"trk_marker\" + \"*\" + \".ry\");\n")
            f.write("setAttr -lock true (\"trk_marker\" + \"*\" + \".rz\");\n")
            f.write("setAttr -lock true (\"trk_marker\" + \"*\" + \".sx\");\n")
            f.write("setAttr -lock true (\"trk_marker\" + \"*\" + \".sy\");\n")
            f.write("setAttr -lock true (\"trk_marker\" + \"*\" + \".sz\");\n")
            #
            # write cameras...

            cl = tde4.getCameraList()
            index = 1
            for cam in cl:
                camType = tde4.getCameraType(cam)
                noframes = tde4.getCameraNoFrames(cam)
                lens = tde4.getCameraLens(cam)
                if lens != None:
                    name = validName(tde4.getCameraName(cam))
                    if tde4.getCameraStereoOrientation(
                            cam) == 'STEREO_LEFT' and tde4.getCameraStereoMode(
                                cam) != 'STEREO_OFF':
                        name = ShotName + '_trk_camLeft'
                    elif tde4.getCameraStereoOrientation(
                            cam
                    ) == 'STEREO_RIGHT' and tde4.getCameraStereoMode(
                            cam) != 'STEREO_OFF':
                        name = ShotName + '_trk_camRight'
                    else:
                        name = ShotName + '_trk_cam'
                    #name       = "%s_%s_1"%(name,index)
                    index += 1
                    fback_w = tde4.getLensFBackWidth(lens)
                    fback_h = tde4.getLensFBackHeight(lens)
コード例 #10
0
 def name(self):
     return tde4.getCameraName(self._cam_id)
コード例 #11
0
ファイル: nukeExporter.py プロジェクト: Rotomator/noid
def generateNukeNode(cam, direction, offset=0, index=0):
    lens = tde4.getCameraLens(cam)
    model = tde4.getLensLDModel(lens)
    num_frames = tde4.getCameraNoFrames(cam)
    w_fb_cm = tde4.getLensFBackWidth(lens)
    h_fb_cm = tde4.getLensFBackHeight(lens)
    lco_x_cm = tde4.getLensLensCenterX(lens)
    lco_y_cm = tde4.getLensLensCenterY(lens)
    pxa = tde4.getLensPixelAspect(lens)
    # xa,xb,ya,yb in unit coordinates, in this order.
    fov = tde4.getCameraFOV(cam)

    print 'camera: ', tde4.getCameraName(cam)
    print 'offset:', offset
    print 'lens:', tde4.getLensName(lens)
    print 'model: ', model

    nukeNode = []

    nukeNode.append('# Created by 3DEqualizer4 ')
    nukeNode.append('# using Export Nuke Distortion Nodes export script')
    nukeNode.append("LD" + tools.nukify_name(model) + ' {')
    nukeNode.append(' direction ' + direction)

    # write focal length curve if dynamic
    if tde4.getCameraZoomingFlag(cam):
        print 'dynamic focal length'
        dynFocalLength = []

        for frame in range(1, num_frames + 1):
            dynFocalLength.append('x%i' % (frame + offset))
            dynFocalLength.append(' %.7f ' %
                                  tde4.getCameraFocalLength(cam, frame))
        focalLenghtStr = "".join(dynFocalLength)
        nukeNode.append(' tde4_focal_length_cm {{curve ' + focalLenghtStr +
                        ' }}')

# write static focal length else
    else:
        print 'static focal length'
        focalLenghtStr = ' tde4_focal_length_cm %.7f '
        focalLenghtStr = focalLenghtStr % tde4.getCameraFocalLength(cam, 1)
        nukeNode.append(focalLenghtStr)

# write focus distance curve if dynamic
    try:
        if tde4.getCameraFocusMode(cam) == "FOCUS_DYNAMIC":
            print 'dynamic focus distance'
            dynFocusDistance = []
            for frame in range(1, num_frames + 1):
                dynFocusDistance.append('x%i' % (frame + offset))
                dynFocusDistance.append(' %.7f ' %
                                        tde4.getCameraFocus(cam, frame))
            focusDStr = "".join(dynFocusDistance)
            toWrite = ' tde4_custom_focus_distance_cm {{curve ' + focusDStr + '}}'
            nukeNode.append(toWrite)
    except:
        # For 3DE4 Release 1:
        pass
# write static focus distance else
    else:
        print 'static focus distance'
        try:
            cameraFocus = ' tde4_custom_focus_distance_cm %.7f '
            cameraFocus = cameraFocus % tde4.getCameraFocus(cam, 1)
            nukeNode.append(cameraFocus)
        except:
            # For 3DE4 Release 1:
            nukeNode.append(' tde4_custom_focus_distance_cm 100.0 ')


# write camera
    nukeNode.append(' tde4_filmback_width_cm %.7f ' % w_fb_cm)
    nukeNode.append(' tde4_filmback_height_cm %.7f ' % h_fb_cm)
    nukeNode.append(' tde4_lens_center_offset_x_cm %.7f ' % lco_x_cm)
    nukeNode.append(' tde4_lens_center_offset_y_cm %.7f ' % lco_y_cm)
    nukeNode.append(' tde4_pixel_aspect %.7f ' % pxa)
    nukeNode.append(' field_of_view_xa_unit %.7f ' % fov[0])
    nukeNode.append(' field_of_view_ya_unit %.7f ' % fov[2])
    nukeNode.append(' field_of_view_xb_unit %.7f ' % fov[1])
    nukeNode.append(' field_of_view_yb_unit %.7f ' % fov[3])
    nukeNode.append(' filter Simon')

    # dynamic distortion
    try:
        dyndistmode = tde4.getLensDynamicDistortionMode(lens)
    except:
        # For 3DE4 Release 1:
        if tde4.getLensDynamicDistortionFlag(lens) == 1:
            dyndistmode = "DISTORTION_DYNAMIC_FOCAL_LENGTH"
        else:
            dyndistmode = "DISTORTION_STATIC"

    if dyndistmode == "DISTORTION_STATIC":
        print 'static lens distortion'
        for para in (tools.getLDmodelParameterList(model)):
            distStr = ' %.7f ' % tde4.getLensLDAdjustableParameter(
                lens, para, 1, 1)
            nukeNode.append(' ' + tools.nukify_name(para) + distStr)
    else:
        print 'dynamic lens distortion,'
        # dynamic
        for para in (tools.getLDmodelParameterList(model)):

            lensCurve = []
            for frame in range(1, num_frames + 1):
                focal = tde4.getCameraFocalLength(cam, frame)
                focus = tde4.getCameraFocus(cam, frame)
                lensCurve.append('x%i' % (frame + offset))
                frameParam = tde4.getLensLDAdjustableParameter(
                    lens, para, focal, focus)
                lensCurve.append(' %.7f ' % frameParam)
            lensCurveStr = ' {{curve ' + "".join(lensCurve) + ' }}'
            nukeNode.append(' ' + tools.nukify_name(para) + lensCurveStr)

    nameNode = 'name ' + getLDNodeName(cam, direction, offset, index)
    nukeNode.append(nameNode)
    nukeNode.append('}')

    return nukeNode
コード例 #12
0
ファイル: nukeExporter.py プロジェクト: Rotomator/noid
def getLDNodeName(cam, direction, offset=0, index=0):
    nameNode = 'LD_3DE4_%s_%s_1'
    nameNode = nameNode % (tools.validName(tde4.getCameraName(cam)), index)
    return nameNode
コード例 #13
0
def exportNukeDewarpNode(cam, offset, nuke_path):
    lens = tde4.getCameraLens(cam)
    model = tde4.getLensLDModel(lens)
    num_frames = tde4.getCameraNoFrames(cam)
    w_fb_cm = tde4.getLensFBackWidth(lens)
    h_fb_cm = tde4.getLensFBackHeight(lens)
    lco_x_cm = tde4.getLensLensCenterX(lens)
    lco_y_cm = tde4.getLensLensCenterY(lens)
    pxa = tde4.getLensPixelAspect(lens)
    # xa,xb,ya,yb in unit coordinates, in this order.
    fov = tde4.getCameraFOV(cam)

    print 'camera: ', tde4.getCameraName(cam)
    print 'offset:', offset
    print 'lens:', tde4.getLensName(lens)
    print 'model: ', model

    f = open(nuke_path, "w")
    try:
        f.write(
            '# Created by 3DEqualizer4 using Export Nuke Distortion Nodes export script\n'
        )
        f.write("LD" + nukify_name(model) + ' {\n')
        f.write(' direction undistort\n')

        # write focal length curve if dynamic
        if tde4.getCameraZoomingFlag(cam):
            print 'dynamic focal length'
            f.write(' tde4_focal_length_cm {{curve ')
            for frame in range(1, num_frames + 1):
                f.write('x%i' % (frame + offset))
                f.write(' %.7f ' % tde4.getCameraFocalLength(cam, frame))
            f.write('}}\n')
# write static focal length else
        else:
            print 'static focal length'
            f.write(' tde4_focal_length_cm %.7f \n' %
                    tde4.getCameraFocalLength(cam, 1))
# write focus distance curve if dynamic
        try:
            if tde4.getCameraFocusMode(cam) == "FOCUS_DYNAMIC":
                print 'dynamic focus distance'
                f.write(' tde4_custom_focus_distance_cm {{curve ')
                for frame in range(1, num_frames + 1):
                    f.write('x%i' % (frame + offset))
                    f.write(' %.7f ' % tde4.getCameraFocus(cam, frame))
                f.write('}}\n')
        except:
            # For 3DE4 Release 1:
            pass
# write static focus distance else
        else:
            print 'static focus distance'
            try:
                f.write(' tde4_custom_focus_distance_cm %.7f \n' %
                        tde4.getCameraFocus(cam, 1))
            except:
                # For 3DE4 Release 1:
                f.write(' tde4_custom_focus_distance_cm 100.0 \n')
# write camera
        f.write(' tde4_filmback_width_cm %.7f \n' % w_fb_cm)
        f.write(' tde4_filmback_height_cm %.7f \n' % h_fb_cm)
        f.write(' tde4_lens_center_offset_x_cm %.7f \n' % lco_x_cm)
        f.write(' tde4_lens_center_offset_y_cm %.7f \n' % lco_y_cm)
        f.write(' tde4_pixel_aspect %.7f \n' % pxa)
        f.write(' field_of_view_xa_unit %.7f \n' % fov[0])
        f.write(' field_of_view_ya_unit %.7f \n' % fov[2])
        f.write(' field_of_view_xb_unit %.7f \n' % fov[1])
        f.write(' field_of_view_yb_unit %.7f \n' % fov[3])

        # write distortion parameters
        #
        # dynamic distortion
        try:
            dyndistmode = tde4.getLensDynamicDistortionMode(lens)
        except:
            # For 3DE4 Release 1:
            if tde4.getLensDynamicDistortionFlag(lens) == 1:
                dyndistmode = "DISTORTION_DYNAMIC_FOCAL_LENGTH"
            else:
                dyndistmode = "DISTORTION_STATIC"

        old_api = True
        try:
            tde4.getLensLDAdjustableParameter(lens, para, 1)
        except:
            old_api = False

        if old_api:
            if dyndistmode == "DISTORTION_DYNAMIC_FOCAL_LENGTH":
                print 'dynamic lens distortion, focal length'
                # dynamic focal length (zoom)
                for para in (getLDmodelParameterList(model)):
                    f.write(' ' + nukify_name(para) + ' {{curve ')
                    for frame in range(1, num_frames + 1):
                        focal = tde4.getCameraFocalLength(cam, frame)
                        f.write('x%i' % (frame + offset))
                        f.write(' %.7f ' % tde4.getLensLDAdjustableParameter(
                            lens, para, focal))
                    f.write('}}\n')

            if dyndistmode == "DISTORTION_DYNAMIC_FOCUS_DISTANCE":
                print 'dynamic lens distortion, focus distance'
                # dynamic focus distance
                for para in (getLDmodelParameterList(model)):
                    f.write(' ' + nukify_name(para) + ' {{curve ')
                    for frame in range(1, num_frames + 1):
                        # Older Releases do not have Focus-methods.
                        try:
                            focus = tde4.getCameraFocus(cam, frame)
                        except:
                            focus = 100.0
                        f.write('x%i' % (frame + offset))
                        f.write(' %.7f ' % tde4.getLensLDAdjustableParameter(
                            lens, para, focus))
                    f.write('}}\n')

# static distortion
            if dyndistmode == "DISTORTION_STATIC":
                print 'static lens distortion'
                for para in (getLDmodelParameterList(model)):
                    f.write(' ' + nukify_name(para) + ' %.7f \n' %
                            tde4.getLensLDAdjustableParameter(lens, para, 1))
        else:
            # new API
            if dyndistmode == "DISTORTION_STATIC":
                print 'static lens distortion'
                for para in (getLDmodelParameterList(model)):
                    f.write(
                        ' ' + nukify_name(para) + ' %.7f \n' %
                        tde4.getLensLDAdjustableParameter(lens, para, 1, 1))
            else:
                print 'dynamic lens distortion,'
                # dynamic
                for para in (getLDmodelParameterList(model)):
                    f.write(' ' + nukify_name(para) + ' {{curve ')
                    for frame in range(1, num_frames + 1):
                        focal = tde4.getCameraFocalLength(cam, frame)
                        focus = tde4.getCameraFocus(cam, frame)
                        f.write('x%i' % (frame + offset))
                        f.write(' %.7f ' % tde4.getLensLDAdjustableParameter(
                            lens, para, focal, focus))
                    f.write('}}\n')

        f.write(' name LD_3DE4_' + decode_entities(tde4.getCameraName(cam)) +
                '\n')
        f.write('}\n')

    finally:
        f.close()
コード例 #14
0
def compress(cams, ui=False):
    errors = []
    max_steps = 0
    seq_cams = {}

    for cam in cams:
        cam_name = tde4.getCameraName(cam)

        if tde4.getCameraType(cam) != 'SEQUENCE':
            errors.append(
                'Camera {} is not a Sequence Camera.'.format(cam_name))
            continue

        start, end = tde4.getCameraSequenceAttr(cam)[:2]
        frames = abs(end - start + 1)
        steps = frames + frames / 100 + 2
        max_steps += steps
        seq_cams[cam] = {
            'name': cam_name,
            'start': start,
            'end': end,
            'frames': frames,
            'steps': steps
        }

    if cams:
        if ui:
            tde4.postProgressRequesterAndContinue(TITLE, 'Please wait...',
                                                  max_steps, 'Ok')
        else:
            print(TITLE)
    else:
        errors.append('Please choose a camera.')

    steps_done = 0

    for cam in seq_cams:
        cam_name = seq_cams[cam]['name']
        msg = 'Exporting: {} (starting)'.format(cam_name)
        if ui:
            tde4.updateProgressRequester(steps_done, msg)
        else:
            print('  0% ' + msg)
        start = seq_cams[cam]['start']
        end = seq_cams[cam]['end']
        frames = seq_cams[cam]['frames']
        steps = seq_cams[cam]['steps']
        path = tde4.getCameraPath(cam)

        if tde4.getPreferenceValue('ICOMPRESS_BCFILE_IN_DIR') == '1':
            # save buffer in project directory
            project_dir = os.path.dirname(tde4.getProjectPath())
            if project_dir:
                # we have a project directory, it's safe to save
                target_path = os.path.join(project_dir, os.path.basename(path))
            else:
                # no project directory, alert the user
                target_path = ''
                errors.append(
                    'Can not save buffer to project directory. Project is not saved.'
                )
        elif tde4.getPreferenceValue('ICOMPRESS_BCFILE_IN_DIR') == '2':
            # save buffer in custom directory
            custom_dir = tde4.getPreferenceValue('ICOMPRESS_CUSTOM_DIR')
            target_path = os.path.join(custom_dir, os.path.basename(path))
        else:
            # default behavior, save buffer in image path
            target_path = path

        if not path:
            errors.append(
                ("Couldn't process camera {} because it doesn't have "
                 'any Footage loaded.').format(cam_name))
            steps_done += steps
            continue

        gamma = tde4.getCamera8BitColorGamma(cam)
        softclip = tde4.getCamera8BitColorSoftclip(cam)
        black, white = tde4.getCamera8BitColorBlackWhite(cam)
        exr = tde4.getCameraImportEXRDisplayWindowFlag(cam)
        sxr = tde4.getCameraImportSXRRightEyeFlag(cam)
        if sxr == 1:
            sxr2 = " -import_sxr_right_eye "
        else:
            sxr2 = " "
        if exr == 1:
            exr2 = " -import_exr_display_window "
        else:
            exr2 = " "
        proc_err = None

        # makeBCFile exits cleanly even if it errored, so we have to parse
        # its errors manually.
        proc = subprocess.Popen(
            (os.path.join(tde4.get3DEInstallPath(), 'bin',
                          'makeBCFile'), '-source', path, '-start', str(start),
             '-end', str(end), '-out', os.path.dirname(target_path), sxr2,
             exr2, '-black', str(black), '-white', str(white), '-gamma',
             str(gamma), '-softclip', str(softclip)),
            stdout=subprocess.PIPE,
            universal_newlines=True)

        for line in iter(proc.stdout.readline, ''):
            line = line.rstrip()

            if line.startswith('Error'):
                proc_err = line
                continue
            elif line.endswith('image files processed'):
                frame = int(line.split('/', 1)[0])
                msg = 'Exporting: {} ({}/{})'.format(cam_name, frame, frames)
                if ui:
                    tde4.updateProgressRequester(steps_done + frame + 1, msg)
                else:
                    print('{: 3d}% {}'.format(
                        100 * (steps_done + frame + 1) / max_steps, msg))

        if proc_err:
            errors.append(
                "Couldn't create Buffer Compression File for Camera {}.".
                format(cam_name))
            errors.append('Message >>    {}'.format(proc_err))
            steps_done += steps
            continue

        msg = 'Exporting: {} (finishing)'.format(cam_name)
        if ui:
            tde4.updateProgressRequester(steps_done + frames + 2, msg)
        else:
            print('{: 3d}% {}'.format(
                100 * (steps_done + frames + 2) / max_steps, msg))
        bcompress = ('x'.join(target_path.split('#' * path.count('#'))) +
                     '.3de_bcompress')

        if not os.path.isfile(bcompress):
            errors.append(
                "Couldn't find Buffer Compression File for Camera {}.".format(
                    cam_name))
            steps_done += steps
            continue

        if not tde4.importBufferCompressionFile(cam):
            errors.append(
                "Couldn't import Buffer Compression File for Camera {}.".
                format(cam_name))

        # Change permissions of the Buffer Compression File,
        # to be nice to everyone else who might work on the shot eventually!
        try:
            os.chmod(bcompress, 0o666)
        except OSError:
            errors.append(
                "Couldn't set permissions of Buffer CompressionFile for Camera {}."
                .format(cam_name))

        steps_done += steps

    if ui:
        tde4.unpostProgressRequester()

        if errors:
            req = tde4.createCustomRequester()
            for i, line in enumerate(errors):
                name = 'line{}'.format(i)
                tde4.addLabelWidget(req, name, line, 'ALIGN_LABEL_LEFT')
                tde4.setWidgetOffsets(req, name, 0, 0, 0, 0)
            tde4.postCustomRequester(req, TITLE, 0, 0, 'Ok')

    else:
        print('100% Done.')

        if errors:
            raise RuntimeError('\n'.join(errors))
コード例 #15
0
ファイル: MayaMelExport.py プロジェクト: cgmafia/3DEtools
def main():
    campg = None
    pgl = tde4.getPGroupList()
    for pg in pgl:
        if tde4.getPGroupType(pg) == "CAMERA": campg = pg
    if campg == None:
        tde4.postQuestionRequester("Export Maya...",
                                   "Error, there is no camera point group.",
                                   "Ok")

    #
    # open requester...

    try:
        req = _export_requester_maya
    except (ValueError, NameError, TypeError):
        _export_requester_maya = tde4.createCustomRequester()
        req = _export_requester_maya
        tde4.addFileWidget(req, "file_browser", "Exportfile...", "*.mel")
        tde4.addTextFieldWidget(req, "startframe_field", "Startframe", "1")
        # tde4.addOptionMenuWidget(req,"mode_menu","Orientation","Y-Up", "Z-Up")
        tde4.addToggleWidget(req, "hide_ref_frames", "Hide Reference Frames",
                             0)

    cam = tde4.getCurrentCamera()
    offset = tde4.getCameraFrameOffset(cam)
    tde4.setWidgetValue(req, "startframe_field", str(offset))

    # ret	= tde4.postCustomRequester(req,"Export Maya (MEL-Script)...",600,0,"Ok","Cancel")
    ret = 1

    if ret == 1:
        # yup	= tde4.getWidgetValue(req,"mode_menu")
        # if yup==2: yup = 0
        yup = 1
        # path	= tde4.getWidgetValue(req,"file_browser")
        path = get_mel_filename()['path']
        # frame0	= float(tde4.getWidgetValue(req,"startframe_field"))
        # frame0	-= 1
        framerange = get_frame_range()
        playbackoptions = 'playbackOptions -min {0} -max {1};'
        playbackoptions = playbackoptions.format(framerange['first'],
                                                 framerange['last'])
        frame0 = framerange['first'] - 1

        hide_ref = tde4.getWidgetValue(req, "hide_ref_frames")
        if path != None:
            if not path.endswith('.mel'): path = path + '.mel'
            f = open(path, "w")
            if not f.closed:

                #
                # write some comments...

                f.write("//\n")
                f.write("// Maya/MEL export data written by %s\n" %
                        tde4.get3DEVersion())
                f.write("//\n")
                f.write(
                    "// All lengths are in centimeter, all angles are in degree.\n"
                )
                f.write("//\n\n")

                #
                # write scene group...
                groupname = """// create scene group...
string $sceneGroupName = `group -em -name "mm_{name}"`;
"""

                # f.write("// create scene group...\n")
                # f.write("string $sceneGroupName = `group -em -name \"Scene\"`;\n")
                groupname = groupname.format(
                    name=get_mel_filename()['filename'][:-4])
                f.write(groupname)

                #
                # write cameras...

                cl = tde4.getCameraList()
                index = 1
                for cam in cl:
                    camType = tde4.getCameraType(cam)
                    noframes = tde4.getCameraNoFrames(cam)
                    lens = tde4.getCameraLens(cam)
                    if lens != None:
                        name = validName(tde4.getCameraName(cam))
                        cam_name = 'cam_mm_' + name
                        # name		= "%s_%s_1"%(name,index)
                        # name		= "%s_%s"%(name,index)
                        name = cam_name
                        index += 1
                        fback_w = tde4.getLensFBackWidth(lens)
                        fback_h = tde4.getLensFBackHeight(lens)
                        p_aspect = tde4.getLensPixelAspect(lens)
                        focal = tde4.getCameraFocalLength(cam, 1)
                        lco_x = tde4.getLensLensCenterX(lens)
                        lco_y = tde4.getLensLensCenterY(lens)

                        # convert filmback to inch...
                        fback_w = fback_w / 2.54
                        fback_h = fback_h / 2.54
                        lco_x = -lco_x / 2.54
                        lco_y = -lco_y / 2.54

                        # convert focal length to mm...
                        focal = focal * 10.0

                        # create camera...
                        f.write("\n")
                        f.write("// create camera %s...\n" % name)
                        f.write(
                            "string $cameraNodes[] = `camera -name \"%s\" -hfa %.15f  -vfa %.15f -fl %.15f -ncp 0.01 -fcp 10000 -shutterAngle 180 -ff \"overscan\"`;\n"
                            % (name, fback_w, fback_h, focal))
                        f.write("string $cameraTransform = $cameraNodes[0];\n")
                        f.write("string $cameraShape = $cameraNodes[1];\n")
                        f.write(
                            "xform -zeroTransformPivots -rotateOrder zxy $cameraTransform;\n"
                        )
                        f.write(
                            "setAttr ($cameraShape+\".horizontalFilmOffset\") %.15f;\n"
                            % lco_x)
                        f.write(
                            "setAttr ($cameraShape+\".verticalFilmOffset\") %.15f;\n"
                            % lco_y)
                        f.write("setAttr ($cameraShape+\".renderable\") 1;\n")
                        p3d = tde4.getPGroupPosition3D(campg, cam, 1)
                        p3d = convertZup(p3d, yup)
                        f.write(
                            "xform -translation %.15f %.15f %.15f $cameraTransform;\n"
                            % (p3d[0], p3d[1], p3d[2]))
                        r3d = tde4.getPGroupRotation3D(campg, cam, 1)
                        rot = convertToAngles(r3d)
                        f.write(
                            "xform -rotation %.15f %.15f %.15f $cameraTransform;\n"
                            % rot)
                        f.write("xform -scale 1 1 1 $cameraTransform;\n")
                        """add pipeline attributes to camerashape"""
                        # attribs = add_pipeline_attribs() ### OBSOLETE WAY
                        attribs = add_pipeline_parms()
                        f.write(attribs)

                        # image plane...
                        f.write("\n\n\n\n// create image plane...\n")
                        f.write(
                            "string $imagePlane = `createNode imagePlane`;\n")
                        f.write(
                            "cameraImagePlaneUpdate ($cameraShape, $imagePlane);\n"
                        )
                        f.write(
                            "setAttr ($imagePlane + \".offsetX\") %.15f;\n" %
                            lco_x)
                        f.write(
                            "setAttr ($imagePlane + \".offsetY\") %.15f;\n" %
                            lco_y)

                        if camType == "SEQUENCE":
                            f.write(
                                "setAttr ($imagePlane+\".useFrameExtension\") 1;\n"
                            )
                        else:
                            f.write(
                                "setAttr ($imagePlane+\".useFrameExtension\") 0;\n"
                            )

                        f.write(
                            "expression -n \"frame_ext_expression\" -s ($imagePlane+\".frameExtension=frame\");\n"
                        )
                        path = tde4.getCameraPath(cam)
                        sattr = tde4.getCameraSequenceAttr(cam)
                        path = prepareImagePath(path, sattr[0])
                        f.write(
                            "setAttr ($imagePlane + \".imageName\") -type \"string\" \"%s\";\n"
                            % (path))
                        f.write("setAttr ($imagePlane + \".fit\") 4;\n")
                        f.write(
                            "setAttr ($imagePlane + \".displayOnlyIfCurrent\") 1;\n"
                        )
                        f.write(
                            "setAttr ($imagePlane  + \".depth\") (9000/2);\n")

                        # parent camera to scene group...
                        f.write("\n")
                        f.write("// parent camera to scene group...\n")
                        f.write("parent $cameraTransform $sceneGroupName;\n")

                        if camType == "REF_FRAME" and hide_ref:
                            f.write(
                                "setAttr ($cameraTransform +\".visibility\") 0;\n"
                            )

                        # animate camera...
                        if camType != "REF_FRAME":
                            f.write("\n")
                            f.write("// animating camera %s...\n" % name)
                            f.write(playbackoptions)
                            # f.write("playbackOptions -min %d -max %d;\n"%(1+frame0,noframes+frame0))
                            f.write("\n\n")

                        frame = 1
                        while frame <= noframes:
                            # rot/pos...
                            p3d = tde4.getPGroupPosition3D(campg, cam, frame)
                            p3d = convertZup(p3d, yup)
                            r3d = tde4.getPGroupRotation3D(campg, cam, frame)
                            rot = convertToAngles(r3d)
                            if frame > 1:
                                rot = [
                                    angleMod360(rot0[0], rot[0]),
                                    angleMod360(rot0[1], rot[1]),
                                    angleMod360(rot0[2], rot[2])
                                ]
                            rot0 = rot
                            f.write(
                                "setKeyframe -at translateX -t %d -v %.15f $cameraTransform; "
                                % (frame + frame0, p3d[0]))
                            f.write(
                                "setKeyframe -at translateY -t %d -v %.15f $cameraTransform; "
                                % (frame + frame0, p3d[1]))
                            f.write(
                                "setKeyframe -at translateZ -t %d -v %.15f $cameraTransform; "
                                % (frame + frame0, p3d[2]))
                            f.write(
                                "setKeyframe -at rotateX -t %d -v %.15f $cameraTransform; "
                                % (frame + frame0, rot[0]))
                            f.write(
                                "setKeyframe -at rotateY -t %d -v %.15f $cameraTransform; "
                                % (frame + frame0, rot[1]))
                            f.write(
                                "setKeyframe -at rotateZ -t %d -v %.15f $cameraTransform; "
                                % (frame + frame0, rot[2]))

                            # focal length...
                            focal = tde4.getCameraFocalLength(cam, frame)
                            focal = focal * 10.0
                            f.write(
                                "setKeyframe -at focalLength -t %d -v %.15f $cameraShape;\n"
                                % (frame + frame0, focal))

                            frame += 1

                #
                # write camera point group...

                f.write("\n")
                f.write("// create camera point group...\n")
                name = "cameraPGroup_%s_1" % validName(
                    tde4.getPGroupName(campg))
                f.write(
                    "string $pointGroupName = `group -em -name  \"%s\" -parent $sceneGroupName`;\n"
                    % name)
                # f.write("$pointGroupName = ($sceneGroupName + \"|\" + $pointGroupName);\n")
                f.write("\n")

                # write points...
                l = tde4.getPointList(campg)
                for p in l:
                    if tde4.isPointCalculated3D(campg, p):
                        name = tde4.getPointName(campg, p)
                        name = "p%s" % validName(name)
                        p3d = tde4.getPointCalcPosition3D(campg, p)
                        p3d = convertZup(p3d, yup)
                        f.write("\n")
                        f.write("// create point %s...\n" % name)
                        f.write(
                            "string $locator = stringArrayToString(`spaceLocator -name %s`, \"\");\n"
                            % name)
                        f.write("$locator = (\"|\" + $locator);\n")
                        f.write("xform -t %.15f %.15f %.15f $locator;\n" %
                                (p3d[0], p3d[1], p3d[2]))
                        f.write("parent $locator $pointGroupName;\n")

                f.write("\n")
                f.write(
                    "xform -zeroTransformPivots -rotateOrder zxy -scale 1.000000 1.000000 1.000000 $pointGroupName;\n"
                )
                f.write("\n")

                #
                # write object/mocap point groups...

                camera = tde4.getCurrentCamera()
                noframes = tde4.getCameraNoFrames(camera)
                pgl = tde4.getPGroupList()
                index = 1
                for pg in pgl:
                    if tde4.getPGroupType(pg) == "OBJECT" and camera != None:
                        f.write("\n")
                        f.write("// create object point group...\n")
                        pgname = "objectPGroup_%s_%d_1" % (validName(
                            tde4.getPGroupName(pg)), index)
                        index += 1
                        f.write(
                            "string $pointGroupName = `group -em -name  \"%s\" -parent $sceneGroupName`;\n"
                            % pgname)
                        f.write(
                            "$pointGroupName = ($sceneGroupName + \"|\" + $pointGroupName);\n"
                        )

                        # write points...
                        l = tde4.getPointList(pg)
                        for p in l:
                            if tde4.isPointCalculated3D(pg, p):
                                name = tde4.getPointName(pg, p)
                                name = "p%s" % validName(name)
                                p3d = tde4.getPointCalcPosition3D(pg, p)
                                p3d = convertZup(p3d, yup)
                                f.write("\n")
                                f.write("// create point %s...\n" % name)
                                f.write(
                                    "string $locator = stringArrayToString(`spaceLocator -name %s`, \"\");\n"
                                    % name)
                                f.write("$locator = (\"|\" + $locator);\n")
                                f.write(
                                    "xform -t %.15f %.15f %.15f $locator;\n" %
                                    (p3d[0], p3d[1], p3d[2]))
                                f.write("parent $locator $pointGroupName;\n")

                        f.write("\n")
                        scale = tde4.getPGroupScale3D(pg)
                        f.write(
                            "xform -zeroTransformPivots -rotateOrder zxy -scale %.15f %.15f %.15f $pointGroupName;\n"
                            % (scale, scale, scale))

                        # animate object point group...
                        f.write("\n")
                        f.write("// animating point group %s...\n" % pgname)
                        frame = 1
                        while frame <= noframes:
                            # rot/pos...
                            p3d = tde4.getPGroupPosition3D(pg, camera, frame)
                            p3d = convertZup(p3d, yup)
                            r3d = tde4.getPGroupRotation3D(pg, camera, frame)
                            rot = convertToAngles(r3d)
                            if frame > 1:
                                rot = [
                                    angleMod360(rot0[0], rot[0]),
                                    angleMod360(rot0[1], rot[1]),
                                    angleMod360(rot0[2], rot[2])
                                ]
                            rot0 = rot
                            f.write(
                                "setKeyframe -at translateX -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, p3d[0]))
                            f.write(
                                "setKeyframe -at translateY -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, p3d[1]))
                            f.write(
                                "setKeyframe -at translateZ -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, p3d[2]))
                            f.write(
                                "setKeyframe -at rotateX -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, rot[0]))
                            f.write(
                                "setKeyframe -at rotateY -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, rot[1]))
                            f.write(
                                "setKeyframe -at rotateZ -t %d -v %.15f $pointGroupName;\n"
                                % (frame + frame0, rot[2]))

                            frame += 1

                    # mocap point groups...
                    if tde4.getPGroupType(pg) == "MOCAP" and camera != None:
                        f.write("\n")
                        f.write("// create mocap point group...\n")
                        pgname = "objectPGroup_%s_%d_1" % (validName(
                            tde4.getPGroupName(pg)), index)
                        index += 1
                        f.write(
                            "string $pointGroupName = `group -em -name  \"%s\" -parent $sceneGroupName`;\n"
                            % pgname)
                        f.write(
                            "$pointGroupName = ($sceneGroupName + \"|\" + $pointGroupName);\n"
                        )

                        # write points...
                        l = tde4.getPointList(pg)
                        for p in l:
                            if tde4.isPointCalculated3D(pg, p):
                                name = tde4.getPointName(pg, p)
                                name = "p%s" % validName(name)
                                p3d = tde4.getPointMoCapCalcPosition3D(
                                    pg, p, camera, 1)
                                p3d = convertZup(p3d, yup)
                                f.write("\n")
                                f.write("// create point %s...\n" % name)
                                f.write(
                                    "string $locator = stringArrayToString(`spaceLocator -name %s`, \"\");\n"
                                    % name)
                                f.write("$locator = (\"|\" + $locator);\n")
                                f.write(
                                    "xform -t %.15f %.15f %.15f $locator;\n" %
                                    (p3d[0], p3d[1], p3d[2]))
                                for frame in range(1, noframes + 1):
                                    p3d = tde4.getPointMoCapCalcPosition3D(
                                        pg, p, camera, frame)
                                    p3d = convertZup(p3d, yup)
                                    f.write(
                                        "setKeyframe -at translateX -t %d -v %.15f $locator; "
                                        % (frame + frame0, p3d[0]))
                                    f.write(
                                        "setKeyframe -at translateY -t %d -v %.15f $locator; "
                                        % (frame + frame0, p3d[1]))
                                    f.write(
                                        "setKeyframe -at translateZ -t %d -v %.15f $locator; "
                                        % (frame + frame0, p3d[2]))
                                f.write("parent $locator $pointGroupName;\n")

                        f.write("\n")
                        scale = tde4.getPGroupScale3D(pg)
                        f.write(
                            "xform -zeroTransformPivots -rotateOrder zxy -scale %.15f %.15f %.15f $pointGroupName;\n"
                            % (scale, scale, scale))

                        # animate mocap point group...
                        f.write("\n")
                        f.write("// animating point group %s...\n" % pgname)
                        frame = 1
                        while frame <= noframes:
                            # rot/pos...
                            p3d = tde4.getPGroupPosition3D(pg, camera, frame)
                            p3d = convertZup(p3d, yup)
                            r3d = tde4.getPGroupRotation3D(pg, camera, frame)
                            rot = convertToAngles(r3d)
                            if frame > 1:
                                rot = [
                                    angleMod360(rot0[0], rot[0]),
                                    angleMod360(rot0[1], rot[1]),
                                    angleMod360(rot0[2], rot[2])
                                ]
                            rot0 = rot
                            f.write(
                                "setKeyframe -at translateX -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, p3d[0]))
                            f.write(
                                "setKeyframe -at translateY -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, p3d[1]))
                            f.write(
                                "setKeyframe -at translateZ -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, p3d[2]))
                            f.write(
                                "setKeyframe -at rotateX -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, rot[0]))
                            f.write(
                                "setKeyframe -at rotateY -t %d -v %.15f $pointGroupName; "
                                % (frame + frame0, rot[1]))
                            f.write(
                                "setKeyframe -at rotateZ -t %d -v %.15f $pointGroupName;\n"
                                % (frame + frame0, rot[2]))

                            frame += 1

                #
                # global (scene node) transformation...

                p3d = tde4.getScenePosition3D()
                p3d = convertZup(p3d, yup)
                r3d = tde4.getSceneRotation3D()
                rot = convertToAngles(r3d)
                s = tde4.getSceneScale3D()
                f.write(
                    "xform -zeroTransformPivots -rotateOrder zxy -translation %.15f %.15f %.15f -scale %.15f %.15f %.15f -rotation %.15f %.15f %.15f $sceneGroupName;\n\n"
                    %
                    (p3d[0], p3d[1], p3d[2], s, s, s, rot[0], rot[1], rot[2]))

                f.write("\n")
                f.close()
                # tde4.postQuestionRequester("Export Maya...","Project successfully exported.","Ok")
                print '--> successfully exported Maya Mel'
            else:
                tde4.postQuestionRequester("Export Maya...",
                                           "Error, couldn't open file.", "Ok")

    return get_mel_filename()['path']
コード例 #16
0
		we_have_set_widget_callback_function = False

# For older releases we cannot do the smart guessing...
	if we_have_set_widget_callback_function:
		widget_default_initial_frame = tde4.addOptionMenuWidget(nuke_node_req,"option_menu_default_initial_frame","Startframe is based on","Nuke Read Node Default","3DE4 Initial Frame","User-defined")
		tde4.setWidgetValue(nuke_node_req,"option_menu_default_initial_frame",str(value_option_menu_default_initial_frame))
		tde4.setWidgetCallbackFunction(nuke_node_req,"option_menu_default_initial_frame","set_initial_frame_widget")
# Without / before smart-guessing we mimick Nuke's Read Node default behaviour.
	tde4.addTextFieldWidget(nuke_node_req,"text_initial_frame_nuke","Startframe in Nuke",str(tde4.getCameraSequenceAttr(id_cam)[0]))

# After creating all widgets we invoke the Callback once explicitly in order to initialize the text widget.
	if we_have_set_widget_callback_function:
		set_initial_frame_widget(widget_default_initial_frame,None,None)

# post requester
	ret	= tde4.postCustomRequester(nuke_node_req,'Export nuke distortion node for camera ' + tde4.getCameraName(id_cam)+' ',700,0,'Ok','Cancel ')
	if ret != 1:
		raise CancelException('Cancelled')
# At this point we know that user has pressed "Ok". Check path and suffix
	nuke_path = tde4.getWidgetValue(nuke_node_req,'file_nuke_path')
	if not nuke_path:
		raise Exception('No path specified')
	if not nuke_path.endswith('.nk'):
		nuke_path += '.nk'
# Update frame values and calculate offset between 3DE4 and Nuke.
	initial_frame_nuke = int(tde4.getWidgetValue(nuke_node_req,"text_initial_frame_nuke"))
# export
	exportNukeDewarpNode(id_cam,initial_frame_nuke,nuke_path)

except CancelException, e:
	pass
コード例 #17
0
def exportNukeDewarpNode(id_cam,offset,nuke_path):
	id_lens 	= tde4.getCameraLens(id_cam)
	model 	= tde4.getLensLDModel(id_lens)
	num_frames 	= tde4.getCameraNoFrames(id_cam)
	w_fb_cm = tde4.getLensFBackWidth(id_lens)
	h_fb_cm = tde4.getLensFBackHeight(id_lens)
	lco_x_cm = tde4.getLensLensCenterX(id_lens)
	lco_y_cm = tde4.getLensLensCenterY(id_lens)
	pxa = tde4.getLensPixelAspect(id_lens)
# xa,xb,ya,yb in unit coordinates, in this order.
	xa_unit,xb_unit,ya_unit,yb_unit = tde4.getCameraFOV(id_cam)
		
	f = open(nuke_path,"w")
	try:
		f.write('# Created by 3DEqualizer4 using Export Nuke Distortion Nodes export script\n')
		f.write("LD" + nukify_name(model) + ' {\n')
		f.write(' direction undistort\n')
################################
# focal length                 #
################################
		if is_focal_length_dynamic(id_cam):
# write focal length curve if dynamic
#			print 'dynamic focal length'
			f.write(' tde4_focal_length_cm {{curve ')	
			for frame in range(num_frames):
# Internally, frames start at 1.
				focal = tde4.getCameraFocalLength(id_cam,frame + 1)
				f.write ('x%i %.7f ' % (frame + offset,focal))
			f.write('}}\n')
		else:
# write static focal length otherwise
#			print 'static focal length'
			f.write(' tde4_focal_length_cm %.7f \n' % tde4.getCameraFocalLength(id_cam,1))
################################
# focus distance               #
################################
# For Release 1 this function return False, so no problem with getCameraFocus.
		if is_focus_distance_dynamic(id_cam):
# write focus distance curve if dynamic
#			print 'dynamic focus distance'
			f.write(' tde4_custom_focus_distance_cm {{curve ')	
			for frame in range(num_frames):
# Internally, frames start at 1.
				focus = tde4.getCameraFocus(id_cam,frame + 1)
				f.write ('x%i %.7f ' % (frame + offset,focus))
			f.write('}}\n')
		else:
			try:
# write static focus distance otherwise
				f.write(' tde4_custom_focus_distance_cm %.7f \n' % tde4.getCameraFocus(id_cam,1))
			except:
# For Release 1 we simply write out the default value to Nuke.
				f.write(' tde4_custom_focus_distance_cm 100.0 \n')
################################
# built-in parameters          #
################################
# the remaining five built-in parameters
		f.write(' tde4_filmback_width_cm %.7f \n' % w_fb_cm)
		f.write(' tde4_filmback_height_cm %.7f \n' % h_fb_cm)
		f.write(' tde4_lens_center_offset_x_cm %.7f \n' % lco_x_cm)
		f.write(' tde4_lens_center_offset_y_cm %.7f \n' % lco_y_cm)
		f.write(' tde4_pixel_aspect %.7f \n' % pxa)
################################
# field-of-view                #
################################
		f.write(' field_of_view_xa_unit %.7f \n' % xa_unit)
		f.write(' field_of_view_xb_unit %.7f \n' % xb_unit)
		f.write(' field_of_view_ya_unit %.7f \n' % ya_unit)
		f.write(' field_of_view_yb_unit %.7f \n' % yb_unit)
		
# write distortion parameters
#
# dynamic distortion
		dyndistmode = get_dynamic_distortion_mode(id_lens)

		old_api = True
		try:
			for para in getLDmodelParameterList(model):
				tde4.getLensLDAdjustableParameter(id_lens, para, 1)
				break
		except:
			old_api = False

		if old_api:
# dynamic focal length (zoom)
			if dyndistmode=="DISTORTION_DYNAMIC_FOCAL_LENGTH":
#				print 'dynamic lens distortion, focal length'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' {{curve ')	
					for frame in range(num_frames):
# Internally, frames start at 1.
						focal = tde4.getCameraFocalLength(id_cam,frame + 1)
						f.write ('x%i %.7f ' % (frame + offset,tde4.getLensLDAdjustableParameter(id_lens,para,focal)))
					f.write('}}\n')
# dynamic focus distance
			if dyndistmode=="DISTORTION_DYNAMIC_FOCUS_DISTANCE":
#				print 'dynamic lens distortion, focus distance'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' {{curve ')	
					for frame in range(num_frames):
# Older Releases do not have Focus-methods.
						try:
# Internally, frames start at 1.
							focus = tde4.getCameraFocus(id_cam,frame + 1)
						except:
							focus = 100.0
						f.write('x%i %.7f ' % (frame + offset,tde4.getLensLDAdjustableParameter(id_lens,para,focus)))
					f.write('}}\n')
# static distortion
			if dyndistmode=="DISTORTION_STATIC":
#				print 'static lens distortion'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' %.7f \n'%tde4.getLensLDAdjustableParameter(id_lens,para,1))
		else:
# new API
			if dyndistmode=="DISTORTION_STATIC":
#				print 'static lens distortion'
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' %.7f \n'%tde4.getLensLDAdjustableParameter(id_lens,para,1,1))
			else:
#				print 'dynamic lens distortion,'
# dynamic
				for para in getLDmodelParameterList(model):
					f.write(' ' + nukify_name(para) + ' {{curve ')	
					for frame in range(num_frames):
# Internally, frames start at 1.
						focal = tde4.getCameraFocalLength(id_cam,frame + 1)
						focus = tde4.getCameraFocus(id_cam,frame + 1)
						f.write('x%i %.7f ' % (frame + offset,tde4.getLensLDAdjustableParameter(id_lens,para,focal,focus)))
#						print "%i[3DE4] -> %i[Nuke]" % (frame + tde4.getCameraFrameOffset(id_cam),frame + offset)
					f.write('}}\n')


		
		f.write(' name LD_3DE4_' + decode_entities(tde4.getCameraName(id_cam)) + '\n')
		f.write('}\n')

	finally:	
		f.close()	
コード例 #18
0
ファイル: nukeExporter.py プロジェクト: Rotomator/noid
def toNuke(params, oneFile=False):
    log.debug('To Nuke - Start')

    cameras = params['cameras']
    camerasOutSize = params['camerasOutSize']
    camerasFrameStart = params['camerasFirstFrame']

    filesGenerated = []
    argsToBatchs = []

    if oneFile:
        filepath = params['file_browser'] + '_undisto.nk'
        tools.ensure_dir(filepath)
        fileObj = open(filepath, 'w')
        for index, cam in enumerate(cameras):
            fileLines = []
            argsExportNuke = [
                cam, index, camerasOutSize[index], filepath, params['date'],
                camerasFrameStart[index]
            ]

            fileLines, argsToBatch = exportNuke(*argsExportNuke)

            if fileLines == -1:
                # print ("Problem with camera "+ str(cam) )
                continue

            writeLines(fileObj, fileLines)
            argsToBatchs.append(argsToBatch)
        filesGenerated.append(filepath)

    else:
        # create Directory
        folderCameras = params['file_browser'] + '_undisto/'
        try:
            os.makedirs(folderCameras)
        except:
            pass  # Todo check if is only that the folder exists

        for index, cam in enumerate(cameras):
            cameraName = "%s_%s_1" % (tools.validName(
                tde4.getCameraName(cam)), index)
            filepath = folderCameras + cameraName + '_undisto.nk'
            tools.ensure_dir(filepath)
            fileObj = open(filepath, 'w')
            fileLines = []
            argsExportNuke = [
                cam, index, camerasOutSize[index], filepath, params['date'],
                camerasFrameStart[index]
            ]

            fileLines, argsToBatch = exportNuke(*argsExportNuke)

            if fileLines == -1:
                # print ("Problem with camera "+ str(cam) )
                continue

            writeLines(fileObj, fileLines)
            argsToBatchs.append(argsToBatch)
            filesGenerated.append(filepath)

    # Launch batch Render
    log.debug('Launching batch Render')

    import toBatch
    for argsToBatch in argsToBatchs:
        toBatch.batch3DE(*(argsToBatch))
    return filesGenerated

    log.debug('To Nuke - End')