import maya.OpenMaya as om
import maya.cmds as cmd
import maya.mel as mel
import maya.OpenMayaUI as omui
import sys
import os
from math import *



def diamantModelingWindow():	
    
    if cmd.window('dToolsModelingUI', ex = True):
        cmd.deleteUI('dToolsModelingUI')
        
    diamantModelingToolUI()
        

class diamantModelingToolUI():        
    def __init__(self):
        
        self.mainWindowUI = cmd.window('dToolsModelingUI', w = 400, h = 42, menuBar = False, title = 'DTools Modeling Companion')        
	
	#create widgets        
	self.CreateModelingWidgets()	
	
	allowedAreas = ['top', 'bottom']
	if cmd.dockControl('dToolsModelingDockUI', ex = True):
	    cmd.deleteUI('dToolsModelingDockUI')
	    
	cmd.dockControl('dToolsModelingDockUI', w = 400, h = 42, l = 'DTools Modeling Companion', ann = 'dTools Companion', area='top', content = self.mainWindowUI, allowedArea = allowedAreas )
	
        #cmd.showWindow( self.mainWindowUI )


    def CreateModelingWidgets(self):
	
	self.mainScrollLayout = cmd.scrollLayout(w = 400, h = 42, horizontalScrollBarThickness=16, verticalScrollBarThickness=16, parent = self.mainWindowUI)	
	
        #self.mainModelingFormLayout = cmd.formLayout( parent = self.mainScrollLayout ) 
	cmd.rowLayout( numberOfColumns=40, columnWidth3=(80, 75, 150), columnAlign=(1, 'right'), columnAttach=[(1, 'both', 0)] )
        
        #create widgets	
	cmd.text( label='  ESmooth: ' )
	ESmoothButton = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='eSmooth.png', ann = 'ESmooth', rpt = True, c = self.ESmooth )
	ESmoothRemoveButton = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='eSmoothRemove.png', ann = 'Remove ESmooth', rpt = True, c = self.RemoveESmooth)
	#cmd.text( label='  Tightness: ' )
	self.mTightOptionMenu = cmd.optionMenu(label='  Tightness')
	cmd.menuItem( label='Low' )
	cmd.menuItem( label='Med' )
	cmd.menuItem( label='High' )
	cmd.optionMenu(self.mTightOptionMenu, e = True, sl = 2 )
	
	#self.mESmoothIF = cmd.intField( minValue=-1, maxValue=3, step=1, v = 2, w = 40 )
	
	
	cmd.image( w = 19, h = 32, image = 'modelUISpacer.png')
	
	cmd.text( label='Maya Smooth: ' )	
	mSmoothButton = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='mSmooth.png', ann = 'mSmooth', rpt = True, c = self.SmoothMayaObject)
	mSmoothRemoveButton = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='mSmoothRemove.png', ann = 'Remove mSmooth', rpt = True, c = self.RemoveMayaSmooth)
	cmd.text( label='  Divisions: ' )
	self.mSmoothIF = cmd.intField( minValue=-1, maxValue=6, step=1, v = 2, w = 40 )
        
        cmd.image( w = 19, h = 32, image = 'modelUISpacer.png')
	
        cmd.text( label='Lock Axis: ' )
	self.xStraightenCB = cmd.checkBox(label = 'X', align = 'left', v = 0)
	self.yStraightenCB = cmd.checkBox(label = 'Y', align = 'left', v = 0)
	self.zStraightenCB = cmd.checkBox(label = 'Z', align = 'left', v = 0)	
	straightenButton = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='straighten.png', ann = 'Straighten Components', rpt = True, c = self.StraightenEdgesVerts )
	
	cmd.image( w = 19, h = 32, image = 'modelUISpacer.png')	
	
	self.dupDirectionRB = cmd.radioCollection()
	self.xDirectionDupRB = cmd.radioButton(sl = 1, label = '-X')
	self.yDirectionDupRB = cmd.radioButton(label = '-Y')
	self.zDirectionDupRB = cmd.radioButton(label = '-Z')
	self.noDirectionDupRB = cmd.radioButton(label = 'None')
	dupFaceButton = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='duplicateFace.png', ann = 'Duplicate Face', rpt = True, c = self.DuplicateFace )
	instanceMirrorButton = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='instanceMirror.png', ann = 'Instance Mirror', rpt = True, c = self.InstanceMirror)
	
	cmd.image( w = 19, h = 32, image = 'modelUISpacer.png')	
	
	dupFaceExtractButton = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='duplicateFaceExtract.png', ann = 'Duplicate Face and Extract', rpt = True, c = self.DuplicateAndExtract )
	combineObjectsButton = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='combineObjects.png', ann = 'Combine Objects and Merge Verts', rpt = True, c = self.CombineAndMerge )
	circleVertsButton = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='circleVerts.png', ann = 'Circle Verts', rpt = True, c = self.CircleVerts)
	makePlanarButton = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='makePlanar.png', ann = 'Make Planar', rpt = True, c = self.MakePlanar)
	
	cmd.image( w = 19, h = 32, image = 'modelUISpacer.png')
	
	cmd.text( label='Selection: ' )
	fToBorderB = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='selectBorderEdge.png', ann = 'Face to Border Edge', rpt = True, c = self.SelectBorderEdges)
	selectHEdgesB = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='selectHardEdges.png', ann = 'Select Hard Edges', rpt = True, c = self.SelectHardEdges)
	storeSelectionB = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='storeSelection.png', ann = 'Store Selection', rpt = True, c = self.StoreSelection)
	restoreSelectionB = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='restoreSelection.png', ann = 'Restore Selection', rpt = True, c = self.RestoreSelection)
        
        cmd.image( w = 19, h = 32, image = 'modelUISpacer.png')
	
	rdBrowserB = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='rdBrowser.png', ann = 'RD Browser', rpt = True, c = self.RDBrowser)
	dToolsB = cmd.iconTextButton( w = 32, h = 32, style='iconOnly', image1='dTools.bmp', ann = 'D Tools Main Window', rpt = True, c = self.RDModelingUIWindow)        
        
    
    
    def SmoothMayaObject(self):		
	allObjects = cmd.filterExpand(sm = 12)
	
	if not allObjects:
	    return
	
	for indObject in allObjects:
	    smoothVal = cmd.intField(self.mSmoothIF, q = True, v = True)
	    cmd.select(indObject, r = True)
	    cmd.polySmooth(mth=0, dv= smoothVal, c=1, kb=1, ksb=1, khe=0, kt=1, kmb=1, suv=1, peh=0, sl=1, dpe=1, ps=0.1, ro=1)
	    
	cmd.select(allObjects, r = True)    

    def RemoveMayaSmooth(self):	
	selectedObjects = cmd.filterExpand(sm = 12)
	
	if not selectedObjects:
	    return
	
	for indObject in selectedObjects:
	    #get the shape node
	    relatives = cmd.listRelatives(indObject, f = True, s = True)
	    if not relatives:
		continue

	    #get the destination connections
	    connections = cmd.listConnections(relatives[0], d = False)

	    #loop through all the connections and check to see if the node is a polySmoothFace node
	    for con in connections:
		if cmd.nodeType(con) == "polySmoothFace":
		    #if it is a polySmoothFace node, lets delete it
		    cmd.delete(con)
		    
    def DuplicateFace(self):
	selectedObjects = cmd.filterExpand(sm = 34)

	if not selectedObjects:
	    return

	if (cmd.radioButton(self.xDirectionDupRB, q = True, sl = True)):
	    cmd.polyChipOff(dup = True, sx = -1, pvt = (0, 0, 0))			

	if (cmd.radioButton(self.yDirectionDupRB, q = True, sl = True)):
	    cmd.polyChipOff(dup = True, sy = -1, pvt = (0, 0, 0))

	if (cmd.radioButton(self.zDirectionDupRB, q = True, sl = True)):
	    cmd.polyChipOff(dup = True, sz = -1, pvt = (0, 0, 0))

	if (cmd.radioButton(self.noDirectionDupRB, q = True, sl = True)):
	    cmd.polyChipOff(dup = True, pvt = (0, 0, 0))			

	cmd.polyNormal(normalMode = 0, userNormalMode = 0, ch = 1)    
     
    def DuplicateAndExtract(self):
	selectedObjects = cmd.filterExpand(sm = 34)
	
	if not selectedObjects:
	    return
		
	selList = om.MSelectionList()
	om.MGlobal.getActiveSelectionList(selList)
	
	if selList.length() > 1:
	    cmd.error("only works on a single object")
	    return
	
	try:
	    cmd.undoInfo(ock = True)
	    dagPath = om.MDagPath()
	    component = om.MObject()
	    
	    selList.getDagPath(0, dagPath, component)
	    
	    polyIds = []
	    
	    mitPolyIds = om.MItMeshPolygon(dagPath ,component)		
	    mitPolyIds.reset()
	    while not mitPolyIds.isDone():			
		polyIds.append(mitPolyIds.index())
		mitPolyIds.next()
		    
	    meshFn = om.MFnMesh()
	    meshFn.setObject(dagPath)		
	    numPolys = meshFn.numPolygons()
	    
	    polyCheckList = [None] * numPolys
	    for i in xrange(0, len(polyIds), 1):
		polyCheckList[polyIds[i]] = 1
		    
	    deletePolys = om.MIntArray()
	    
	    for i in xrange(0, numPolys, 1):
		if polyCheckList[i] == None:				
		    deletePolys.append(i)
	    
	    meshName = ""
	    objName = selectedObjects[0]
	    if '.' in objName:
		splitBuf = objName.split('.')
		meshName = splitBuf[0]		
		    
	    dupObject = cmd.duplicate(meshName)
	    cmd.select(d = True)
	    cmd.select(dupObject)
	    
	    dupSelList = om.MSelectionList()
	    om.MGlobal.getActiveSelectionList(dupSelList)		
	    
	    dupDagPath = om.MDagPath()
	    dupSelList.getDagPath(0, dupDagPath)
	    
	    faceCompFn = om.MFnSingleIndexedComponent()
	    polyComps = om.MObject()
	    polyComps = faceCompFn.create(om.MFn.kMeshPolygonComponent)
	    faceCompFn.addElements(deletePolys)
	    
	    om.MGlobal.select(dupDagPath, polyComps, om.MGlobal.kReplaceList)
	    cmd.delete()
	    cmd.select(dupObject)
	    
	except:
	    cmd.error("an error occured while duplicating polys!")
	finally:
	    cmd.undoInfo(cck = True)    
	    
    def StraightenEdgesVerts(self):
	xCheck = cmd.checkBox(self.xStraightenCB, q = True, v = True)
	yCheck = cmd.checkBox(self.yStraightenCB, q = True, v = True)
	zCheck = cmd.checkBox(self.zStraightenCB, q = True, v = True)
	
	mirrorAxis = "all"
	if cmd.checkBox('mirror_RDMT_CB', ex = True):
	    if cmd.radioButton('mirrorX_RDMT_RB', q = True, sl = True):
		mirrorAxis = "x"
	    if cmd.radioButton('mirrorY_RDMT_RB', q = True, sl = True):
		mirrorAxis = "y"
	    if cmd.radioButton('mirrorZ_RDMT_RB', q = True, sl = True):
		mirrorAxis = "z"
    
	if xCheck == False and yCheck == False and zCheck == False:
	    cmd.rdStraightenCmd(axm = mirrorAxis)
	if xCheck == True and yCheck == False and zCheck == False:
	    cmd.rdStraightenCmd(ax = "x", axm = mirrorAxis)
	if xCheck == False and yCheck == True and zCheck == False:
	    cmd.rdStraightenCmd(ax = "y", axm = mirrorAxis)
	if xCheck == False and yCheck == False and zCheck == True:
	    cmd.rdStraightenCmd(ax = "z", axm = mirrorAxis)
	if xCheck == True and yCheck == True and zCheck == False:
	    cmd.rdStraightenCmd(ax = "xy", axm = mirrorAxis)
	if xCheck == True and yCheck == False and zCheck == True:
	    cmd.rdStraightenCmd(ax = "xz", axm = mirrorAxis)
	if xCheck == False and yCheck == True and zCheck == True:
	    cmd.rdStraightenCmd(ax = "yz", axm = mirrorAxis)       		    
	
    def CircleVerts(self):    
	cmd.rdCircleVertsCmd()
	
    def MakePlanar(self):
	cmd.rdMakePlanarCmd()
	
    def ESmooth(self):
	#smoothVal = cmd.intField(self.mESmoothIF, q = True, v = True)
	smoothVal = cmd.optionMenu(self.mTightOptionMenu, q = True, sl = True)	
	
	cmd.rdESmoothCmd(nd = smoothVal)
	
    def RemoveESmooth(self):
	selectedObjects = cmd.filterExpand(sm = 12)
	    
	if not selectedObjects:
	    return
    
	cmd.setToolTo('selectSuperContext')
	for indObject in selectedObjects:	    
	    ogObj = cmd.listConnections(indObject + '.message', d = True, sh = True)
	    if not ogObj:
		continue
	    cmd.delete(indObject)	    
	    cmd.setAttr((ogObj[0] + '.intermediateObject'), False)
	    cmd.setAttr((ogObj[0] + '.visibility'), True)  

    def InstanceMirror(self):
	xVal = 1.0
	yVal = 1.0
	zVal = 1.0
	
	if (cmd.radioButton(self.xDirectionDupRB, q = True, sl = True)):
	    xVal = -1.0		
	
	if (cmd.radioButton(self.yDirectionDupRB, q = True, sl = True)):
	    yVal = -1.0

	if (cmd.radioButton(self.zDirectionDupRB, q = True, sl = True)):
	    zVal = -1.0	

	allObjects = cmd.filterExpand(sm = 12)
	for obj in allObjects:
	    dupObj = cmd.duplicate(obj, ilf = True)
	    cmd.scale(xVal, yVal, zVal, dupObj, r = True)
	
	
    def CombineAndMerge(self):	
	newObj = cmd.polyUnite(ch = 0)
	cmd.polyMergeVertex(d = 0.01)
	cmd.select(d = True)
	cmd.select(newObj)
	
	
    #procs for selection tools
    def SelectBorderEdges(self):
	cmd.rdSelectCmd(be = True)
    
    def SelectHardEdges(self):
	cmd.rdSelectCmd(he = True)
	
    def StoreSelection(self):
	self.mStoredSelection = cmd.ls(sl = True)
	
    def RestoreSelection(self):
	cmd.select(self.mStoredSelection, r = True)
	
    #other procs
    def RDBrowser(self):
	mel.eval('rdBrowser')
	

    def RDModelingUIWindow(self):
	mel.eval('rd_modeling_tool_ui_window')

#diamantModelingWindow()
