Пример #1
0
def takeSnapShot(targetObj, renderPath, rotX=-30.0, rotY=45.0, rotZ=0.0, resX=300, resY=300, useBoundingBox=False):
	'''
	Take a snapshot of the selected object using the Maya renderer then move the image to a directory
	'''
	
	# build the bounding box and find it's centre
	bBox = targetObj
	if useBoundingBox is True:
		bBox = buildBoundingBoxGeo(targetObj, noChildren=False, ignoreInv=True)
	focusPoint = cmds.xform(bBox, query=True, ws=True, t=True)
	
	# build the camera the move and orient it
	tempCam = cmds.camera(ar=True, ff=3, fl=35)
	camName = tempCam[1]
	cmds.setAttr(camName+'.renderable', True)
	cmds.setAttr(camName+'.displayFilmGate', True)
	cmds.setAttr(camName+'.displayResolution', True)
	cmds.setAttr(camName+'.backgroundColor', 0.5, 0.5, 0.5, type='double3') #transform
	cmds.move(focusPoint[0], focusPoint[1], focusPoint[2], tempCam, ws=True) 
	cmds.rotate( rotX, rotY, rotZ, tempCam, ws=True)
	
	# build the bounding box then fit the camera
	cmds.select(bBox, r=True)
	cmds.viewFit(camName, an = False, f = 0.9 )
	if useBoundingBox is True:
		cmds.delete(bBox)
	
	# set the render globals
	cmds.currentTime(1)
	cmds.setAttr('defaultRenderGlobals.imageFormat', 8)
	cmds.setAttr('defaultRenderQuality.edgeAntiAliasing', 0)
	cmds.setAttr('defaultRenderQuality.shadingSamples', 2)
	cmds.setAttr('defaultRenderQuality.maxShadingSamples', 8)
	cmds.setAttr('defaultRenderQuality.useMultiPixelFilter', 1)
	cmds.setAttr('defaultRenderQuality.enableRaytracing', 0)
	
	# build the lightrig
	lightRigGrp = cmds.group(em=True, name='lightRigGroup')
	lightMain = cmds.directionalLight(rotation=(-20, -45, 0), intensity=0.8)
	lightFill = cmds.directionalLight(rotation=(-20, 45, 0), intensity=0.4)
	lightUnder = cmds.directionalLight(rotation=(75, 0, 0), intensity=0.15)
	lightKey = cmds.directionalLight(rotation=(-25, 145, 0), intensity=4.0)
	cmds.parent([lightMain, lightFill, lightUnder, lightKey], lightRigGrp)
	cmds.rotate( rotX, rotY, rotZ, lightRigGrp, ws=True)
	
	# select everything, build the special shader, render, then delete everything
	cmds.select([targetObj, lightRigGrp], r=True)
	renderLayerName = cmds.createRenderLayer(name='tempSnapShot_rlayer', mc=True)
	shaderNodes = buildReverseNormalShader() #build the shader
	cmds.sets(targetObj, e=True, forceElement=shaderNodes[0]) #adding the shader here means it's in the render layer
	tempImage= cmds.render(camName, layer=renderLayerName, x=resX, y=resY)
	cmds.editRenderLayerGlobals(currentRenderLayer='defaultRenderLayer')
	cmds.delete([lightRigGrp, tempCam[0], renderLayerName, shaderNodes[0], shaderNodes[1], shaderNodes[2], shaderNodes[3]])
	
	# copy the thumbnail to the desired location
	output = cmds.sysFile(tempImage, rename=renderPath)
	if output==True:
		print 'Path for thumbnail: ' + renderPath
		return renderPath
	return None
Пример #2
0
def snapShot(cam, objs, renderPath):
	
    # build the lightrig
    lightRigGrp = cmds.group(em=True, name='lightRigGroup')
    lightMain = cmds.directionalLight(rotation=(-20, -45, 0), intensity=0.8)
    lightFill = cmds.directionalLight(rotation=(-20, 45, 0), intensity=0.4)
    lightUnder = cmds.directionalLight(rotation=(75, 0, 0), intensity=0.15)
    lightKey = cmds.directionalLight(rotation=(-25, 145, 0), intensity=4.0)
    cmds.parent([lightMain, lightFill, lightUnder, lightKey], lightRigGrp)
	
    # select everything, build the special shader, render, then delete everything
    renderLayerName = cmds.createRenderLayer(name='tempSnapShot_rlayer', empty=True, mc=True)

    cmds.editRenderLayerMembers(renderLayerName, objs)
    cmds.editRenderLayerMembers(renderLayerName, lightRigGrp)
    
    shaderNodes = buildTempShader() #build the shader
    cmds.sets(objs, e=True, forceElement=shaderNodes[0]) #adding the shader here means it's in the render layer
  
    tempImage= cmds.render(cam, layer=renderLayerName)
    
    cmds.editRenderLayerGlobals(currentRenderLayer='defaultRenderLayer')
 
    cmds.delete(lightRigGrp, cam, renderLayerName)
    cmds.delete(shaderNodes)
    
    # copy the thumbnail to the desired location
    output = cmds.sysFile(tempImage, rename=renderPath)
    if output==True:
        print 'Path for thumbnail: ' + renderPath
        return renderPath

    return None
Пример #3
0
    def testMetallicResponse(self):
        cmds.file(force=True, new=True)
        mayaUtils.loadPlugin("mayaUsdPlugin")

        cmds.xform("persp", t=(0, 0, 50))
        cmds.xform("persp", ro=[0, 0, 0], ws=True)

        # Create Test Spheres
        for i in range(5):
            for j in range(5):
                sphere_xform = cmds.polySphere()[0]
                cmds.move(2.5 * (i - 2),
                          2.5 * (j - 2),
                          0,
                          sphere_xform,
                          absolute=True)

                material_node = cmds.shadingNode("usdPreviewSurface",
                                                 asShader=True)
                material_sg = cmds.sets(
                    renderable=True,
                    noSurfaceShader=True,
                    empty=True,
                    name=material_node + "SG",
                )
                cmds.connectAttr(
                    material_node + ".outColor",
                    material_sg + ".surfaceShader",
                    force=True,
                )
                cmds.sets(sphere_xform, e=True, forceElement=material_sg)

                cmds.setAttr(material_node + ".diffuseColor",
                             0.944,
                             0.776,
                             0.373,
                             type="double3")
                cmds.setAttr(material_node + ".useSpecularWorkflow", False)
                cmds.setAttr(material_node + ".metallic", i * 0.25)
                roughness = j * 0.25
                if j == 0:
                    roughness = 0.001
                cmds.setAttr(material_node + ".roughness", roughness)

        blue_light = cmds.directionalLight(rgb=(0, 0.6069, 1))
        blue_transform = cmds.listRelatives(blue_light, parent=True)[0]
        cmds.xform(blue_transform, ro=(-45, -45, 0), ws=True)

        orange_light = cmds.directionalLight(rgb=(1, 0.2703, 0))
        orange_transform = cmds.listRelatives(orange_light, parent=True)[0]
        cmds.xform(orange_transform, ro=(-45, 45, 0), ws=True)

        panel = mayaUtils.activeModelPanel()
        cmds.modelEditor(panel, edit=True, lights=False, displayLights="all")

        if int(os.getenv("MAYA_LIGHTAPI_VERSION")) == 2:
            self.assertSnapshotClose("testMetallicResponseLightAPI2.png")
        else:
            self.assertSnapshotClose("testMetallicResponseLightAPI1.png")
Пример #4
0
    def create(self):
        origName = 'rimLight'
        numberSuffix = 0

        if origName in cmds.ls():
            numberSuffix = 1
            while origName + str(numberSuffix) in cmds.ls():
                numberSuffix = numberSuffix + 1

        if numberSuffix == 0:
            uniqueName = origName
        else:
            uniqueName = origName + str(numberSuffix)

        cmds.directionalLight(name=uniqueName)
        cmds.select(cl=True)
        if uniqueName == origName:
            shapeName = uniqueName + 'Shape'
        else:
            shapeName = origName + 'Shape' + str(numberSuffix)
        cmds.select(shapeName, r=True)
        cmds.addAttr(sn='rimIntensity', defaultValue=1, h=False, k=True)
        cmds.addAttr(sn='sensitivity', defaultValue=0.5, h=False, k=True)
        cmds.addAttr(sn='start', defaultValue=0, h=False, k=True)
        cmds.addAttr(sn='end', defaultValue=1, h=False, k=True)
        cmds.addAttr(sn='startIntensity', defaultValue=3, h=False, k=True)
        cmds.addAttr(sn='endIntensity', defaultValue=0, h=False, k=True)

        #Create new nodes for shading of light
        remapName = uniqueName + '_remapValue'
        cmds.createNode('remapValue', name=remapName)
        samplerName = uniqueName + '_samplerInfo'
        cmds.createNode('samplerInfo', name=samplerName)

        #set attributes of newly created nodes
        cmds.setAttr(remapName + '.value[0].value_FloatValue', 1)
        cmds.setAttr(remapName + '.value[1].value_FloatValue', 0)
        cmds.setAttr(remapName + '.value[0].value_Interp', 2)

        #connect attributes
        cmds.connectAttr(samplerName + '.normalCameraZ',
                         remapName + '.inputValue')
        cmds.connectAttr(shapeName + '.startIntensity',
                         remapName + '.value[0].value_FloatValue')
        cmds.connectAttr(shapeName + '.endIntensity',
                         remapName + '.value[1].value_FloatValue')
        cmds.connectAttr(shapeName + '.start',
                         remapName + '.value[0].value_Position')
        cmds.connectAttr(shapeName + '.end',
                         remapName + '.value[1].value_Position')
        cmds.connectAttr(shapeName + '.rimIntensity', remapName + '.outputMax')
        cmds.connectAttr(shapeName + '.sensitivity', remapName + '.inputMax')
        cmds.connectAttr(remapName + '.outValue', shapeName + '.intensity')

        cmds.setAttr(shapeName + '.intensity', keyable=False, channelBox=False)

        cmds.select(uniqueName, r=True)
Пример #5
0
    def create(self):
        origName = "rimLight"
        numberSuffix = 0

        if origName in cmds.ls():
            numberSuffix = 1
            while origName + str(numberSuffix) in cmds.ls():
                numberSuffix = numberSuffix + 1

        if numberSuffix == 0:
            uniqueName = origName
        else:
            uniqueName = origName + str(numberSuffix)

        cmds.directionalLight(name=uniqueName)
        cmds.select(cl=True)
        if uniqueName == origName:
            shapeName = uniqueName + "Shape"
        else:
            shapeName = origName + "Shape" + str(numberSuffix)
        cmds.select(shapeName, r=True)
        cmds.addAttr(sn="rimIntensity", defaultValue=1, h=False, k=True)
        cmds.addAttr(sn="sensitivity", defaultValue=0.5, h=False, k=True)
        cmds.addAttr(sn="start", defaultValue=0, h=False, k=True)
        cmds.addAttr(sn="end", defaultValue=1, h=False, k=True)
        cmds.addAttr(sn="startIntensity", defaultValue=3, h=False, k=True)
        cmds.addAttr(sn="endIntensity", defaultValue=0, h=False, k=True)

        # Create new nodes for shading of light
        remapName = uniqueName + "_remapValue"
        cmds.createNode("remapValue", name=remapName)
        samplerName = uniqueName + "_samplerInfo"
        cmds.createNode("samplerInfo", name=samplerName)

        # set attributes of newly created nodes
        cmds.setAttr(remapName + ".value[0].value_FloatValue", 1)
        cmds.setAttr(remapName + ".value[1].value_FloatValue", 0)
        cmds.setAttr(remapName + ".value[0].value_Interp", 2)

        # connect attributes
        cmds.connectAttr(samplerName + ".normalCameraZ", remapName + ".inputValue")
        cmds.connectAttr(shapeName + ".startIntensity", remapName + ".value[0].value_FloatValue")
        cmds.connectAttr(shapeName + ".endIntensity", remapName + ".value[1].value_FloatValue")
        cmds.connectAttr(shapeName + ".start", remapName + ".value[0].value_Position")
        cmds.connectAttr(shapeName + ".end", remapName + ".value[1].value_Position")
        cmds.connectAttr(shapeName + ".rimIntensity", remapName + ".outputMax")
        cmds.connectAttr(shapeName + ".sensitivity", remapName + ".inputMax")
        cmds.connectAttr(remapName + ".outValue", shapeName + ".intensity")

        cmds.setAttr(shapeName + ".intensity", keyable=False, channelBox=False)

        cmds.select(uniqueName, r=True)
Пример #6
0
def createRenderEnvironment():
    lightName = cmds.directionalLight(name='scenic_light1', intensity=0.5)
    cmds.move(0, 2500, 0, lightName)
    cmds.rotate('-45deg', '-45deg', 0, lightName)

    lightName = cmds.directionalLight(name='scenic_light2', intensity=0.5)
    cmds.move(0, 2500, 0, lightName)
    cmds.rotate('-45deg', '135deg', 0, lightName)

    floorName, shape = cmds.polyPlane(width=10000, height=10000, name='floor')
    shader, shaderEngine = createShader('Floor_Surface', 'surfaceShader', (1.0, 1.0, 1.0))
    cmds.select(floorName)
    cmds.sets(forceElement=shaderEngine)
Пример #7
0
    def actionCmd(self, *args):

        #create turntable
        mc.polyCylinder(h=0.223, r=6.44)
        #create lights
        self.light1 = mc.directionalLight()
        mc.xform(t=(2.265, 6.358, -6.81), ro=(-139.31, -12.398, 31.896))
        self.light2 = mc.directionalLight()
        mc.xform(t=(7.9, 7.7, 0), ro=(-71.7, 22.8, -41.0))
        self.light3 = mc.directionalLight()
        mc.xform(t=(-2.3, 7.1, 7.5), ro=(-43.9, -12.4, 31.9))

        self.animateCam()
Пример #8
0
    def testShadowsAndSSAO(self):
        cmds.file(force=True, new=True)
        mayaUtils.loadPlugin("mayaUsdPlugin")

        cmds.xform("persp", t=(10, 10, 10))
        cmds.xform("persp", ro=[-30, 45, 0], ws=True)

        testFile = testUtils.getTestScene("UsdPreviewSurface",
                                          "LightAPI_Test.usda")
        mayaUtils.createProxyFromFile(testFile)

        white_light = cmds.directionalLight(rgb=(1, 1, 1))
        white_transform = cmds.listRelatives(white_light, parent=True)[0]
        cmds.xform(white_transform, ro=(-35, 0, 0), ws=True)

        if int(os.getenv("MAYA_LIGHTAPI_VERSION")) == 2:
            light_api = "V2"
        else:
            light_api = "V1"

        panel = mayaUtils.activeModelPanel()
        cmds.modelEditor(panel, edit=True, lights=False, displayLights="all")
        cmds.setAttr("hardwareRenderingGlobals.ssaoEnable", False)
        cmds.modelEditor(panel, edit=True, shadows=False)

        self.assertSnapshotClose('LightAPI_{}.png'.format(light_api))

        cmds.setAttr("hardwareRenderingGlobals.ssaoEnable", True)
        self.assertSnapshotClose('SSAO_LightAPI_{}.png'.format(light_api))

        cmds.modelEditor(panel, edit=True, shadows=True)
        self.assertSnapshotClose('Shadow_LightAPI_{}.png'.format(light_api))

        cmds.setAttr("hardwareRenderingGlobals.ssaoEnable", False)
        cmds.modelEditor(panel, edit=True, shadows=False)
Пример #9
0
def addSun():
    if cmds.objExists("SUN") == 0:
        newSun = cmds.directionalLight(n="SUN")
        newSunTransform = cmds.listRelatives(newSun, p=True, type="transform")
        lightGrp = makeGroup('LIGHTS')
        cmds.parent(newSunTransform, lightGrp)
    else:
        cmds.select("SUN", r=True)
Пример #10
0
def directionalLight(*args, **kwargs):
    """
    Maya Bug Fix:
      - name flag was ignored
    """

    if kwargs.get('query', kwargs.get('q', False)) or kwargs.get(
            'edit', kwargs.get('e', False)):
        return cmds.directionalLight(*args, **kwargs)

    else:
        name = kwargs.pop('name', kwargs.pop('n', False))
        if name:
            tmp = cmds.directionalLight(*args, **kwargs)
            tmp = cmds.rename(cmds.listRelatives(tmp, parent=1)[0], name)
            return _general.PyNode(cmds.listRelatives(tmp, shapes=1)[0])

    return _general.PyNode(cmds.directionalLight(*args, **kwargs))
def create_light(*args):

    light_name = args[0]
    if not(cmds.objExists(light_name)):
        # Create a directional light
        if args[1] == "dir":
            light = cmds.directionalLight( n=args[0],rotation=(-60, 5, 30))

            # Change the light intensity
            cmds.directionalLight( light, e=True, intensity=1 ,sc = (1,1,1), rs = 0)
            mel.eval( "setAttr " + light+".useDepthMapShadows 1;")
            mel.eval( "setAttr " + light+".dmapBias 10;")
            l_t = cmds.listRelatives(light, p=True)
            
        if args[1] == "pt":
            light = cmds.pointLight( n=args[0])
            cmds.pointLight (light, e=True, intensity = 1, rs=1)
            l_t = cmds.listRelatives(light, p=True)
            cmds.setAttr(l_t[0]+".ty", 20)
            
    return light_name
Пример #12
0
    def createLight(self, lightObj, name):
        if lightObj.lightType == "Directional":
            light = mc.directionalLight(name=name, rgb=lightObj.color, intensity=lightObj.intensity,
                                 rs=lightObj.castShadows)
        elif lightObj.lightType == "Point":
            light = mc.pointLight(name=name, rgb=lightObj.color, intensity=lightObj.intensity,
                                 rs=lightObj.castShadows)
        else:
            light = mc.spotLight(name=name, coneAngle=45, rgb=lightObj.color, intensity=lightObj.intensity,
                                 rs=lightObj.castShadows)

        return light
Пример #13
0
def basic(*args):
    """creates a basic 6 light light rig for interiors, probably unnecessary now..."""
    if (not cmds.ls('lights')):
        cmds.group(name='lights', em=True, w=True)
    cool = [.8, .85, 1]
    warm = [1, .88, .8]
    north = cmds.directionalLight(n='lFill_fromSouthOnNorth', rgb=cool, i=.2)
    cmds.setAttr(
        cmds.listRelatives(north, type='transform', p=True)[0] + '.ry', 180)
    south = cmds.directionalLight(n='lFill_fromNorthOnSouth', rgb=cool, i=.2)
    east = cmds.directionalLight(n='lFill_fromWestOnEast', rgb=cool, i=.2)
    cmds.setAttr(
        cmds.listRelatives(east, type='transform', p=True)[0] + '.ry', 90)
    west = cmds.directionalLight(n='lFill_fromEastOnWest', rgb=cool, i=.2)
    cmds.setAttr(
        cmds.listRelatives(west, type='transform', p=True)[0] + '.ry', -90)
    sky = cmds.directionalLight(n='lFill_fromFloorOnSky', rgb=warm, i=.1)
    cmds.setAttr(
        cmds.listRelatives(sky, type='transform', p=True)[0] + '.rx', 90)
    floor = cmds.directionalLight(n='lFill_fromSkyOnFloor', rgb=cool, i=.2)
    cmds.setAttr(
        cmds.listRelatives(floor, type='transform', p=True)[0] + '.rx', -90)
    amb = cmds.ambientLight(n='lAmb_onSet', i=.01)
    cmds.parent(cmds.ls(type='light'), 'lights')
    refresh()
Пример #14
0
    def createLight(self, lightNodeType, lightName, *args, **kwargs):
        preCreationSelection = mc.ls(sl=True, long=True)
        if len(preCreationSelection) < 1:
            preCreationSelection = None
        else:
            preCreationSelection = preCreationSelection[0]

        if lightNodeType == 'spotLight':
            shapeNode = mc.spotLight(name=lightName)
        elif lightNodeType == 'directionalLight':
            shapeNode = mc.directionalLight(name=lightName)
        elif lightNodeType == 'pointLight':
            shapeNode = mc.pointLight(name=lightName)
        elif lightNodeType == 'ambientLight':
            shapeNode = mc.ambientLight(name=lightName)
        elif lightNodeType == 'volumeLight':
            initNode = mc.createNode('volumeLight')
            transform = mc.listRelatives(initNode, parent=True,
                                         fullPath=True)[0]
            result = mc.rename(transform, lightName)
            shapeNode = mc.listRelatives(result,
                                         shapes=True,
                                         noIntermediate=True,
                                         type='light')[0]
        elif lightNodeType == 'areaLight':
            initNode = mc.createNode('areaLight')
            transform = mc.listRelatives(initNode, parent=True,
                                         fullPath=True)[0]
            result = mc.rename(transform, lightName)
            shapeNode = mc.listRelatives(result,
                                         shapes=True,
                                         noIntermediate=True,
                                         type='light')[0]
        else:
            return None
        if shapeNode:
            transformNode = mc.listRelatives(shapeNode, parent=True)[0]
            self.alignLight(transformNode, preCreationSelection)
            tools.setDefaultAttrs(shapeNode)

            try:
                self.post_fn.postLightCreation(transformNode, shapeNode, *args,
                                               **kwargs)
            except:
                tools.logger.exception(
                    "Post light creation function not executed due to exceptions"
                )
            finally:
                return transformNode, shapeNode
        else:
            return None
Пример #15
0
def addLight(kind, *args):
	if(not cmds.ls('lights')):
		cmds.group(name='lights', em=True, w=True)
	if kind == 'spot':
		newLight = cmds.spotLight()
	elif kind == 'dir':
		newLight = cmds.directionalLight()
	elif kind == 'point':
		newLight = cmds.pointLight()
	elif kind == 'amb':
		newLight = cmds.ambientLight()
	elif kind == 'area':
		newLight = cmds.shadingNode ('areaLight', asLight=True)
	cmds.parent(newLight, 'lights')
	refresh()
Пример #16
0
def setup_objects():
    if cmds.objExists(g_ffxNormalMapLightingRig):
        cmds.delete(g_ffxNormalMapLightingRig)
    light_x = cmds.directionalLight(rgb=[1, 0, 0], rotation=(0, 90, 0),  name="directionalLightX")
    light_y = cmds.directionalLight(rgb=[0, 1, 0], rotation=(-90, 0, 0), name="directionalLightY")
    light_z = cmds.directionalLight(rgb=[0, 0, 1], rotation=(0, 0, 0),   name="directionalLightZ")
    cmds.group(light_x, light_y, light_z, name=g_ffxNormalMapLightingRig)
    set_nm_rig_direction()

    required_objs = ["defaultRenderGlobals", "fumeFXShape1", "directionalLightX", "directionalLightY", "directionalLightZ"]
    for obj in required_objs:
        if not cmds.objExists(obj):
            cmds.warning("Object '{}' is not exists.".format(obj))
            return

    cmds.scriptJob(attributeChange=['directionalLightXShape.intensity', "SceneTweaks.sync_nm_rig_intensity('X')\nSceneTweaks.update_ui()"], parent=g_window)
    cmds.scriptJob(attributeChange=['directionalLightYShape.intensity', "SceneTweaks.sync_nm_rig_intensity('Y')\nSceneTweaks.update_ui()"], parent=g_window)
    cmds.scriptJob(attributeChange=['directionalLightZShape.intensity', "SceneTweaks.sync_nm_rig_intensity('Z')\nSceneTweaks.update_ui()"], parent=g_window)
    cmds.scriptJob(attributeChange=['fumeFXShape1.sh_shadow_falloff',   "SceneTweaks.update_ui()"], parent=g_window)
    cmds.scriptJob(          event=["timeChanged",                      "SceneTweaks.update_ui()"], parent=g_window)
    cmds.scriptJob(attributeChange=['defaultRenderGlobals.startFrame',  "SceneTweaks.update_ui()"], parent=g_window)
    cmds.scriptJob(attributeChange=['defaultRenderGlobals.endFrame',    "SceneTweaks.update_ui()"], parent=g_window)

    update_ui()
Пример #17
0
def add_light(kind, *args):
    """adds a new light, organizes it, and refreshes the UI"""
    if (not cmds.ls('lights')):
        cmds.group(name='lights', em=True, w=True)
    if kind == 'spot':
        new_light = cmds.spotLight()
    elif kind == 'dir':
        new_light = cmds.directionalLight()
    elif kind == 'point':
        new_light = cmds.pointLight()
    elif kind == 'amb':
        new_light = cmds.ambientLight()
    elif kind == 'area':
        new_light = cmds.shadingNode('areaLight', asLight=True)
    cmds.parent(new_light, 'lights')
    refresh()
Пример #18
0
def add_light(kind, *args):
    """adds a new light, organizes it, and refreshes the UI"""
    if(not cmds.ls('lights')):
        cmds.group(name='lights', em=True, w=True)
    if kind == 'spot':
        new_light = cmds.spotLight()
    elif kind == 'dir':
        new_light = cmds.directionalLight()
    elif kind == 'point':
        new_light = cmds.pointLight()
    elif kind == 'amb':
        new_light = cmds.ambientLight()
    elif kind == 'area':
        new_light = cmds.shadingNode ('areaLight', asLight=True)
    cmds.parent(new_light, 'lights')
    refresh()
Пример #19
0
def makeLights(daytime, name_):
    '''
    Creates lights for the city.
    
    daytime: Boolean variable which is true if it is day and false if it is night.
    On exit: A directional light has been created and rotated randomly. If daytime
             is true a ambient light has also been created.    
    '''
    light = cmds.directionalLight(name = name_ + "directionalLight", rs = True)
    rotatex = random.randint(-90,0)
    rotatey = random.randint(0,360)
    cmds.xform(name_ + "directionalLight", rotation = (rotatex,rotatey,0), translation = (0,50,0),relative = True, ws = True)
    if daytime == False:
        cmds.setAttr(light + ".intensity", 0.05)
    else:
        light2 = cmds.ambientLight(name = name_ + "ambientLight",intensity = 0.5)
        cmds.xform(name_ + "ambientLight", translation = (0,50,0))
Пример #20
0
    def keepRenderGlobalInfo(self):
        
        self._imageFormat = cmds.getAttr( self._renderGlobalNode+'.imageFormat' )
        self._imagePrefix = cmds.getAttr( self._renderGlobalNode+'.imageFilePrefix' )
        self._baseImageAnimValue = cmds.getAttr( self._renderGlobalNode+'.animation' )
        if not self._imagePrefix: self._imagePrefix = ''
        

        ambientShape = cmds.ambientLight( i=0.0 )
        directShape  = cmds.directionalLight( i=1.5 )
        ambient = cmds.listRelatives( ambientShape, p=1 )[0]
        direct  = cmds.listRelatives( directShape,  p=1 )[0]
        
        self._lights = [ ambient, direct ]
        
        mtx = cmds.getAttr( self._cam + '.wm' )
        cmds.xform( direct, ws=1, matrix=mtx )
        cmds.refresh()
Пример #21
0
def lightingMode():
    light = 'dmptools_temp_directional_light'
    sel = cmds.ls(sl=True)
    if not sel:
        raise UserWarning('Please select something!')

    if not cmds.ls(light):
        light = cmds.directionalLight(name='dmptools_temp_directional_light')
    selM = cmds.xform(sel[0], q=True, matrix=True)
    lightT = cmds.listRelatives(light, p=True)[0]

    cmds.setAttr(light+'.locatorScale', 0.01)
    cmds.xform(lightT, matrix=selM)
    
    rotateCtx = cmds.manipRotateContext()
    cmds.setToolTo(rotateCtx)
    
    setSelectedLights()
Пример #22
0
    def keepRenderGlobalInfo(self):

        self._imageFormat = cmds.getAttr(self._renderGlobalNode +
                                         '.imageFormat')
        self._imagePrefix = cmds.getAttr(self._renderGlobalNode +
                                         '.imageFilePrefix')
        self._baseImageAnimValue = cmds.getAttr(self._renderGlobalNode +
                                                '.animation')
        if not self._imagePrefix: self._imagePrefix = ''

        ambientShape = cmds.ambientLight(i=0.0)
        directShape = cmds.directionalLight(i=1.5)
        ambient = cmds.listRelatives(ambientShape, p=1)[0]
        direct = cmds.listRelatives(directShape, p=1)[0]

        self._lights = [ambient, direct]

        mtx = cmds.getAttr(self._cam + '.wm')
        cmds.xform(direct, ws=1, matrix=mtx)
        cmds.refresh()
def  createTestShapes():
  import maya.cmds as cmds

  if cmds.objExists('domeTestLight'): 
    print('Removing existing Domemaster3D object: domeTestLight')
    cmds.select( 'domeTestLight', replace=True)
    cmds.delete()

  if cmds.objExists('polyTestSphere'): 
    print('Removing existing Domemaster3D object: polyTestSphere')
    cmds.select( 'polyTestSphere', replace=True)
    cmds.delete()

  if cmds.objExists('polyTestCube'): 
    print('Removing existing Domemaster3D object: polyTestCube')
    cmds.select( 'polyTestCube', replace=True)
    cmds.delete()

  test_sphere_name = cmds.polySphere( name='polyTestSphere', radius=24, subdivisionsX=20, subdivisionsY=20, axis=(0, 1, 0),  createUVs=2, constructionHistory=True)
  cmds.setAttr(test_sphere_name[0]+'.translateX', 80)
  cmds.setAttr(test_sphere_name[0]+'.translateY', 75)

  #Smooth the render time polygon sphere shape
  cmds.displaySmoothness( test_sphere_name, divisionsU=3, divisionsV=3, pointsWire=16, pointsShaded=4, polygonObject=3 )

  test_cube_name = cmds.polyCube( name='polyTestCube', width=40, height=40, depth=40, subdivisionsX=1, subdivisionsY=1, subdivisionsZ=1, axis=(0, 1, 0),  createUVs=4, constructionHistory=True)
  cmds.setAttr(test_cube_name[0]+'.translateX', 0)
  cmds.setAttr(test_cube_name[0]+'.translateY', 75)
  cmds.setAttr(test_cube_name[0]+'.translateZ', -80)
  cmds.setAttr(test_cube_name[0]+'.rotateX', 88)
  cmds.setAttr(test_cube_name[0]+'.rotateY', 0)
  cmds.setAttr(test_cube_name[0]+'.rotateZ', 0)

  dome_light_shape_name = cmds.directionalLight()
  dome_light_name = getObjectParentNode( dome_light_shape_name )
  dome_light_name = cmds.rename (dome_light_name, "domeTestLight")

  cmds.setAttr( (dome_light_name+'.translateX'), -32)
  cmds.setAttr( (dome_light_name+'.rotateX'), 38)
  cmds.setAttr( (dome_light_name+'.rotateY'), 47)
  cmds.setAttr( (dome_light_name+'.rotateZ'), -62)
Пример #24
0
def defaultLighting():
    """
    Creates the default lighting in the scene
    Useful when there is no lighting in the scene
    """
    # check if lights exist
    if cmds.ls(lt=True):
        return
    # save current selection
    selected = cmds.ls(sl=True, l=True)
    # create and place test light
    lightShape = cmds.directionalLight()
    lightXform = cmds.listRelatives(lightShape, p=True)[0]
    cmds.setAttr("{0}.tx".format(lightXform), 5)
    cmds.setAttr("{0}.ty".format(lightXform), 5)
    cmds.setAttr("{0}.ry".format(lightXform), 90)
    cmds.setAttr("{0}.rz".format(lightXform), 45)
    # activate lights on viewport
    viewport = lib.getActiveModelPanel()
    cmds.modelEditor(viewport, edit=True, displayLights="all")
    # bring back selection
    cmds.select(selected, r=True)
Пример #25
0
def create_arnold_default_light():
    """ Create generic default light for arnold which can not use maya default light """
    cmds.directionalLight(rotation=(45, 30, 15),
                          intensity=0.7,
                          useRayTraceShadows=0)
    cmds.directionalLight(rotation=(240, 45, 45),
                          intensity=0.7,
                          useRayTraceShadows=0)
    cmds.directionalLight(rotation=(-62, 55, 0),
                          intensity=1.0,
                          useRayTraceShadows=1)

    try:
        import mtoa.utils as mutils
        mutils.createLocator("aiSkyDomeLight", asLight=True)
    except Exception as e:
        LOGGER.error('Error creating arnold Sky Dome Light: %s', e)
Пример #26
0
def createLightRig():

    offsetAmount = 20
    lightRotation = 30

    newLight = cmds.spotLight(rgb=(1, 1, 1), name="KeyLight")
    lightTransform = cmds.listRelatives(newLight, parent=True)
    keyLight = lightTransform[0]

    newLight = cmds.spotLight(rgb=(0.8, 0.8, 0.8), name="FillLight")
    lightTransform = cmds.listRelatives(newLight, parent=True)
    fillLight = lightTransform[0]

    newLight = cmds.directionalLight(rgb=(0.2, 0.2, 0.2), name="BackLight")
    lightTransform = cmds.listRelatives(newLight, parent=True)
    backLight = lightTransform[0]

    cmds.move(0, 0, offsetAmount, keyLight)
    cmds.move(0, 0, 0, keyLight + ".rotatePivot")
    cmds.rotate(-lightRotation, lightRotation, 0, keyLight)

    cmds.move(0, 0, offsetAmount, fillLight)
    cmds.move(0, 0, 0, fillLight + ".rotatePivot")
    cmds.rotate(-lightRotation, -lightRotation, 0, fillLight)

    cmds.move(0, 0, offsetAmount, backLight)
    cmds.move(0, 0, 0, backLight + ".rotatePivot")
    cmds.rotate(180 + lightRotation, 0, 0, backLight)

    rigNode = cmds.group(empty=True, name="LightRig")

    cmds.parent(keyLight, rigNode)
    cmds.parent(fillLight, rigNode)
    cmds.parent(backLight, rigNode)

    cmds.select(rigNode, replace=True)
Пример #27
0
def basic(*args):
	if(not cmds.ls('lights')):
			cmds.group(name='lights', em=True, w=True)
	cool = [.8, .85, 1]
	warm = [1, .88, .8]
	north = cmds.directionalLight(n='lFill_fromSouthOnNorth', rgb=cool, i=.2)
	cmds.setAttr(cmds.listRelatives(north,type='transform',p=True)[0] + '.ry', 180)
	south = cmds.directionalLight(n='lFill_fromNorthOnSouth', rgb=cool, i=.2)
	east = cmds.directionalLight(n='lFill_fromWestOnEast', rgb=cool, i=.2)
	cmds.setAttr(cmds.listRelatives(east,type='transform',p=True)[0] + '.ry', 90)
	west = cmds.directionalLight(n='lFill_fromEastOnWest', rgb=cool, i=.2)
	cmds.setAttr(cmds.listRelatives(west,type='transform',p=True)[0] + '.ry', -90)
	sky = cmds.directionalLight(n='lFill_fromFloorOnSky', rgb=warm, i=.1)
	cmds.setAttr(cmds.listRelatives(sky,type='transform',p=True)[0] + '.rx', 90)
	floor = cmds.directionalLight(n='lFill_fromSkyOnFloor', rgb=cool, i=.2)
	cmds.setAttr(cmds.listRelatives(floor,type='transform',p=True)[0] + '.rx', -90)
	amb = cmds.ambientLight(n='lAmb_onSet', i=.01)
	cmds.parent(cmds.ls(type='light'), 'lights')
	refresh()
import math

# ****************************
# ---------- SETUP ----------
# ****************************

# ----- Create Light -----

# Create ambient light

light = cmds.ambientLight(intensity=1.0)
cmds.ambientLight(light, e=True, ss=True, intensity=0.2, n='lightAmb')
cmds.move(0, 8, 0)

# Create directional light
light = cmds.directionalLight(rotation=(45, 30, 15), n='lightDir')
cmds.directionalLight(light, e=True, ss=True, intensity=0.0)

# Query it
cmds.ambientLight(light, q=True, intensity=True)
cmds.directionalLight(light, q=True, intensity=True)

# ----- Create Transparent Box -----

# Create the groundPlane
cmds.polyCube(w=5,
              h=2,
              d=5,
              sx=1,
              sy=1,
              sz=1,
Пример #29
0
def game():
    cmds.file(force=True, new=True)
    #length of playback for game
    cmds.playbackOptions(maxTime='20sec')
    #lights
    cmds.directionalLight()
    cmds.scale(4.910268, 4.910268, 4.910268, r=True)
    cmds.move(17.938379, 12.193473, 0, r=True)
    cmds.rotate(0, 98.271943, 0, r=True, os=True, fo=True)
    cmds.rotate(-23.925408, 0, 0, r=True, os=True, fo=True)
    cmds.move(0, 0, -0.622877, r=True)
    cmds.move(0, 0, -3.289271, r=True)
    cmds.duplicate()
    #// Result: directionalLight2 //
    cmds.move(-20.838684, 0, 0, r=True)
    cmds.rotate(0, 24.509822, 0, r=True, os=True, fo=True)
    cmds.rotate(0, 103.346384, 0, r=True, os=True, fo=True)
    cmds.rotate(-44.285251, 0, 0, r=True, os=True, fo=True)
    cmds.move(-14.586563, 0, 0, r=True)
    cmds.move(0, 0, -5.104265, r=True)
    cmds.move(0, 0, -4.284069, r=True)
    cmds.pointLight()
    cmds.move(0, 0, 5.003762, r=True)
    cmds.move(0, 0, 11.322471, r=True)
    cmds.move(0, 0, 3.520321, r=True)
    cmds.duplicate()
    #// Result: pointLight2 //
    cmds.move(0, 0, -62.281584, r=True)
    cmds.move(0, 0, 20.779332, r=True)
    cmds.setAttr("pointLightShape1.intensity", 0.2)
    #prefix for parts
    pfx = "jenga_"
    #the jenga brick
    cmds.polyCube(d=3, h=0.5, n=pfx + "brick")
    myBlinn = cmds.shadingNode('blinn', asShader=True)
    cmds.select(pfx + "brick")
    cmds.hyperShade(assign=myBlinn)
    cmds.select(cl=True)
    cmds.hyperShade(objects=myBlinn)
    cmds.setAttr("blinn1.color", 0.243, 0.155, 0.101, type="double3")
    cmds.setAttr("blinn1.ambientColor", 1, 1, 1, type="double3")
    # create a new MASH network with grid distribution
    mashNetwork = mapi.Network()
    mashNetwork.createNetwork(name=pfx + "tower",
                              distributionStyle=6,
                              geometry="Repro")
    #adjust the distribution
    cmds.setAttr(mashNetwork.distribute + ".gridz", 1)
    cmds.setAttr(mashNetwork.distribute + ".gridx", 3)
    cmds.setAttr(mashNetwork.distribute + ".gridy", 1)
    cmds.setAttr(mashNetwork.distribute + ".gridAmplitudeZ", 0)
    cmds.setAttr(mashNetwork.distribute + ".gridAmplitudeY", 0)
    cmds.setAttr(mashNetwork.distribute + ".gridAmplitudeX", 2.05)
    # add a Replicator node
    rep = mashNetwork.addNode("MASH_Replicator")
    # add a Dyanmics node
    dyn = mashNetwork.addNode("MASH_Dynamics")
    # add a Python node
    py = mashNetwork.addNode("MASH_Python")
    #adjust the Replicator settings to make a tower
    cmds.setAttr(pfx + "tower_Replicator.replicants", 17)
    cmds.setAttr(pfx + "tower_Replicator.offsetPositionY", 0.5)
    cmds.setAttr(pfx + "tower_Replicator.offsetPositionX", 0)
    cmds.setAttr(pfx + "tower_Replicator.offsetPositionZ", 0)
    cmds.setAttr(pfx + "tower_Replicator.rotatePointsY", 1530)
    #ajust the bullet solver ground plane
    cmds.setAttr(pfx + "tower_BulletSolverShape.groundPlanePositionY", -0.25)
    #ajust the Dynamics settings
    cmds.setAttr(pfx + "tower_Dynamics.friction", 1)
    #add the python code
    cmds.polyCube(n=pfx + "test")
Пример #30
0
    def Light_Import_BTN_Fun(self):
        File_Path = QFileDialog.getOpenFileName(self,
                                                caption=u"保存文件到",
                                                directory=".",
                                                filter="json (*.json)")
        # Note 空数组处理
        try:
            if type(File_Path) is tuple:
                File_Path = File_Path[0]
            if type(File_Path) is list:
                File_Path = File_Path[0]
        except:
            traceback.print_exc()
            return

        if not os.path.exists(File_Path):
            return

        Light_Json = {}
        with open(File_Path, 'r') as f:
            Light_Json = json.load(f)

        for lightName in Light_Json['LightData']:

            if cmds.objExists(lightName):
                continue

            lightNameData = Light_Json['LightData'][lightName]

            # Note 检查灯光的类型
            if lightNameData['Type'] == "pointLight":
                light = cmds.pointLight(n=lightName)
            elif lightNameData['Type'] == "spotLight":
                light = cmds.spotLight(n=lightName)
                cmds.setAttr(light + ".coneAngle", lightNameData['coneAngle'])
                cmds.setAttr(light + ".penumbraAngle",
                             lightNameData['penumbraAngle'])
                cmds.setAttr(light + ".dropoff", lightNameData['dropoff'])
            elif lightNameData['Type'] == "areaLight":
                light = cmds.shadingNode('areaLight',
                                         asLight=1,
                                         n=lightNameData['Name'])
            elif lightNameData['Type'] == "directionalLight":
                light = cmds.directionalLight(n=lightName)
            elif lightNameData['Type'] == "aiSkyDomeLight":
                try:
                    aiLight = mtoa.utils.createLocatorWithName(
                        "aiSkyDomeLight", lightName, asLight=True)
                except:
                    print "fail to build the aiSkyDomeLight - skip this light"
                    continue
                cmds.rename(aiLight[0], lightNameData['Name'])
            elif lightNameData['Type'] == "aiAreaLight":
                try:
                    aiLight = mtoa.utils.createLocatorWithName("aiAreaLight",
                                                               lightName,
                                                               asLight=True)
                except:
                    print "fail to build the aiAreaLight - skip this light"
                    continue
                cmds.rename(aiLight[0], lightNameData['Name'])

            R = lightNameData['color']['R']
            G = lightNameData['color']['G']
            B = lightNameData['color']['B']
            cmds.setAttr(lightNameData['Name'] + ".color",
                         R,
                         G,
                         B,
                         type="double3")

            cmds.setAttr(lightNameData['Name'] + ".intensity",
                         lightNameData['Intensity'])
            cmds.setAttr(lightNameData['Name'] + ".aiExposure",
                         lightNameData['Exposure'])

            tx = lightNameData['Translate']['tx']
            ty = lightNameData['Translate']['ty']
            tz = lightNameData['Translate']['tz']
            cmds.setAttr(lightName + ".tx", tx)
            cmds.setAttr(lightName + ".ty", ty)
            cmds.setAttr(lightName + ".tz", tz)

            rx = lightNameData['Rotate']['rx']
            ry = lightNameData['Rotate']['ry']
            rz = lightNameData['Rotate']['rz']
            cmds.setAttr(lightName + ".rx", rx)
            cmds.setAttr(lightName + ".ry", ry)
            cmds.setAttr(lightName + ".rz", rz)

            sx = lightNameData['Scale']['sx']
            sy = lightNameData['Scale']['sy']
            sz = lightNameData['Scale']['sz']
            cmds.setAttr(lightName + ".sx", sx)
            cmds.setAttr(lightName + ".sy", sy)
            cmds.setAttr(lightName + ".sz", sz)

        QMessageBox.warning(self, u"Success", u"Json Import Success!")
        self.Save_Json_Fun()
Пример #31
0
	def create(self):
		
		print ("asset path: ", self.assetspath)

		blankdocument = self.assetspath+'/MayaProject.ma'
		
		print ("Document path: ", blankdocument)

		# Open your file
		self.render_file = cmds.file(blankdocument, o=True)

		cmds.file(new=True,f=True)
		cmds.file(rn=blankdocument)
		
		# Open Shot List
		views = []
		newviews = []		

		# Placeholder Object
		cmds.polyCube(n='placeholder')
		cmds.group('placeholder',n='ProductGroup')
		cmds.move(0,1,0)
		cmds.select('placeholder')
		cmds.CenterPivot('placeholder')

		# Import OBJ from Agisoft
		ModelPath = self.assetspath+'/output/model.obj'
		cmds.file(ModelPath, i=True)
		cmds.select('Mesh')
		cmds.CenterPivot('Mesh')
		cmds.select('Mesh','placeholder')
		cmds.align(x='mid',y='mid',z='mid',alignToLead=True)
		cmds.group('Mesh',p='ProductGroup')

		# Delete Placeholder
		cmds.delete('placeholder')
		
		# Key Model Positions
		with open(self.assetspath+'/shotListConfig.txt') as inf:
			  		
			# Identify all elements in view column		
			for line in inf:
				parts = line.split() 
				if len(parts) > 1:   
					s = parts[3]
					views.append(s)
					
			# replace tqt elements with angle 
			for idx, item in enumerate(views):
				if item == 'tqt':
					views[idx] = '0_45_0'
					print (views)  			
					
			# Remove the header line		
			views.pop(0)
			
			# Replace _ with , for each element
			angles = ([view.replace('_', ',') for view in views])
			
			# Remove Duplicates
			for i in angles:
				if i not in newviews:
					newviews.append(i)
							
			# Define Frames
			frame = 0
			view = []
			
			# Assign X, Y & Z values from the first 3 elements 
			for view in newviews:
				viewsplit = view.split(",")
				x = viewsplit[0]
				y = viewsplit[1]
				z = viewsplit[2]
				
				# Move frame forward one
				frame += 1
				# Print New Frame
				print (frame)
				
				# Set Key Frame with new X,Y & Z values on new time frame
				cmds.rotate( x, y, z, 'ProductGroup' )
				cmds.setKeyframe('ProductGroup',time=frame)
				
				# Print X,Y & Z Values
				print ("x= " + x)
				print ("y= " + y)
				print ("z= " + z)		

		# Create Lights
		cmds.directionalLight(n='key',intensity=.2,rs=True)
		cmds.rotate(-45,-45,0)
		cmds.scale(10,10,10)
		cmds.setAttr("keyShape.lightAngle",5)
		cmds.setAttr("keyShape.shadowRays",15)

		# Create Camera 
		cam = cmds.camera(n='maincamera',ff='vertical')
		cmds.move(0,1,12)
		width = 512
		height = 512
		cmds.setAttr( 'defaultResolution.deviceAspectRatio', ( ( width ) / ( height ) ) )
		cmds.setAttr('maincameraShape2.backgroundColor',1,1,1)
		cmds.setAttr('maincameraShape2.focalLength', 85)

		# Group Scene
		cmds.group('maincamera1','key', n='Scene')

		# Group ALL
		cmds.group('Scene','ProductGroup',n='ALL')

		# Save File
		cmds.file(rename=self.render_file)
		cmds.file( save=True, type='mayaAscii' )
def playblastTurntableGenerator():

    model = cmds.ls(sl=True, l=True)

    if len(model) < 1:
        cmds.warning('Nothing is selected. Select at least 1 object/group.')
    else:
        scaleFactor = getSceneBBoxScale(model)
        modelCenter = getSceneBBoxCenter(model)
        '''
		Create lightRig
		'''
        namespaces = cmds.namespaceInfo(':', listOnlyNamespaces=True, r=True)
        if 'turntableSet' in namespaces:
            cmds.namespace(setNamespace=':')
            cmds.namespace(deleteNamespaceContent=True,
                           removeNamespace='turntableSet')

        turntableSetNamespace = 'turntableSet'
        cmds.namespace(add=turntableSetNamespace)

        turntableSetGroupName = turntableSetNamespace + ':' + turntableSetNamespace + '_GRP'
        cmds.group(em=True, name=turntableSetGroupName)
        lightGroupName = (turntableSetNamespace + ':lights_GRP')
        cmds.group(em=True, name=lightGroupName)
        cmds.parent(lightGroupName, turntableSetGroupName)

        spotLight01 = 'turntableSpotLight01'
        cmds.spotLight(n=turntableSetNamespace + ':' + spotLight01,
                       coneAngle=70,
                       intensity=1.065,
                       penumbra=7.5,
                       dropOff=15)
        cmds.setAttr(
            turntableSetNamespace + ':' + spotLight01 + '.useDepthMapShadows',
            1)
        cmds.setAttr(
            turntableSetNamespace + ':' + spotLight01 + '.dmapResolution',
            4096)
        cmds.setAttr(
            turntableSetNamespace + ':' + spotLight01 + '.dmapFilterSize', 10)
        cmds.setAttr(turntableSetNamespace + ':' + spotLight01 +
                     '.shadowColor',
                     0.213,
                     0.213,
                     0.213,
                     type='double3')
        cmds.xform(turntableSetNamespace + ':' + spotLight01,
                   t=(10.68561, 10.28704, 13.95764),
                   ro=(-27.66044, 32.98632, 0),
                   ws=True)
        cmds.parent(turntableSetNamespace + ':' + spotLight01, lightGroupName)

        spotLight02 = 'turntableSpotLight02'
        cmds.spotLight(n=turntableSetNamespace + ':' + spotLight02,
                       coneAngle=45,
                       intensity=0.4,
                       penumbra=7.5,
                       dropOff=5)
        cmds.setAttr(turntableSetNamespace + ':' + spotLight02 +
                     '.shadowColor',
                     1,
                     1,
                     1,
                     type='double3')
        cmds.xform(turntableSetNamespace + ':' + spotLight02,
                   t=(-10.43612, 8.78771, -5.27289),
                   ro=(-217.39926, -65.2236, -180),
                   ws=True)
        cmds.parent(turntableSetNamespace + ':' + spotLight02, lightGroupName)

        directionalLight01 = 'turntableDirect01'
        cmds.directionalLight(n=turntableSetNamespace + ':' +
                              directionalLight01,
                              intensity=0.3,
                              rotation=[-47.78754, 0, 0])
        cmds.setAttr(turntableSetNamespace + ':' + directionalLight01 +
                     '.shadowColor',
                     1,
                     1,
                     1,
                     type='double3')
        cmds.parent(turntableSetNamespace + ':' + directionalLight01,
                    lightGroupName)

        cycloGeoCreation('turntableSet', 'defaultGrey_C_cycloA_GES')
        cmds.parent(turntableSetNamespace + ':defaultGrey_C_cycloA_GES',
                    turntableSetGroupName)
        '''
		Adjust Rig Scale and Pos
		'''

        cmds.xform(turntableSetGroupName,
                   absolute=True,
                   translation=[
                       modelCenter[0],
                       cmds.exactWorldBoundingBox(model,
                                                  ignoreInvisible=True)[1],
                       modelCenter[2]
                   ],
                   ws=True)
        cmds.scale(scaleFactor,
                   scaleFactor,
                   scaleFactor,
                   turntableSetGroupName,
                   absolute=True)
        '''
		Create and Assign shaders
		'''

        createAndAssignShaders(turntableSetNamespace, model)
        '''
		Create Camera
		'''
        cameraName = turntableSetNamespace + ':' + 'turntableCameraA_CAM'
        cam = cmds.camera()
        cmds.rename(cam[0], cameraName)
        cmds.setAttr(cameraName + '.focalLength', 50)
        cmds.setAttr(cameraName + '.displayGateMaskColor',
                     0,
                     0,
                     0,
                     type='double3')
        cmds.setAttr(cameraName + '.displayGateMaskOpacity', 1)
        cmds.xform(cameraName,
                   absolute=True,
                   translation=[0, modelCenter[1] * 1.5, scaleFactor * 12],
                   ws=True)

        cameraAimLocatorName = turntableSetNamespace + ':cameraAim_CTRL'
        cmds.spaceLocator(n=cameraAimLocatorName)
        cmds.aimConstraint(cameraAimLocatorName,
                           cameraName,
                           n=turntableSetNamespace + ':cameraAimConstraint')
        cmds.setAttr(turntableSetNamespace + ':cameraAimConstraint.offsetY',
                     -90)
        cmds.xform(cameraAimLocatorName,
                   absolute=True,
                   translation=modelCenter,
                   ws=True)

        mel.eval('setNamedPanelLayout("Single Perspective View")')
        cmds.lookThru(cameraName)

        cmds.parent(cameraName, turntableSetGroupName)
        cmds.parent(cameraAimLocatorName, turntableSetGroupName)
        '''
		Create Turntable Locator
		'''
        locName = turntableSetNamespace + ':turntableLocatorA_LOC'
        cmds.spaceLocator(n=locName)
        cmds.xform(locName,
                   absolute=True,
                   translation=[modelCenter[0], 0, modelCenter[2]],
                   ws=True)
        cmds.parent(locName, turntableSetGroupName)
        cmds.parentConstraint(locName,
                              model,
                              maintainOffset=True,
                              n=turntableSetNamespace +
                              ':parentConstraint_CTR')
        '''
		Turntable Animation
		'''
        setSpinAnim(locName, 1, 101)
        #setSpinAnim(lightGroupName, 101, 201)
        #setSpinAnim(lightGroupName, 101, 201)
        #setSpinAnim(lightGroupName, 101, 201)
        '''
		Time Settings
		'''
        startFrame = 1
        endFrame = 100

        cmds.playbackOptions(ast=startFrame, e=True)
        cmds.playbackOptions(aet=endFrame, e=True)
        cmds.playbackOptions(min=startFrame, e=True)
        cmds.playbackOptions(max=endFrame, e=True)
        '''
		Viewport Settings
		'''
        panel = getPanelFromCamera(turntableSetNamespace +
                                   ':turntableCameraA_CAMShape')[0]

        cmds.modelEditor(panel, e=True, displayAppearance='smoothShaded')
        cmds.modelEditor(panel, e=True, dl='all')
        cmds.modelEditor(panel, e=True, shadows=1)
        cmds.modelEditor(panel, e=True, allObjects=0)
        cmds.modelEditor(panel, e=True, polymeshes=1)
        cmds.modelEditor(panel, e=True, grid=0)
        cmds.setAttr("hardwareRenderingGlobals.ssaoEnable", 1)
        cmds.setAttr("hardwareRenderingGlobals.multiSampleEnable", 1)

        activateSmoothPreview(model)
        '''
		 Render Settings
		'''

        cmds.setAttr("defaultResolution.width", 1920)
        cmds.setAttr("defaultResolution.height", 1080)
Пример #33
0
def run_script(num_shield_pieces=50):
    RED = [1, 0, 0]  #red blood cells
    BLUE = [0, 0, 1]  #blue for the core, aka Sonic
    DARK_RED = [.545, 0, 0]

    #create the lighting for the scene
    main_light = cmds.directionalLight(name="main_light", intensity=5)
    cmds.move(-5.711, 14.564, 11.097, "main_light")
    cmds.rotate('-67.367deg', '-24.33deg', '54.557deg', "main_light")

    #create the shape of the core and the shield
    shield_shape = cmds.polyTorus(sr=0.2, name="myRing#")  #shape of shield
    shield_center = cmds.polyPlatonicSolid(radius=2.55, st=1, name="core")
    applyMaterial(shield_center[0], DARK_RED, 'lambert')
    cmds.move(0, 9, 0, "core")  #move the core higher

    #add decorative cylinder to core
    core_piece_1 = cmds.polyCylinder(name="tube_1")
    applyMaterial(core_piece_1[0], BLUE, 'lambert')
    cmds.move(0.195, 11.014, -1.221, "tube_1")
    cmds.rotate('-30.351deg', 0, 0, "tube_1")
    cmds.scale(0.505, 0.619, 0.505, "tube_1")

    #add another decorative cylinder to core
    core_piece_2 = cmds.polyCylinder(name="tube_2")
    applyMaterial(core_piece_2[0], RED, 'lambert')
    cmds.move(-0.917, 11.185, -0.216, "tube_2")
    cmds.rotate('-3.436deg', '14.201deg', '24.834deg', "tube_2")
    cmds.scale(0.505, 0.619, 0.505, "tube_2")

    #generate random shield fragments
    shield_pieces, shield_pieces_group = generate_shield(
        shield_shape, num_shield_pieces)

    #coloring the shield pieces
    for piece_obj in shield_pieces:
        applyMaterial(piece_obj[0], RED, 'phong')

    #aim fragments at core
    aim_at_first(shield_center, shield_pieces)

    #create and link expansion attribute
    locator_group = expand_from_first(shield_center, shield_pieces)

    #must group locators so they can be rotated with the fragments
    cmds.parent(locator_group, shield_pieces_group)

    startTime = cmds.playbackOptions(query=True, minTime=True)
    endTime = cmds.playbackOptions(query=True, maxTime=True)

    #second param is rotation param
    key_rotation(shield_pieces_group, 'rotateY', startTime, endTime)

    #create heartbeat animation pattern
    cmds.cutKey(shield_center,
                time=(startTime, endTime),
                attribute='expansion')
    heartbeat(shield_center, 0)
    heartbeat(shield_center, 2)
    heartbeat(shield_center, 4)
    heartbeat(shield_center, 6)
    heartbeat(shield_center, 8)
    heartbeat(shield_center, 10)
    cmds.selectKey(shield_center,
                   time=(startTime, endTime),
                   attribute='expansion',
                   keyframe=True)
    cmds.keyTangent(inTangentType='linear', outTangentType='linear')
Пример #34
0
def softFill():
    controls = ( 'tx', 'ty', 'tz',
                 'rx', 'ry', 'rz',
                 'sx', 'sy', 'sz', 'v' )
    
    lightAttr = ( 'color', 'dmapBias', 'dmapFilterSize', 
                  'dmapResolution', 'emitSpecular', 'shadowColor',
                  'shadowRays', 'useDepthMapShadows', 'useRayTraceShadows')
    
    lights = []
    
    # Create group
    softFill = cmds.group(em=True, name='softFill#')
    
    # Create and set group attributes
    cmds.addAttr( softFill, longName='color', attributeType='float3', usedAsColor=True )
    cmds.addAttr( softFill, longName='red', attributeType='float', defaultValue=1, parent='color' )
    cmds.addAttr( softFill, longName='green', attributeType='float', defaultValue=1, parent='color' )
    cmds.addAttr( softFill, longName='blue', attributeType='float', defaultValue=1, parent='color' )

    cmds.addAttr( softFill, longName='intensity', attributeType='float', defaultValue=1, softMinValue=0, softMaxValue=10 )
    cmds.addAttr( softFill, longName='lightAngle', attributeType='float', defaultValue=5, minValue=0, maxValue=90 )
    cmds.addAttr( softFill, longName='emitSpecular', attributeType='bool' )

    cmds.addAttr( softFill, longName='shadowColor', attributeType='float3', usedAsColor=True )
    cmds.addAttr( softFill, longName='redShadow', attributeType='float', parent='shadowColor' )
    cmds.addAttr( softFill, longName='greenShadow', attributeType='float', parent='shadowColor' )
    cmds.addAttr( softFill, longName='blueShadow', attributeType='float', parent='shadowColor' )

    cmds.addAttr( softFill, longName='shadows', attributeType='enum', enumName='None:Depth Map:Ray Trace' )
    cmds.addAttr( softFill, longName='dmapResolution', attributeType='short', defaultValue=512, minValue=16, maxValue=8192 )
    cmds.addAttr( softFill, longName='dmapFilterSize', attributeType='short', defaultValue=.001, softMinValue=0, softMaxValue=5 )
    cmds.addAttr( softFill, longName='dmapBias', attributeType='float', defaultValue=.001, softMinValue=.001, softMaxValue=1 )
    cmds.addAttr( softFill, longName='shadowRays', attributeType='short', defaultValue=1, softMinValue=1, softMaxValue=40 )

    cmds.addAttr( softFill, longName='useDepthMapShadows', attributeType='bool', hidden=True)
    cmds.addAttr( softFill, longName='useRayTraceShadows', attributeType='bool', hidden=True)
    
    cmds.setAttr( (softFill + '.displayHandle'), 1 )
    
    # Setup enum value mapping
    cmds.setDrivenKeyframe( (softFill + '.useDepthMapShadows'), currentDriver=(softFill + '.shadows'), 
                             inTangentType='spline', outTangentType='spline' )
    cmds.setDrivenKeyframe( (softFill + '.useDepthMapShadows'), currentDriver=(softFill + '.shadows'), 
                             inTangentType='spline', outTangentType='spline',
                             driverValue=1, value=1 )
    cmds.setDrivenKeyframe( (softFill + '.useDepthMapShadows'), currentDriver=(softFill + '.shadows'), 
                             inTangentType='spline', outTangentType='spline',
                             driverValue=2 )

    cmds.setDrivenKeyframe( (softFill + '.useRayTraceShadows'), currentDriver=(softFill + '.shadows'), 
                             inTangentType='spline', outTangentType='spline' )
    cmds.setDrivenKeyframe( (softFill + '.useRayTraceShadows'), currentDriver=(softFill + '.shadows'), 
                             inTangentType='spline', outTangentType='spline',
                             driverValue=1 )
    cmds.setDrivenKeyframe( (softFill + '.useRayTraceShadows'), currentDriver=(softFill + '.shadows'), 
                             inTangentType='spline', outTangentType='spline',
                             driverValue=2, value=1 )

    # Create and connect utility nodes
    # MD Intensity
    softFillIntensity = cmds.shadingNode( 'multiplyDivide', asUtility=True, name=(softFill + '_mdIntensity') )
    cmds.setAttr( (softFillIntensity + ".operation"), 2 )
    cmds.setAttr( (softFillIntensity + ".input1X"), 1 )
    cmds.setAttr( (softFillIntensity + ".input2X"), 5 )
    cmds.connectAttr( (softFill + '.intensity'), (softFillIntensity + '.input1X') )
    
    # MD Light Angle
    softFillLightAngle = cmds.shadingNode( 'multiplyDivide', asUtility=True, name=(softFill + '_mdLightAngle') )
    cmds.setAttr ( (softFillLightAngle + '.input1X'), 5 )
    cmds.setAttr ( (softFillLightAngle + '.input1Y'), 5 )
    cmds.setAttr ( (softFillLightAngle + '.input2Y'), -1 )
    cmds.connectAttr( (softFill + '.lightAngle'), (softFillLightAngle + '.input1X') )
    cmds.connectAttr( (softFill + '.lightAngle'), (softFillLightAngle + '.input1Y') )
    
    # Save directional light names
    softFillName = softFill + '_light'
    
    # Create directional lights
    for i in range(1,6):
        light = cmds.directionalLight( name=(softFillName + str(i)) )
        lights.append(light)
    
    # Add directional lights to group
    cmds.group( lights, useAsGroup=softFill )
    
    # Connect light angle utility node to lights' rotations
    cmds.connectAttr( (softFillLightAngle + '.outputX'), (softFillName + '2.rotateX') )
    cmds.connectAttr( (softFillLightAngle + '.outputY'), (softFillName + '3.rotateX') )
    cmds.connectAttr( (softFillLightAngle + '.outputY'), (softFillName + '4.rotateY') )
    cmds.connectAttr( (softFillLightAngle + '.outputX'), (softFillName + '5.rotateY') )
    
    # Connect utility node output to light intensity
    for i in range(0,5):
        cmds.connectAttr( (softFillIntensity + '.outputX'), (lights[i] + '.intensity') )
        for control in controls:
            if control != 'rx' and control != 'ry':
                cmds.setAttr( (softFillName + str(i+1) + '.' + control), lock=True )
        
        # Connect light attributes
        for attr in lightAttr:
            cmds.connectAttr( (softFill + '.' + attr), (lights[i] + '.' + attr) )
Пример #35
0
    def create(self):

        print("asset path: ", self.assetspath)

        blankdocument = self.assetspath + '/MayaProject.ma'

        print("Document path: ", blankdocument)

        # Open your file
        self.render_file = cmds.file(blankdocument, o=True)

        cmds.file(new=True, f=True)
        cmds.file(rn=blankdocument)

        # Open Shot List
        views = []
        newviews = []

        # Placeholder Object
        cmds.polyCube(n='placeholder')
        cmds.group('placeholder', n='ProductGroup')
        cmds.move(0, 1, 0)
        cmds.select('placeholder')
        cmds.CenterPivot('placeholder')

        # Import OBJ from Agisoft
        ModelPath = self.assetspath + '/output/model.obj'
        cmds.file(ModelPath, i=True)
        cmds.select('Mesh')
        cmds.CenterPivot('Mesh')
        cmds.select('Mesh', 'placeholder')
        cmds.align(x='mid', y='mid', z='mid', alignToLead=True)
        cmds.group('Mesh', p='ProductGroup')

        # Delete Placeholder
        cmds.delete('placeholder')

        # Key Model Positions
        with open(self.assetspath + '/shotListConfig.txt') as inf:

            # Identify all elements in view column
            for line in inf:
                parts = line.split()
                if len(parts) > 1:
                    s = parts[3]
                    views.append(s)

            # replace tqt elements with angle
            for idx, item in enumerate(views):
                if item == 'tqt':
                    views[idx] = '0_45_0'
                    print(views)

            # Remove the header line
            views.pop(0)

            # Replace _ with , for each element
            angles = ([view.replace('_', ',') for view in views])

            # Remove Duplicates
            for i in angles:
                if i not in newviews:
                    newviews.append(i)

            # Define Frames
            frame = 0
            view = []

            # Assign X, Y & Z values from the first 3 elements
            for view in newviews:
                viewsplit = view.split(",")
                x = viewsplit[0]
                y = viewsplit[1]
                z = viewsplit[2]

                # Move frame forward one
                frame += 1
                # Print New Frame
                print(frame)

                # Set Key Frame with new X,Y & Z values on new time frame
                cmds.rotate(x, y, z, 'ProductGroup')
                cmds.setKeyframe('ProductGroup', time=frame)

                # Print X,Y & Z Values
                print("x= " + x)
                print("y= " + y)
                print("z= " + z)

        # Create Lights
        cmds.directionalLight(n='key', intensity=.2, rs=True)
        cmds.rotate(-45, -45, 0)
        cmds.scale(10, 10, 10)
        cmds.setAttr("keyShape.lightAngle", 5)
        cmds.setAttr("keyShape.shadowRays", 15)

        # Create Camera
        cam = cmds.camera(n='maincamera', ff='vertical')
        cmds.move(0, 1, 12)
        width = 512
        height = 512
        cmds.setAttr('defaultResolution.deviceAspectRatio',
                     ((width) / (height)))
        cmds.setAttr('maincameraShape2.backgroundColor', 1, 1, 1)
        cmds.setAttr('maincameraShape2.focalLength', 85)

        # Group Scene
        cmds.group('maincamera1', 'key', n='Scene')

        # Group ALL
        cmds.group('Scene', 'ProductGroup', n='ALL')

        # Save File
        cmds.file(rename=self.render_file)
        cmds.file(save=True, type='mayaAscii')
Пример #36
0
def create_directional_light():
    mc.directionalLight()
Пример #37
0
 def button_sun_onClicked(self):
     if cmds.objExists("sun"):
         print "Sun already exist"
     else:
         cmds.directionalLight(name="sun")
         cmds.parent("sun", "Studio")
    def Light_Import_Fn(self):
        File_Path = QFileDialog.getOpenFileName(self,
                                                caption=u"保存文件到",
                                                directory=".",
                                                filter="json (*.json)")
        # 空数组处理
        try:
            if type(File_Path) is tuple:
                File_Path = File_Path[0]
            if type(File_Path) is list:
                File_Path = File_Path[0]
        except:
            traceback.print_exc()
            return

        if not os.path.exists(File_Path):
            return

        Light_Json = {}
        with open(File_Path, 'r') as f:
            Light_Json = json.load(f)

        for lightName in Light_Json['LightData']:
            lightNameData = Light_Json['LightData'][lightName]

            if lightNameData['Type'] == "pointLight":
                light = cmds.pointLight(n=lightName)
            elif lightNameData['Type'] == "spotLight":
                light = cmds.spotLight(n=lightName)
                cmds.setAttr(light + ".coneAngle", lightNameData['coneAngle'])
                cmds.setAttr(light + ".penumbraAngle",
                             lightNameData['penumbraAngle'])
                cmds.setAttr(light + ".dropoff", lightNameData['dropoff'])
            elif lightNameData['Type'] == "areaLight":
                light = cmds.shadingNode('areaLight',
                                         asLight=1,
                                         n=lightNameData['Name'])
                # cmds.rename(light,lightNameData['Name'])
                # light = lightNameData['Name']
            elif lightNameData['Type'] == "directionalLight":
                light = cmds.directionalLight(n=lightName)
            elif lightNameData['Type'] == "aiSkyDomeLight":
                aiLight = mtoa.utils.createLocatorWithName(
                    "aiSkyDomeLight", lightNameData['Name'], asLight=True)
                cmds.rename(aiLight[1], lightName)
            elif lightNameData['Type'] == "aiAreaLight1":
                aiLight = mtoa.utils.createLocatorWithName(
                    "aiAreaLight", lightNameData['Name'], asLight=True)
                cmds.rename(aiLight[1], lightName)

            R = lightNameData['color']['R']
            G = lightNameData['color']['G']
            B = lightNameData['color']['B']
            try:
                cmds.setAttr(lightNameData['Name'] + ".color",
                             R,
                             G,
                             B,
                             type="double3")
            except:
                print light

            cmds.setAttr(lightNameData['Name'] + ".intensity",
                         lightNameData['Intensity'])
            cmds.setAttr(lightNameData['Name'] + ".aiExposure",
                         lightNameData['Exposure'])

            tx = lightNameData['Translate']['tx']
            ty = lightNameData['Translate']['ty']
            tz = lightNameData['Translate']['tz']
            cmds.setAttr(lightName + ".tx", tx)
            cmds.setAttr(lightName + ".ty", ty)
            cmds.setAttr(lightName + ".tz", tz)

            rx = lightNameData['Rotate']['rx']
            ry = lightNameData['Rotate']['ry']
            rz = lightNameData['Rotate']['rz']
            cmds.setAttr(lightName + ".rx", rx)
            cmds.setAttr(lightName + ".ry", ry)
            cmds.setAttr(lightName + ".rz", rz)

            sx = lightNameData['Scale']['sx']
            sy = lightNameData['Scale']['sy']
            sz = lightNameData['Scale']['sz']
            cmds.setAttr(lightName + ".sx", sx)
            cmds.setAttr(lightName + ".sy", sy)
            cmds.setAttr(lightName + ".sz", sz)
Пример #39
0
def _createLights( domeRig, isSpot, numLights, numArcs, radius ):
    lights = []
    
    # Calculate light angle in arc
    if numLights < 5:
        a = 90.0 / (numLights + 1)
        start = 1
        end = numLights + 1
    else:
        a = 90.0 / (numLights - 1)
        start = 0
        end = numLights

    # Create and position lights in a single arc
    for t in range(start,end):
        if numLights < 5: n = t
        else: n = t + 1
        
        # Create Light
        domeLightName = (domeRig + '_light' + str(n))

        if isSpot: domeLight = cmds.spotLight( name=domeLightName )
        else:      domeLight = cmds.directionalLight( name=domeLightName )

        # Calculate position
        tx = radius * math.cos(math.radians(a*t))
        ty = radius * math.sin(math.radians(a*t))

        # Set position
        cmds.setAttr((domeLightName + '.translateX'), tx)
        cmds.setAttr((domeLightName + '.translateY'), ty)

        lights.append(domeLight)

    a = 360.0 / numArcs

    # Add lights to group
    cmds.group( lights, useAsGroup=domeRig )

    lightArcs = OrderedDict()

    for i in range(1,numArcs):
        # Duplicate Light Arc
        arcLights = cmds.duplicate( domeRig, renameChildren=True )

        # Set rig pivot to origin
        _centerPivot( arcLights[0] )

        # Rotate the group
        cmds.setAttr((arcLights[0] + '.rotateY'), a*i)

        # Remove the group from the duplicated arc
        grp = arcLights.pop(0)

        # Add lights to light arc dictionary
        lightArcs.update({grp:arcLights})

    for grp in lightArcs:
        for l in lightArcs[grp]:
            # Parent all the lights into the original group
            cmds.parent( l, domeRig )
            chld = cmds.listRelatives(l, children=True)
            lights.append( chld[0] )

        # Delete duplicated group
        cmds.delete(grp)

    # Set rig pivot to origin
    _centerPivot( domeRig )

    return lights