Пример #1
0
def create_front():
    cmds.imagePlane(name="front_IP",
                    width=100,
                    height=100,
                    lookThrough="front",
                    showInAllViews=True)
    cmds.move(0, 0, -950)
def _createCamGate(camera='',
                   pathToImage='I:/lsapipeline/fx/ImageGate_1280_720.png'):
    if not camera:
        camera = utils.getShotCamera()

    if camera:
        if not cmds.objExists('camGate'):
            cmds.imagePlane(n='camGate')
            cmds.rename('camGate1', 'camGate')
            cmds.pointConstraint('%s' % camera,
                                 'camGate',
                                 mo=False,
                                 n='tmpPoint')
            cmds.orientConstraint('%s' % camera,
                                  'camGate',
                                  mo=False,
                                  n='tmpOrient')
            cmds.delete(['tmpPoint', 'tmpOrient'])
            cmds.parent('camGate', '%s' % camera)
            cmds.connectAttr('camGateShape.message',
                             '%sShape.imagePlane[0]' % camera,
                             f=True)
            cmds.setAttr('camGate.depth', 0.01)
            cmds.setAttr('camGate.sizeX', 1.710)
            cmds.setAttr('camGate.sizeY', 2)
            cmds.setAttr('camGate.offsetX', 0.004)
            cmds.setAttr('camGate.offsetY', 0.003)
            cmds.setAttr('camGateShape.imageName', pathToImage, type='string')
            cmds.setAttr('camGateShape.lockedToCamera', 1)
            cmds.setAttr('camGateShape.displayOnlyIfCurrent', 1)
Пример #3
0
def create_back():
    cmds.imagePlane(name="back_IP",
                    width=100,
                    height=100,
                    lookThrough="back",
                    showInAllViews=True)
    cmds.move(0, 0, 950)
    cmds.rotate(0, 180, 0)
Пример #4
0
def create_side():
    cmds.imagePlane(name="side_IP",
                    width=100,
                    height=100,
                    lookThrough="side",
                    showInAllViews=True)
    cmds.move(-950, 0, 0)
    cmds.rotate(0, 90, 0)
Пример #5
0
 def _createCamForSBoard(self, shotName, framePath):
     camName = '%s_shotCam' % shotName
     if cmds.objExists(camName):
         if not cmds.objExists('%s_animaticsCam' % shotName):
             dupCamList = cmds.duplicate(camName)
             for each in dupCamList:
                 if 'shotCam' in each:
                     animCam = cmds.rename(each,
                                           '%s_animaticsCam' % shotName)
                     imagePlaneShape = cmds.imagePlane(n='%s_ip' % shotName,
                                                       c='%sShape' %
                                                       animCam)[-1]
                     cmds.setAttr('%s.imageName' % imagePlaneShape,
                                  '%s' % framePath,
                                  type='string')
                     cmds.setAttr('%s.useFrameExtension' % imagePlaneShape,
                                  1)
         else:
             imagePlanes = cmds.listConnections('%s_animaticsCamShape' %
                                                shotName,
                                                s=1)
             if imagePlanes:
                 imagePlaneShape = [
                     each for each in imagePlanes if 'camGate' not in each
                 ][0]
                 cmds.setAttr('%s.imageName' % imagePlaneShape,
                              '%s' % framePath,
                              type='string')
                 cmds.setAttr('%s.useFrameExtension' % imagePlaneShape, 1)
Пример #6
0
    def createImagePlanes(self, arg):
        """ NOT YET IMPLEMENTED
	    	The idea is to find a way to store camera names in the .chan file from
	    	Photoscan, based on the photo filename, then use that to automatically
	    	create image planes with the appropriate images.
	    """

        path = "/Volumes/hggl_SAN_1/Project_Media/110053_The_Louvre/2009753_The_Louvre/Vfx/PC010/3D/photoscan/sourceImages/charles/atrium_Undistorted/atrium_undistorted/proxy"
        portrait = True

        camLs = mc.ls(sl=True)

        for cam in camLs:
            if portrait:
                hfa = mc.getAttr("%sShape.horizontalFilmAperture" % cam)
                vfa = mc.getAttr("%sShape.verticalFilmAperture" % cam)
                mc.setAttr("%sShape.horizontalFilmAperture" % cam, vfa)
                mc.setAttr("%sShape.verticalFilmAperture" % cam, hfa)
                mc.setAttr("%sShape.filmFit" % cam, 2)

            imagePlane = mc.imagePlane(c="%sShape" % cam,
                                       lt=cam,
                                       n="%s_imagePlane" % cam,
                                       fn="%s/%s.jpg" % (path, cam),
                                       sia=False)
            mc.setAttr("%s.displayOnlyIfCurrent" % imagePlane[1], True)
            mc.setAttr("%s.alphaGain" % imagePlane[1], 0.8)
            mc.setAttr("%s.depth" % imagePlane[1], 256)
Пример #7
0
def createOrUpdatePlayblastCam(frameOffset, moviePath, separateCam = False):
    print "\n\n\creating the cam\n\n\n"
    if separateCam:
        cam = cmds.ls("syncSketchPlayer_camera*")
        print "is separate"
    else:
        cam = get_current_camera()

    imagePlane = cmds.ls("syncSketchPlayer_imageplane*")

    if not(cam and imagePlane):
        cam = cmds.camera(name="syncSketchPlayer_camera")
        cameraShape = cmds.listRelatives(cam, shapes=True)[0]
        imagePlane = cmds.imagePlane(name="syncSketchPlayer_imageplane", camera=cameraShape, quickTime=True,
                                       lookThrough=cameraShape, showInAllViews=False)
        implagePlaneShape = cmds.listRelatives(imagePlane, shapes=True)[0]

    else:
        if cmds.objectType( cam ) != 'camera':
            cameraShape = cmds.listRelatives(cam, shapes=True)[0]
        else:
            cameraShape = cam
        implagePlaneShape = cmds.listRelatives(imagePlane, shapes=True)[0]

    cmds.setAttr(implagePlaneShape + '.imageName', moviePath, type="string")
    cmds.setAttr(implagePlaneShape + '.useFrameExtension', 1)
    cmds.setAttr(implagePlaneShape + '.textureFilter', 1)
    cmds.setAttr(implagePlaneShape + '.type', 2)
    cmds.setAttr(implagePlaneShape + '.frameOffset', 1)
    cmds.setAttr(implagePlaneShape + '.imageName', moviePath, type="string")
Пример #8
0
    def _create_image_plane(self, path, sg_publish_data):
        """
        Create a file texture node for a UDIM (Mari) texture

        :param path: Path to file.
        :param sg_publish_data: Shotgun data dictionary with all the standard
            publish fields.
        :returns: The newly created file node
        """

        app = self.parent

        has_frame_spec, path = self._find_first_frame(path)
        if not path:
            self.parent.logger.error(
                "Could not find file on disk for published file path %s" %
                (path, ))
            return

        # create an image plane for the supplied path, visible in all views
        (img_plane, img_plane_shape) = cmds.imagePlane(fileName=path,
                                                       showInAllViews=True)
        app.logger.debug("Created image plane %s with path %s" %
                         (img_plane, path))

        if has_frame_spec:
            # setting the frame extension flag will create an expression to use
            # the current frame.
            cmds.setAttr("%s.useFrameExtension" % (img_plane_shape, ), 1)
def CreateImgPlane():
    # создаю список из нужных image sequence
    propImgList = []
    
    # наполняю список, чтобы узнать кол-во кадров
    for imgName in GetInfo.imgList:
        if GetInfo.fileName in imgName:
            propImgList.append(imgName)
            imgExists = True
    
    # если image sequence существует для данного файла
    if imgExists == True:
    
        # задаю timeline range равным кол-ву кадров
        propImgList.sort()
        lastImg = propImgList[-1]
        lastImg = lastImg.split('.')
        lastImg = lastImg[0]
        maxTime = lastImg[-2-1:]
        
        cmds.playbackOptions( minTime=0, maxTime=maxTime )
    
        # создаю image plane
        myImagePlane = cmds.imagePlane(w = 22, h = 22)
        cmds.setAttr(myImagePlane[1] + '.type', 0)
        cmds.setAttr(myImagePlane[1] + '.frameOffset', 0)
        cmds.setAttr(myImagePlane[1] + '.useFrameExtension', 1)
        cmds.setAttr(myImagePlane[1] + '.imageName', GetInfo.imgPath, type = 'string')
        
    else:
        print 'Image reference not found'
        
    # перемещаю image plane в нужное место, возле головы
    cmds.delete(cmds.pointConstraint('jaw_LOC', 'imagePlane1'))
    cmds.move(-16, 0, 0, r = True, ls = True, wd = True)
Пример #10
0
def setup_image(sele):
    source_image = cmds.listRelatives(cmds.listRelatives(sele))
    if source_image:
        source_image_shape = cmds.listRelatives(source_image)
        source_image_path = cmds.getAttr('%s.imageName' %source_image[0])    
        
        new_cam_image, new_cam_image_shape = cmds.imagePlane(camera = new_cam, fileName = source_image_path)
        transfer_attr( source_image_shape, new_cam_image_shape, inConnections = True)
        image_sequence(new_cam_image_shape, 0)
Пример #11
0
def imgPlaneCreator():
    #get show, shot, asset, version
    showName = os.getenv('SHOW')
    shotName = os.getenv('SHOT')
    assetName = 'BG_light_flatanim_plate'
    highestVersion = shotgun.getLastVersion(showName, shotName, assetName)[assetName]
    if highestVersion == 0:
        #no light flatanim plate published, set starting path to lib/images
        startPath = '/X/projects/' + showName + '/SHOTS/' + shotName + '/lib/images'
    else:
        #get version name
        if len(str(highestVersion)) == 1:
            versionName = 'v00' + str(highestVersion)
        if len(str(highestVersion)) == 2:
            versionName = 'v0' + str(highestVersion)
        if len(str(highestVersion)) == 3:
            versionName = 'v' + str(highestVersion)
        #create starting path
        startPath = '/X/projects/' + showName + '/SHOTS/' + shotName + '/lib/images/anim/BG_flatanim_plate/' + assetName + '/' + versionName 
    #get render settings
    renderEngine = mc.getAttr("defaultRenderGlobals.ren")
    resWidth = mc.getAttr('defaultResolution.width')
    resHeight = mc.getAttr('defaultResolution.height')
    deviceAspectRatio = mc.getAttr('defaultResolution.deviceAspectRatio')
    #get selected panel
    activePanel = mc.getPanel(withFocus = True)
    if (mc.objectTypeUI(activePanel) == 'modelEditor'):
        #get camera
        activeCam = mc.modelPanel(activePanel, q = True, camera = True)
        camShape = mc.listRelatives(activeCam, shapes = True)
        #get camera info
        camScale = mc.getAttr(camShape[0]+'.cameraScale')
        camAperture = mc.getAttr(camShape[0]+'.horizontalFilmAperture')
        regSizeX = float(camAperture)
        regSizeY = float(camAperture) / float(deviceAspectRatio)
        newSizeX = regSizeX * float(camScale)
        newSizeY = regSizeY * float(camScale)
        #open file browser
        filePath = mc.fileDialog2(fileMode = 1, caption = 'Create Image Plane', dir = startPath)
        #create image plane and setup attributes
        if filePath:
            if (len(filePath) == 1):
                imgPlaneName = mc.imagePlane(camera = camShape[0], fileName = filePath[0])
                mc.setAttr(imgPlaneName[0]+'.useFrameExtension',1)
                mc.setAttr(imgPlaneName[0]+'.depth',5000)
                mc.setAttr(imgPlaneName[0]+'.fit',4)
                mc.setAttr(imgPlaneName[0]+'.coverageX',resWidth)
                mc.setAttr(imgPlaneName[0]+'.coverageY',resHeight)
                if renderEngine == "vray":
                    mc.setAttr(imgPlaneName[0]+'.sizeX',newSizeX)
                    mc.setAttr(imgPlaneName[0]+'.sizeY',newSizeY)
                else:
                    mc.setAttr(imgPlaneName[0]+'.sizeX',regSizeX)
                    mc.setAttr(imgPlaneName[0]+'.sizeY',regSizeY)
    else:
        mc.warning('Please select a view and try again.')
Пример #12
0
def DOIT(*args):
    cameralist = cmds.listCameras()
    imageFile = '/groups2/papa/Rigging'
    for i in cameralist:
        imagePlaneName = cmds.imagePlane(c=i)
        print imagePlaneName
        cmds.setAttr(imagePlaneName[0] + '.imageName', '/groups2/papa/Rigging/theInspiration.JPG', type='string')
        
    
    cmds.warning('Welp, you asked for it.')
Пример #13
0
def DOIT(*args):
    cameralist = cmds.listCameras()
    imageFile = '/groups2/papa/Rigging'
    for i in cameralist:
        imagePlaneName = cmds.imagePlane(c=i)
        print imagePlaneName
        cmds.setAttr(imagePlaneName[0] + '.imageName', '/groups2/papa/Rigging/theInspiration.JPG', type='string')
        
    
    cmds.warning('Welp, you asked for it.')
def _createCamGate(camera = '', pathToImage = ''):
    if not camera:
        camera = getShotCamera()

    if camera:
        if not cmds.objExists('camGate'):
            cmds.imagePlane(n = 'camGate')
            cmds.rename('camGate1', 'camGate')
            cmds.pointConstraint('%s' % camera, 'camGate', mo = False, n ='tmpPoint')
            cmds.orientConstraint('%s' % camera, 'camGate', mo = False, n ='tmpOrient')
            cmds.delete(['tmpPoint', 'tmpOrient'])
            cmds.parent('camGate', '%s' % camera)
            cmds.connectAttr('camGateShape.message', '%sShape.imagePlane[0]' % camera, f = True)
            cmds.setAttr('camGate.depth', 0.01)
            cmds.setAttr('camGate.sizeX', 1.710)
            cmds.setAttr('camGate.sizeY', 2)
            cmds.setAttr('camGate.offsetX', 0.004)
            cmds.setAttr('camGate.offsetY', 0.003)
            cmds.setAttr('camGateShape.imageName', pathToImage, type = 'string')
            cmds.setAttr('camGateShape.lockedToCamera', 1)
            cmds.setAttr('camGateShape.displayOnlyIfCurrent', 1)
Пример #15
0
def apply_imageplane(filename, camera=None):
    import maya.cmds as cmds
    #Get Camera Shapes
    if not camera:
        ssCamera = cmds.camera()[1]

    else:
        # todo: there might be another camera in this hierarchy
        ssCamera = filter((lambda x: x if "Shape" in x else None), cmds.ls(camera, dag=True))[0]

    imagePlane = cmds.imagePlane(camera=ssCamera)
    cmds.setAttr("{}.type".format(imagePlane[1], 2), 2)
    cmds.setAttr("{}.imageName".format(imagePlane[1], 2), filename, type='string')
Пример #16
0
def imagePlane(*args, **kwargs):
    res = cmds.imagePlane(*args, **kwargs)
    if not kwargs.get('query', kwargs.get('q', False)):
        res = _factories.maybeConvert(res, _general.PyNode)
    if isinstance(res, list) and len(res) == 1:
        # unpack for specific query flags
        unpackFlags = {
            'c', 'camera', 'h', 'height', 'lookThrough', 'lt', 'maintainRatio',
            'mr', 'showInAllViews', 'sia', 'w', 'width'
        }
        if kwargs.get('query', kwargs.get(
                'q', False)) and not unpackFlags.isdisjoint(kwargs):
            res = res[0]
    return res
Пример #17
0
def create_imagePlanes():
    front_ip = cmds.imagePlane(
        name="front_IP",
        fileName="front_ref.jpg",
        lookThrough="front",
        showInAllViews=False)
    cmds.move(0,0,-950)
    cmds.createDisplayLayer(name="front_ref_L")
    cmds.imagePlane(
        name="side_IP",
        fileName="side_ref.jpg",
        lookThrough="side",
        showInAllViews=False)
    cmds.move(-950,0,0)
    cmds.rotate(0,90,0)
    cmds.createDisplayLayer(name="side_ref_L")
    cmds.imagePlane(
        name="back_IP",
        fileName="back_ref.jpg",
        lookThrough="back",
        showInAllViews=False)
    cmds.move(0,0,950)
    cmds.rotate(0,180,0)
    cmds.createDisplayLayer(name="back_ref_L")
Пример #18
0
def createImagePlane():
	if cmds.objExists("Environment:Cam"):
		plate = cmds.imagePlane(fileName="../direction/plate.jpg", camera="Environment:Cam")
		cmds.setAttr(plate[1] + ".depth", 1000)
		cmds.setAttr("defaultResolution.lockDeviceAspectRatio", 1)
		width = float(cmds.getAttr(plate[1] + ".coverageX"))
		height = float(cmds.getAttr(plate[1] + ".coverageY"))
		ratio = width/height
		cmds.setAttr("defaultResolution.width", width)
		cmds.setAttr("defaultResolution.height", height)
		cmds.setAttr("defaultResolution.deviceAspectRatio", ratio)
		cmds.setAttr(plate[1] + ".sizeY", cmds.getAttr(plate[1] + ".sizeX") / ratio)
		print "Image plane created successfully. Render resolution updated accordingly."
	else:
		print "Load environment file with a camera before creating image plane"
Пример #19
0
def create_imagePlanes():
    front_ip = cmds.imagePlane(name="front_IP",
                               fileName="front_ref.jpg",
                               lookThrough="front",
                               showInAllViews=False)
    cmds.move(0, 0, -950)
    fnt_layer = cmds.createDisplayLayer(name="front_ref_L")
    cmds.setAttr("{}.displayType".format(fnt_layer), 2)
    cmds.imagePlane(name="side_IP",
                    fileName="side_ref.jpg",
                    lookThrough="side",
                    showInAllViews=False)
    cmds.move(-950, 0, 0)
    cmds.rotate(0, 90, 0)
    side_layer = cmds.createDisplayLayer(name="side_ref_L")
    cmds.setAttr("{}.displayType".format(side_layer), 2)
    cmds.imagePlane(name="back_IP",
                    fileName="back_ref.jpg",
                    lookThrough="back",
                    showInAllViews=False)
    cmds.move(0, 0, 950)
    cmds.rotate(0, 180, 0)
    back_layer = cmds.createDisplayLayer(name="back_ref_L")
    cmds.setAttr("{}.displayType".format(back_layer), 2)
Пример #20
0
def create_imagePlanes():
    front_ip = cmds.imagePlane(name="front_IP",
                               width=100,
                               height=100,
                               lookThrough="front",
                               showInAllViews=False)
    cmds.imagePlane(front_ip, edit=True, showInAllViews=True)
    print(cmds.imagePlane(front_ip, query=True))
    cmds.imagePlane(front_ip, edit=True, showInAllViews=False)
    cmds.move(0, 0, -950)
    cmds.imagePlane(name="side_IP",
                    width=100,
                    height=100,
                    lookThrough="side",
                    showInAllViews=False)
    cmds.move(-950, 0, 0)
    cmds.rotate(0, 90, 0)
    cmds.imagePlane(name="back_IP",
                    width=100,
                    height=100,
                    lookThrough="back",
                    showInAllViews=False)
    cmds.move(0, 0, 950)
    cmds.rotate(0, 180, 0)
Пример #21
0
def cam_bake():

    # creating a fresh camera 
    new_cam,new_cam_shape = cmds.camera(n = 'MM_camera')
    
    # parenting that camera with the selected camera  
    parent_newcam_node = cmds.parentConstraint(sele, new_cam, maintainOffset = False)


    # copying the selected camera image plane values including the sequence path and pasting that in to a newly created image plane which is connected to the new camera. 
    # If no source image available then its directly move on to the bake process. 
    source_image = cmds.listRelatives(cmds.listRelatives(sele))
    if source_image:
        source_image_shape = cmds.listRelatives(source_image)
        source_image_path = cmds.getAttr('%s.imageName' %source_image[0])    
       
        new_cam_image, new_cam_image_shape = cmds.imagePlane(camera = new_cam, fileName = source_image_path)
        cmds.copyAttr( source_image_shape, new_cam_image_shape, inConnections = True, values = True)
        cmds.setAttr ('%s.useFrameExtension'  %new_cam_image_shape, 0)

    # baking the new camera channels and deleting the constraint. 
    cmds.bakeResults( new_cam , time=(StartTime,EndTime) )
    cmds.delete(parent_newcam_node)
    
    # will enable the Image sequence option inside image plane. 
    if source_image:
        cmds.setAttr ('%s.useFrameExtension'  %new_cam_image_shape, 1)

    # transferring the camera setting 
    cmds.copyAttr( sele_shape,new_cam_shape,values = True)

    # cheching for any curves inside the camera shape, this is mainly to get the focal curve incase if available. And pasting that in to the new camera. 
    copy_keys = cmds.copyKey(sele_shape)
    if copy_keys:
        cmds.pasteKey(new_cam_shape)
    
    # creating a new group for the newly created camera. Add that under this group. 
    Render_camera_grp = cmds.group(n = 'RenderCamGroup', empty = True)
    cmds.parent(new_cam, Render_camera_grp)

    # locking the attributes. 
    cam_attr = ['translate', 'rotate', 'scale', 'focalLength', 'horizontalFilmAperture', 'verticalFilmAperture' ]

    for attr in cam_attr:
        cmds.setAttr('%s.%s' % (new_cam, attr) , lock = True)
    for i in range (0,3):
        cmds.setAttr('%s.%s' % (Render_camera_grp, cam_attr[i]) , lock = True)
Пример #22
0
 def _createCamForSBoard(self, shotName, framePath):
     camName = '%s_shotCam' % shotName
     if cmds.objExists(camName):
         if not cmds.objExists('%s_animaticsCam' % shotName):
             dupCamList = cmds.duplicate(camName)
             for each in dupCamList:
                 if 'shotCam' in each:
                     animCam = cmds.rename(each, '%s_animaticsCam' % shotName)
                     imagePlaneShape = cmds.imagePlane(n = '%s_ip' % shotName, c='%sShape' % animCam)[-1]
                     cmds.setAttr('%s.imageName' % imagePlaneShape, '%s' % framePath, type='string')
                     cmds.setAttr('%s.useFrameExtension' % imagePlaneShape, 1)
         else:
             imagePlanes = cmds.listConnections('%s_animaticsCamShape' % shotName, s=1)
             if imagePlanes:
                 imagePlaneShape = [each for each in imagePlanes if 'camGate' not in each][0]
                 cmds.setAttr('%s.imageName' % imagePlaneShape, '%s' % framePath, type='string')
                 cmds.setAttr('%s.useFrameExtension' % imagePlaneShape, 1)
    def _create_image_plane(self, path, sg_publish_data):
        """
        Create a file texture node for a UDIM (Mari) texture

        :param path: Path to file.
        :param sg_publish_data: Shotgun data dictionary with all the standard
            publish fields.
        :returns: The newly created file node
        """

        app = self.parent
        has_frame_spec = False

        # replace any %0#d format string with a glob character. then just find
        # an existing frame to use. example %04d => *
        frame_pattern = re.compile("(%0\dd)")
        frame_match = re.search(frame_pattern, path)
        if frame_match:
            has_frame_spec = True
            frame_spec = frame_match.group(1)
            glob_path = path.replace(frame_spec, "*")
            frame_files = glob.glob(glob_path)
            if frame_files:
                path = frame_files[0]
            else:
                app.logger.error(
                    "Could not find file on disk for published file path %s" %
                    (path,)
                )
                return

        # create an image plane for the supplied path, visible in all views
        (img_plane, img_plane_shape) = cmds.imagePlane(
            fileName=path,
            showInAllViews=True
        )
        app.logger.debug(
            "Created image plane %s with path %s" %
            (img_plane, path)
        )

        if has_frame_spec:
            # setting the frame extension flag will create an expression to use
            # the current frame.
            cmds.setAttr("%s.useFrameExtension" % (img_plane_shape,), 1)
Пример #24
0
    def _create_image_plane(self, path, sg_publish_data):
        """
        Create a file texture node for a UDIM (Mari) texture
        :param path: Path to file.
        :param sg_publish_data: Shotgun data dictionary with all the standard
            publish fields.
        :returns: The newly created file node
        """

        app = self.parent
        has_frame_spec = False

        # replace any %0#d format string with a glob character. then just find
        # an existing frame to use. example %04d => *
        frame_pattern = re.compile("(%0\dd)")
        frame_match = re.search(frame_pattern, path)
        if frame_match:
            has_frame_spec = True
            frame_spec = frame_match.group(1)
            glob_path = path.replace(frame_spec, "*")
            frame_files = glob.glob(glob_path)
            if frame_files:
                path = frame_files[0]
            else:
                app.logger.error(
                    "Could not find file on disk for published file path %s" %
                    (path,)
                )
                return

        # create an image plane for the supplied path, visible in all views
        (img_plane, img_plane_shape) = cmds.imagePlane(
            fileName=path,
            showInAllViews=True
        )
        app.logger.debug(
            "Created image plane %s with path %s" %
            (img_plane, path)
        )

        if has_frame_spec:
            # setting the frame extension flag will create an expression to use
            # the current frame.
            cmds.setAttr("%s.useFrameExtension" % (img_plane_shape,), 1)
Пример #25
0
def main():
    if mc.objExists("*dualImagePlane*"):
        mc.delete("*dualImagePlane*")  # Delete existing "dualImagePlane"
        return

    active3dViewCamShape, active3dViewCamTrans = getActive3dViewCam()

    try:
        active3dViewCamImagePlaneShape = mc.listRelatives(active3dViewCamShape,
                                                          allDescendents=True,
                                                          type='imagePlane',
                                                          fullPath=True)[0]
        active3dViewCamImagePlaneShapeImageName = mc.getAttr(
            active3dViewCamImagePlaneShape + '.imageName')
    except:
        mc.warning("No image plane found in current view.")
        return

    dualImagePlaneTrans = mc.imagePlane(
        name="dualImagePlane",
        sia=False,
        fileName=active3dViewCamImagePlaneShapeImageName,
        camera=active3dViewCamTrans)[0]
    dualImagePlaneShape = mc.listRelatives(dualImagePlaneTrans,
                                           shapes=True,
                                           fullPath=True)[0]

    mc.setAttr(dualImagePlaneShape + '.useFrameExtension', 1)
    mc.setAttr(dualImagePlaneShape + '.frameCache',
               mc.getAttr(active3dViewCamImagePlaneShape + '.frameCache'))
    mc.setAttr(dualImagePlaneShape + '.alphaGain', 0.5)

    # Depth Expression
    mc.expression(s="{0}.depth = {1}.nearClipPlane + 1".format(
        dualImagePlaneShape, active3dViewCamShape),
                  object=dualImagePlaneTrans)

    mc.AttributeEditor()
Пример #26
0
def create_imagePlanes():
    cmds.imagePlane(name="front_IP",
                    width=100,
                    height=100,
                    lookThrough="front",
                    showInAllViews=True)
    cmds.move(0, 0, -950)
    cmds.imagePlane(name="side_IP",
                    width=100,
                    height=100,
                    lookThrough="side",
                    showInAllViews=True)
    cmds.move(-950, 0, 0)
    cmds.rotate(0, 90, 0)
    cmds.imagePlane(name="back_IP",
                    width=100,
                    height=100,
                    lookThrough="back",
                    showInAllViews=True)
    cmds.move(0, 0, 950)
    cmds.rotate(0, 180, 0)
Пример #27
0
def playblast(filename="C:/Users/jhwan/Desktop/test1.avi", stName='amoogae'):
    basedir = os.path.dirname(os.path.realpath(__file__))
    imagePlaneFile = os.path.join(basedir, 'logo.png')

    #check existing huds
    allHuds = cmds.headsUpDisplay(lh=True)
    allHudInfo = {}
    for hud in allHuds:
        hudInfo = {}
        if cmds.headsUpDisplay(hud, visible=True, q=True):
            if not cmds.headsUpDisplay(hud, preset=True, q=True) == 'noPreset':
                hudInfo['section'] = cmds.headsUpDisplay(hud,
                                                         section=True,
                                                         q=True)
                hudInfo['block'] = cmds.headsUpDisplay(hud, block=True, q=True)
                hudInfo['preset'] = cmds.headsUpDisplay(hud,
                                                        preset=True,
                                                        q=True)
                allHudInfo[hud] = hudInfo

    #remove existing hudes
    for hud in allHuds:
        cmds.headsUpDisplay(hud, rem=True)

    try:
        cmds.headsUpDisplay('HUDFrame',
                            section=8,
                            block=0,
                            blockAlignment='center',
                            dataWidth=40,
                            preset='currentFrame')
    except:
        pass

    try:
        cmds.headsUpDisplay('HUDFocalLength',
                            section=6,
                            block=0,
                            blockAlignment='center',
                            dataWidth=40,
                            preset='focalLength')
    except:
        pass

    try:
        cmds.headsUpDisplay('HUDStudentName',
                            section=7,
                            block=0,
                            blockAlignment='center',
                            dataWidth=40,
                            label=stName)
    except:
        pass

    # adding logo
    currentCam = cmds.lookThru(q=True)
    imgPlane = cmds.imagePlane(camera=currentCam, fileName=imagePlaneFile)

    # check for grid
    isGridOn = False
    if cmds.grid(toggle=True, q=True):
        cmds.grid(toggle=False)
        isGridOn = True

    cmds.playblast(filename=filename,
                   format='avi',
                   sequenceTime=0,
                   clearCache=1,
                   viewer=1,
                   showOrnaments=1,
                   fp=4,
                   percent=100,
                   compression="MS-CRAM",
                   quality=100,
                   widthHeight=(1280, 720))

    # back to original
    if cmds.headsUpDisplay('HUDFrame', exists=True):
        cmds.headsUpDisplay('HUDFrame', remove=True)
    if cmds.headsUpDisplay('HUDFocalLength', exists=True):
        cmds.headsUpDisplay('HUDFocalLength', remove=True)
    if cmds.headsUpDisplay('HUDStudentName', exists=True):
        cmds.headsUpDisplay('HUDStudentName', remove=True)

    #delete logo
    cmds.delete(imgPlane)

    if isGridOn:
        cmds.grid(toggle=True)

    import pprint
    pprint.pprint(allHudInfo)
    #recover huds
    for hud in allHudInfo.keys():
        try:
            cmds.headsUpDisplay(hud,
                                section=allHudInfo[hud]['section'],
                                block=allHudInfo[hud]['block'],
                                blockAlignment='center',
                                preset=allHudInfo[hud]['preset'])
        except:
            cmds.headsUpDisplay(hud,
                                section=allHudInfo[hud]['section'],
                                block=allHudInfo[hud]['block'],
                                blockAlignment='center')
Пример #28
0
def sequence_cameras(cameras, start_frame=1001, img_sequence=None):
    """
    Creates an uber camera from input cameras

    :param cameras(models.Camera list): list of camera objects
    :param start_frame(int): Frame to start animation

    :raises: None

    :return: None
    :rtype: NoneType
    """
    uber_cam = cmds.camera(name="uber_cam")
    uber_cam[0] = cmds.rename(uber_cam[0], "uber_cam")
    uber_cam[1] = cmds.listRelatives(uber_cam[0], children=True)[0]

    imgPlane = cmds.imagePlane(camera=uber_cam[1])
    cmds.imagePlane(imgPlane[1], edit=True, showInAllViews=False)
    imgPlane[0] = cmds.rename(imgPlane[0], "uber_IMGPLNE")
    imgPlane[1] = cmds.listRelatives(imgPlane[0], children=True)[0]

    cmds.setAttr("%s.fit" % imgPlane[1], 4)
    cmds.setAttr("%s.displayOnlyIfCurrent" % imgPlane[1], 1)
    cmds.connectAttr("%s.horizontalFilmAperture" % uber_cam[1],
                     "%s.sizeX" % imgPlane[1])
    cmds.connectAttr("%s.verticalFilmAperture" % uber_cam[1],
                     "%s.sizeY" % imgPlane[1])

    for t, cam in enumerate(cameras):

        frameNumber = (t + start_frame)
        translation = cam.translation
        rotation = cam.rotation

        for i, direction in enumerate(["X", "Y", "Z"]):

            cmds.setKeyframe(uber_cam[0],
                             value=translation[i],
                             attribute="translate%s" % direction,
                             inTangentType="spline",
                             outTangentType="spline",
                             time=frameNumber)

            cmds.setKeyframe(uber_cam[0],
                             value=rotation[i],
                             attribute="rotate%s" % direction,
                             inTangentType="spline",
                             outTangentType="spline",
                             time=frameNumber)

        cmds.setKeyframe(uber_cam[1],
                         value=cam.focal_length,
                         attribute="focalLength",
                         inTangentType="spline",
                         outTangentType="spline",
                         time=frameNumber)

        filmback = cam.filmback

        cmds.setKeyframe(uber_cam[1],
                         value=filmback[0],
                         attribute="horizontalFilmAperture",
                         inTangentType="spline",
                         outTangentType="spline",
                         time=frameNumber)

        cmds.setKeyframe(uber_cam[1],
                         value=filmback[1],
                         attribute="verticalFilmAperture",
                         inTangentType="spline",
                         outTangentType="spline",
                         time=frameNumber)

    cmds.refresh()

    return uber_cam
Пример #29
0
def gt_import_fspy_json(json_path,
                        image_path,
                        convert_up_axis_z_to_y=True,
                        lock_camera=True,
                        set_scene_resolution=True):
    '''
    Imports the data from a JSON file exported out of fSpy
    It creates a camera and an image plane and use the read data to update it.
    
            Parameters:
                json_path (string): A path pointing to the json file exported out of fSpy
                image_path (string): A path pointing to the image used in fSpy (must be the same one used for the JSON)
                convert_up_axis_z_to_y (bool): Converts the Up Axis of the camera to be +Y instead of +Z
                lock_camera (bool): Locks the default channels: Translate, Rotate and Scale for the camera.
                set_scene_resolution (bool): Uses the resolution from the image to set the scene resolution.

    '''
    function_name = 'GT fSpy Importer'
    cmds.undoInfo(openChunk=True, chunkName=function_name)
    try:
        # Read json_file
        with open(json_path) as json_file:
            json_data = json.load(json_file)
            
        # Create a camera an group it
        group = cmds.group( em=True, name='camera_fspy_grp' )
        camera_transform, camera_shape = cmds.camera(dr=True, overscan=1.3)
        cmds.parent(camera_transform, group)

        # Apply Matrix
        xform_matrix_list = []
        rows = json_data['cameraTransform']['rows']
        matrix = zip(rows[0],rows[1],rows[2],rows[3])

        for number in matrix:
            xform_matrix_list += number

        cmds.xform(camera_transform, matrix=xform_matrix_list)
        
        # Create Image Plane
        image_transform, image_shape = cmds.imagePlane(camera=camera_transform)
        cmds.setAttr(image_shape + '.imageName', image_path, type='string')
        
        # Compute Focal Length
        fov_horizontal = json_data['horizontalFieldOfView']
        fov_vertical = json_data['verticalFieldOfView']

        image_width = json_data['imageWidth']
        image_height = json_data['imageHeight']

        aspect_ratio = float(image_width) / float(image_height)
        h_aperture = float(24) # 36 x 24 (35mm) default in Maya
        v_aperture = h_aperture * aspect_ratio

        tan = math.tan((fov_horizontal / 2.0))
        focal_length = v_aperture / (2.0 * tan)

        cmds.setAttr(camera_shape + '.fl', focal_length)
        
        if convert_up_axis_z_to_y:
            cmds.rotate(-90, 0 ,0, group)
            cmds.makeIdentity(group, apply=True, r=1)
            message = 'Camera <span style=\"color:#FF0000;text-decoration:underline;\"> +Z </span> was converted to <span style=\"color:#FF0000;text-decoration:underline;\"> +Y </span>'
            cmds.inViewMessage(amg=message, pos='botLeft', fade=True, alpha=.9)
            
        if lock_camera:
            for attr in ['t', 'r', 's']:
                for axis in ['x', 'y', 'z']:
                    cmds.setAttr(camera_transform + '.' + attr + axis, lock=True)
                    cmds.setAttr(image_transform + '.' + attr + axis, lock=True)
                    
        if set_scene_resolution:
            cmds.setAttr( "defaultResolution.width", int(image_width) )
            cmds.setAttr( "defaultResolution.height", int(image_height) )
            cmds.setAttr( "defaultResolution.pixelAspect", 1 )
            cmds.setAttr( "defaultResolution.dar", aspect_ratio )
            message = 'Scene resolution changed to: <span style=\"color:#FF0000;text-decoration:underline;\">' +  str(image_width) + 'x'  +  str(image_height) +' </span>'
            cmds.inViewMessage(amg=message, pos='botLeft', fade=True, alpha=.9)
        
        camera_transform = cmds.rename(camera_transform, 'camera_fspy')
        
    except Exception as e:
        raise e
    finally:
        cmds.undoInfo(closeChunk=True, chunkName=function_name)
Пример #30
0
    def process(self, instance):
        shotAssetsDir = instance.data['shotAssetPath']

        versionDir = instance.data['vprefix'] + instance.data['version']

        cameraFile = os.path.join(shotAssetsDir, 'camera', 'renderCam.abc')

        publishDir = os.path.join(instance.data['publishDir'], versionDir)

        envFile = os.path.join(instance.data['publishDir'], 'env.mb')
        charFile = os.path.join(publishDir, 'char.mb')
        animFile = os.path.join(publishDir, 'animation_publish.mb')
        if 'image_planes' in instance.data:
            imagePlanes = instance.data['image_planes']
        else:
            imagePlanes = []

        metadata = instance.data['metadata']
        metadata['version'] = versionDir
        metadata['renderCam'] = cameraFile
        if os.path.exists(envFile):
            metadata['publish_env_file'] = envFile
        else:
            metadata['publish_env_file'] = ''
        if os.path.exists(charFile):
            metadata['publish_char_file'] = charFile
        else:
            metadata['publish_char_file'] = ''
        metadata['publish_anim_file'] = animFile
        instance.set_data('metadata', value=metadata)

        instance.context.set_data('nextTask', value='Animation')

        if os.path.exists(animFile):
            os.remove(animFile)

        mayaScript = "import maya.cmds as cmds;" \
                     "import maya.mel as mel;" \
                     "import maya.standalone; " \
                     "maya.standalone.initialize('Python'); " \
                     "cmds.loadPlugin('AbcImport');"
        if os.path.exists(charFile):
            copyfile(charFile, animFile)
            mayaScript += "cmds.file('%s', o=True, f=True);" % animFile
        else:
            mayaScript += "cmds.file(new=True, f=True);" \
                          "cmds.file(rename='%s');" % animFile

        audioNodes = cmds.ls(type='audio')
        if len(audioNodes) > 0:
            soundFile = cmds.sound(audioNodes[0], file=True, query=True)
            soundOffset = cmds.sound(audioNodes[0], offset=True, query=True)
            mayaScript += "cmds.file('%s', i=True, type='audio', options='o=%s');" % \
                          (soundFile, soundOffset)

        if os.path.exists(envFile):
            mayaScript += "cmds.file('%s', r=True);" % envFile

        if os.path.exists(cameraFile):
            mayaScript += "cmds.AbcImport('%s', mode='import');" % cameraFile

        if len(imagePlanes) > 0:
            for imagePlane in imagePlanes:
                imageName = imagePlane.split('->')[-1]
                imagePath = cmds.getAttr(imagePlane + '.imageName')
                imageSeq = cmds.getAttr(imagePlane + '.useFrameExtension')
                frameOffset = cmds.getAttr(imagePlane + '.frameOffset')
                imageSizeX = cmds.getAttr(imagePlane + '.sizeX')
                imageSizeY = cmds.getAttr(imagePlane + '.sizeY')
                imageOffsetX = cmds.getAttr(imagePlane + '.offsetX')
                imageOffsetY = cmds.getAttr(imagePlane + '.offsetY')
                camera = cmds.imagePlane(imagePlane, camera=True, query=True)[0]
                if imageName == 'imagePlane1':
                    mayaScript += "cmds.imagePlane(camera='%s');" % camera
                else:
                    mayaScript += "cmds.imagePlane(camera='%s', name='%s');" % (camera, imageName)
                mayaScript += "cmds.setAttr('%s.imageName', '%s', type='string');" % (imagePlane,
                                                                                      imagePath)
                mayaScript += "cmds.setAttr('%s.useFrameExtension', %s);" % (imagePlane, imageSeq)
                mayaScript += "cmds.setAttr('%s.frameOffset', %s);" % (imagePlane, frameOffset)
                mayaScript += "cmds.setAttr('%s.sizeX', %s);" % (imagePlane, imageSizeX)
                mayaScript += "cmds.setAttr('%s.sizeY', %s);" % (imagePlane, imageSizeY)
                mayaScript += "cmds.setAttr('%s.offsetX', %s);" % (imagePlane, imageOffsetX)
                mayaScript += "cmds.setAttr('%s.offsetY', %s);" % (imagePlane, imageOffsetY)

        mayaScript += "cmds.file(save=True, type='mayaBinary', force=True);" \
                      "cmds.quit();" \
                      "os._exit(0)"

        print mayaScript

        mayapyPath = instance.context.data['mayapy']
        if mayapyPath == '' or not os.path.exists(mayapyPath):
            self.log.error('mayapy not found. Unable to publish file.')
            raise pyblish.api.ExtractionError

        maya = subprocess.Popen(mayapyPath + ' -c "%s"' % mayaScript, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, shell=True)
        out, err = maya.communicate()
        exitcode = maya.returncode
        if str(exitcode) != '0':
            self.log.error('Unable to publish file.')
            raise pyblish.api.ExtractionError
        else:
            self.log.info('Anim Publish Successful.')
Пример #31
0
def changeCommand_func(cameras, path):
    imagePlane = maya.imagePlane(cameras[0], q=1, n=True)[0]
    maya.setAttr(imagePlane + ".imageName", path, type="string")
Пример #32
0
def mvgSetImagePlane(cameraShape, imageFile):
    import maya.cmds as cmds
    imagePlaneName = cmds.imagePlane(camera=cameraShape)
    cmds.setAttr( "%s.imageName" % imagePlaneName[0], imageFile, type="string")
Пример #33
0
def copy_bake_camera(cam, replace_cam=False):
    # camName = cam
    camShape = cmds.listRelatives(cam, typ='camera')[0]
    garbages = []
    keyables = cmds.listAttr(cam, camShape, keyable=True)
    keyables += cmds.listAttr(cam, st=['rotateOrder', '*Pivot*'])
    # roMapping = ('xyz', 'yzx', 'zxy', 'xzy', 'yxz', 'zyx')
    # roCurrent = roMapping[cmds.getAttr(cam + '.rotateOrder')]
    # roIndex = roMapping.index(roGiven)
    parents = cmds.listRelatives(cam, parent=True, fullPath=True)
    # copy camera and cleanup children
    dup_cam = cmds.duplicate(cam, name=cam + '_baked', returnRootsOnly=True)[0]
    childs = cmds.listRelatives(dup_cam,
                                children=True,
                                typ='transform',
                                fullPath=True)
    if childs:
        cmds.delete(childs)
    # unlock new camera
    for attr in keyables:
        cmds.setAttr(dup_cam + '.' + attr, lock=False)
    # parent attrs may also have been locked somehow...
    for attr in 'trs':
        cmds.setAttr(dup_cam + '.' + attr, lock=False)
    # unparent and cleanup pivots
    if parents:
        dup_cam = cmds.parent(dup_cam, w=True)[0]
    cmds.xform(dup_cam, zeroTransformPivots=True)
    cmds.makeIdentity(dup_cam,
                      apply=True,
                      translate=True,
                      rotate=True,
                      scale=True)
    # contraint new camera to original one and set rotateOrder
    garbages.extend(cmds.parentConstraint(cam, dup_cam, maintainOffset=True))
    # cmds.setAttr(dup_cam + '.rotateOrder', roIndex)
    # connect imagePlane to dup_cam
    imagePlane = cmds.imagePlane(cam, q=True, name=True)
    if imagePlane:
        imagePlane = imagePlane[0]
        cmds.imagePlane(imagePlane, detach=True, edit=True)
        cmds.imagePlane(camera=dup_cam, edit=True)
    # copy focal animation if exist
    if cmds.copyKey(cam, at='fl'):
        cmds.pasteKey(dup_cam, at='fl')
    # cleanup old camera
    if replace_cam:
        # check existence
        existing = cmds.ls(cam)
        if existing:
            # if cmds.confirmDialog(message='%s already exists, do you want to replace it?' %
            #         cam, button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') == 'Yes':
            garbages.extend(existing)

    # unlock camera
    for attr in keyables:
        cmds.setAttr(dup_cam + '.' + attr, lock=False)
    # make sure the curves on camera continue on for motion blur
    time_range = get_time_range_in_slider()
    cmds.bakeResults(dup_cam, t=time_range)
    cmds.delete(dup_cam, staticChannels=True)
    cmds.filterCurve(dup_cam)
    cmds.keyTangent(dup_cam, itt='spline', ott='spline')
    # master.extendKeyframes([dup_cam])
    # cleanup garbages
    if garbages:
        cmds.delete(garbages)
        while parents:
            if not cmds.listConnections(parents[0]) \
                    and not cmds.listRelatives(parents[0], children=True):
                parent = parents[0]
                parents = cmds.listRelatives(parent,
                                             parent=True,
                                             fullPath=True)
                cmds.delete(parent)
            else:
                break
    # set key at startFrame if attr has no animation
    for attr in cmds.listAttr(dup_cam,
                              camShape,
                              keyable=True,
                              st=['translate*', 'rotate*', 'focalLength']):
        if not cmds.listConnections(dup_cam + '.' + attr, destination=False):
            cmds.setKeyframe(dup_cam,
                             itt='spline',
                             ott='spline',
                             attribute=attr,
                             t=time_range[0])
    # set scale and visibility
    for attr in cmds.listAttr(dup_cam,
                              keyable=True,
                              st=['scale*', 'visibility']):
        cmds.delete(dup_cam + '.' + attr, icn=True)
        cmds.setAttr(dup_cam + '.' + attr, 1)
    # set camera clip range
    l_objs = cmds.ls(typ='mesh')
    l_objs.append(dup_cam)
    l_bbox = cmds.exactWorldBoundingBox(l_objs)
    maxDist = math.sqrt((l_bbox[3] - l_bbox[0])**2 +
                        (l_bbox[4] - l_bbox[1])**2 +
                        (l_bbox[5] - l_bbox[2])**2)
    farClip = math.ceil(maxDist) * 2
    nearClip = 0.1
    cmds.setAttr(dup_cam + '.farClipPlane', farClip)
    cmds.setAttr(dup_cam + '.nearClipPlane', nearClip)
    # lock attributes
    for attr in keyables:
        cmds.setAttr(dup_cam + '.' + attr, lock=True)
    # look through cam and rename
    # pane = cmds.playblast(activeEditor=True)
    # pane = pane if not pane.count('|') else pane.split('|')[-1]
    # cmds.modelPanel(pane, e=True, camera=dup_cam)
    # camName = cmds.rename(cam, camName)
    # # create motion trail
    # if cmds.menuItem(master.ui['mtrailCB'], q=True, checkBox=True):
    #     if not cmds.listConnections(camName, t='snapshot', d=True):
    #         l_cameraPath = cmds.snapshot(camName,
    #                                      ch=True,
    #                                      st=master.getStartFrame(),
    #                                      et=master.getEndFrame(),
    #                                      motionTrail=True)
    #         camPath = cmds.rename(l_cameraPath[0], camName + '_path')
    #         if cmds.objExists('|layout|misc'):
    #             cmds.parent(camPath, '|layout|misc')
    # # cleanup horizon line
    # curves = cmds.ls('horizon*', exactType='transform')
    # for c in curves:
    #     if cmds.attributeQuery('camera', node=c, exists=True) and not cmds.listConnections(c + '.camera'):
    #         cmds.delete(c)
    # # create horizon line
    # plugs = cmds.listConnections(camName + '.message', plugs=True, d=True)
    # if not plugs or not any(i.endswith('.camera') for i in plugs):
    #     if cmds.menuItem(master.ui['horizonRenderCB'], query=True, checkBox=True):
    #         horizon = cmds.polyCylinder(radius=1, height=1,
    #                                     name='horizon_mesh1',
    #                                     subdivisionsX=50, subdivisionsY=5, subdivisionsZ=0,
    #                                     axis=(0, 1, 0), createUVs=False, constructionHistory=False)[0]
    #         cmds.delete(horizon + '.f[250:251]')
    #         cmds.addAttr(horizon, longName='depth', attributeType='double', minValue=0.1, defaultValue=1)
    #         cmds.setAttr(horizon + '.depth', keyable=True)
    #         cmds.expression(o=horizon, name=horizon + '_expr',
    #                         string=('sx = sz = depth;'
    #                                 'sy = (20/defaultResolution.height)'
    #                                 '* (%s.verticalFilmAperture*depth/%s.focalLength);' % (camName, camName)))
    #         setupHorizon(horizon, camName)
    #     if cmds.menuItem(master.ui['horizonCB'], query=True, checkBox=True):
    #         horizon = cmds.circle(normal=(0, 1, 0),
    #                               name='horizon_curve1',
    #                               constructionHistory=False)[0]
    #         setupHorizon(horizon, camName)

    return dup_cam
def changeCommand_func(cameras, path):
    imagePlane = maya.imagePlane(cameras[0], q=1, n=True)[0]
    #print imagePlane
    newpath = path.replace('\\', '/')
    maya.setAttr(imagePlane + ".imageName", newpath, type="string")
Пример #35
0
cameralist = maya.listCameras()                                                                         #获得当前相机列表
cameralist.remove('persp');cameralist.remove('front');cameralist.remove('top');cameralist.remove('side');
cameralist.reverse()
eistr = []
for i in cameralist:
	eistr.append([cameralist.index(i),i])                                                               #获得ei字符串

cameraenum = maya.attrEnumOptionMenu(w = 100, ei = eistr)                                               #建立一个下拉框显示过滤后的camera
cameraindex = maya.attrEnumOptionMenu(cameraenum,q=1,npm=True)

for i in eistr:
	if i[0] == cameraindex:
		thisCamera = i[1]                                                                               #获得当前camera
		break

if maya.imagePlane(thisCamera,q= 1,camera=True):
    thisImagePlane = maya.imagePlane(thisCamera,q = 1,n = True)[0]                                          #获得当前plane
else:
	maya.imagePlane(thisCamera,camera=thisCamera)
	thisImagePlane = maya.imagePlane(thisCamera,q = 1,n = True)[0]                                          #获得当前plane


maya.button(label="Replace sequence",w = 100,command = 'selected_node = maya.ls(sl=1);\
file_value = maya.textField(file,q = 1,tx = 1);\
picture = maya.getFileList(folder = file_value)[1] if file_value.find(".") == -1 else "";\
maya.setAttr(thisImagePlane+".imageName",file_value + picture,type="string");\
framecache_value = maya.intSliderGrp(cacheframe,q=True,v = True);\
maya.setAttr(thisImagePlane+".frameCache",framecache_value);\
imageSizelist = maya.imagePlane(thisCamera,q=1,imageSize=1);\
maya.textField(targetsizewidth,tx = imageSizelist[0] ,w=100,edit=True,enterCommand=("maya.setFocus(\'" + targetsizeheight + "\')"));\
maya.textField(targetsizeheight,tx = imageSizelist[1] ,w=100,edit=True,enterCommand=("maya.setFocus(\'" + sourcesizewidth + "\')"));\
Пример #36
0
def center3d():
    """
    Centers the viewport to TLOC.
    This may not work properly if the Image Plane's Aspect Ratio and Device Aspect Ratio(in Render Setting) does not match.
    Image Plane Size: 1920 X 1080 (1.778)  and  Image Size: 1920 X 1080 (1.778) --> O
    Image Plane Size: 1920 X 1080 (1.778)  and  Image Size: 960 X 540 (1.778) --> O
    Image Plane Size: 1920 X 1080 (1.778) and  Image Size: 3000 X 1500 (1.5) --> X
    """
    # Get selected transform list
    selTransformList = mc.ls(selection=True, long=True)
    if len(selTransformList) == 0:
        mc.warning("Select one or more Transform Nodes")
        return

    # Check if imagePlane is in selection list
    for selTransform in selTransformList:
        objectType = getObjectType(selTransform)
        if objectType == "imagePlane":
            mc.warning("Can't Center3D an image plane")
            return

    # Get Active 3D View Camera
    active3dViewCamShape, active3dViewCamTrans = getActive3dViewCam()

    active3dViewCamTrans = mc.listRelatives(active3dViewCamShape,
                                            parent=True,
                                            fullPath=True)[0]
    try:
        active3dViewCamImgPlaneShape = mc.listRelatives(active3dViewCamShape,
                                                        allDescendents=True,
                                                        type='imagePlane')[0]
    except:
        active3dViewCamImgPlaneShape = None

    # Set Imageplane to show in "All Views"
    if active3dViewCamImgPlaneShape is not None:
        mc.imagePlane(active3dViewCamImgPlaneShape,
                      e=True,
                      showInAllViews=True)

    # Create Center3D Locator
    center3dLoc = mc.spaceLocator(name='center3d_#')[0]
    mc.setAttr(center3dLoc + '.v', 0)

    for selTransform in selTransformList:
        mc.pointConstraint(selTransform, center3dLoc, maintainOffset=False)

    # Create Center3D Camera
    center3dCam = mc.camera(name=active3dViewCamTrans + center3dLoc)[0]
    center3DcamTrans = mc.ls(mc.parent(center3dCam,
                                       active3dViewCamTrans,
                                       relative=True),
                             long=True)[0]
    center3DcamShape = mc.listRelatives(center3DcamTrans,
                                        shapes=True,
                                        fullPath=True)[0]

    # LookThru Center3D Camera
    panelWithFocus = mc.getPanel(withFocus=True)
    mc.lookThru(panelWithFocus, center3DcamShape)

    # Sync Shape Attributes. Active 3D View Cam & Center 3D Cam
    mc.connectAttr(active3dViewCamShape + '.hfa', center3DcamShape + '.hfa')
    mc.connectAttr(active3dViewCamShape + '.vfa', center3DcamShape + '.vfa')
    mc.connectAttr(active3dViewCamShape + '.fl', center3DcamShape + '.fl')
    mc.connectAttr(active3dViewCamShape + '.nearClipPlane',
                   center3DcamShape + '.nearClipPlane')
    mc.connectAttr(active3dViewCamShape + '.farClipPlane',
                   center3DcamShape + '.farClipPlane')

    # Center3D Expression
    exp = 'global proc float[] cTtransformPoint(float $mtx[], float $pt[]) // multiply 4x4 matrix with 4x vector\n'
    exp += '{\n'
    exp += '    float $res[] = {};\n'
    exp += '    if(`size $pt` == 3)\n'
    exp += '    $pt[3] = 1.0;\n'
    exp += '    for($i=0;$i<4;$i++){\n'
    exp += '    float $tmp = 0;\n'
    exp += '    for($k=0;$k<4;$k++){\n'
    exp += '        $tmp += $pt[$k] * $mtx[$k * 4 + $i];\n'
    exp += '    };\n'
    exp += '    $res[$i] = $tmp;\n'
    exp += '    };\n'
    exp += '    return $res;\n'
    exp += '};\n'

    exp += 'global proc float[] cGetProjectionMatrix(string $shape) //get camera projection matrix\n'
    exp += '{\n'
    exp += '    float $res[] = {};\n'
    exp += '    if(`objExists $shape` && `nodeType $shape` == "camera"){\n'
    exp += '    python "import maya.OpenMaya as om";\n'
    exp += '    python "list = om.MSelectionList()";\n'
    exp += '    python (' + '"' + 'list.add(' + "'" + '"' + '+ $shape + ' + '"' + "')" + '");\n'
    exp += '    python "depNode = om.MObject()";\n'
    exp += '    python "list.getDependNode(0, depNode)";\n'
    exp += '    python "camFn = om.MFnCamera(depNode)";\n'
    exp += '    python "pMtx = om.MFloatMatrix()";\n'
    exp += '    python "pMtx = camFn.projectionMatrix()";\n'
    exp += '    for($i=0;$i<=3;$i++){\n'
    exp += '        for($k=0;$k<=3;$k++)\n'
    exp += '        $res[`size $res`] = `python ("pMtx(" + $i + ", " + $k + ")")`;\n'
    exp += '    };\n'
    exp += '    };\n'
    exp += '    return $res;\n'
    exp += '};\n'

    exp += 'global proc float[] cWorldSpaceToImageSpace(string $camera, float $worldPt[])\n'
    exp += '{\n'
    exp += '    string $camShape[] = `ls -dag -type "camera" $camera`;\n'
    exp += '    if(! `size $camShape`)\n'
    exp += '    return {};\n'
    exp += '    string $cam[] = `listRelatives -p -f $camShape`;\n'
    exp += '    float $cam_inverseMatrix[] = `getAttr ($cam[0] + ".worldInverseMatrix")`;\n'
    exp += '    float $cam_projectionMatrix[] = `cGetProjectionMatrix $camShape[0]`;\n'
    exp += '    float $ptInCamSpace[] = `cTtransformPoint $cam_inverseMatrix $worldPt`;\n'
    exp += '    float $projectedPoint[] = `cTtransformPoint $cam_projectionMatrix $ptInCamSpace`;\n'
    exp += '    float $resultX = (($projectedPoint[0] / $projectedPoint[3]));\n'
    exp += '    float $resultY = (($projectedPoint[1] / $projectedPoint[3]));\n'
    exp += '    return {$resultX, $resultY};\n'
    exp += '};\n'

    exp += 'float $xy[] = cWorldSpaceToImageSpace("' + active3dViewCamTrans + '", {' + center3dLoc + '.translateX,' + center3dLoc + '.translateY,' + center3dLoc + '.translateZ});\n'
    exp += center3DcamShape + '.horizontalFilmOffset = ($xy[0] *' + active3dViewCamShape + '.hfa)/2 ;\n'
    exp += center3DcamShape + '.verticalFilmOffset = ($xy[1] *' + active3dViewCamShape + '.vfa)/2 ;\n'

    mc.expression(s=exp, object=center3DcamShape)

    # Select Center3D Loc ##
    mc.select(center3dLoc, replace=True)