"""
HB_ClipSymmetry V1.0

Last Modified: 6/28/2017
Works with CINEMA 4D R16.050 and up.
Copyright: Holger Biebrach, www.c4dstuff.com

Name-US: HB_ClipSymmetry
Description-US: Selected Object will be made Symmetrical with Clipping on the X-Axis

Useage:
The Selected Object will become symmetrical. On the YZ-Plane the Object gets Clipped. 
Use The ConvertSymmetry Script to convert the Setup back to a Polygonal Object.

Video Tutorial:
https://youtu.be/G9XVCcOe6jQ?t=22m31s

ChangeLog:

6/28/2017 Release Version v1.0

"""

import c4d
from c4d import utils

def GetGlobalPosition(obj):
    return obj.GetMg().off

def GetGlobalRotation(obj):
    return utils.MatrixToHPB(obj.GetMg())


def ResetLocalCoordinates(obj):
    m = obj.GetMg()
    m.off = c4d.Vector(0,0,0)
    m.v1 = c4d.Vector(1,0,0)
    m.v2 = c4d.Vector(0,1,0)
    m.v3 = c4d.Vector(0,0,1)
    doc.AddUndo(c4d.UNDOTYPE_CHANGE, obj)
    obj.SetMl(m)

def SetGlobalRotation(obj, rot):

    m = obj.GetMg()
    pos = m.off
    scale = c4d.Vector( m.v1.GetLength(),
                        m.v2.GetLength(),
                        m.v3.GetLength())

    m = utils.HPBToMatrix(rot)

    m.off = pos
    m.v1 = m.v1.GetNormalized() * scale.x
    m.v2 = m.v2.GetNormalized() * scale.y
    m.v3 = m.v3.GetNormalized() * scale.z
    
    doc.AddUndo(c4d.UNDOTYPE_CHANGE, obj)
    obj.SetMg(m)

def main():
    doc.StartUndo()
    
    bc = c4d.BaseContainer()
    c4d.gui.GetInputState(c4d.BFM_INPUT_KEYBOARD,c4d.BFM_INPUT_CHANNEL,bc)
    modifier= bc[c4d.BFM_INPUT_QUALIFIER]

    selobj = doc.GetActiveObject()
    
    if modifier==0:#NO MODIFIER
        objPos=selobj.GetMl()


    symobj=c4d.BaseObject(c4d.Osymmetry)
    symobj.SetName("HB_ClipSymmetry")
    symobj.SetMg(objPos)
    
    symobj.InsertAfter(selobj)
    doc.AddUndo(c4d.UNDOTYPE_NEW, symobj)
    
    boolobj=c4d.BaseObject(c4d.Oboole)
    boolobj.SetName("HB_Boole")
    boolobj[c4d.BOOLEOBJECT_SINGLE_OBJECT]=True
    boolobj[c4d.BOOLEOBJECT_HIDE_NEW_EDGES]=True

    boolobj.InsertUnder(symobj)
    doc.AddUndo(c4d.UNDOTYPE_NEW, boolobj)
    
    
    cutcube=c4d.BaseObject(c4d.Ocube)
    cutcube.SetName("HB_ClipCube")
    cutcube[c4d.PRIM_CUBE_LEN,c4d.VECTOR_X]=10000
    cutcube[c4d.PRIM_CUBE_LEN,c4d.VECTOR_Y]=10000
    cutcube[c4d.PRIM_CUBE_LEN,c4d.VECTOR_Z]=10000
    cutcube[c4d.ID_BASEOBJECT_REL_POSITION,c4d.VECTOR_X]=-5000
    
    cutcube.InsertUnder(boolobj)
    doc.AddUndo(c4d.UNDOTYPE_NEW, cutcube)
    selobjRoot=c4d.BaseObject(c4d.Onull)
    selobjRoot.SetName("HB_SymmetryCenter")
    selobjRoot.InsertUnder(boolobj)
    doc.AddUndo(c4d.UNDOTYPE_NEW, selobjRoot)
    doc.AddUndo(c4d.UNDOTYPE_DELETE, selobj)
    selobj.Remove()
    
    selobj.InsertUnder(selobjRoot)
    doc.AddUndo(c4d.UNDOTYPE_NEW, selobj)
    ResetLocalCoordinates(selobj)

    doc.EndUndo()
    c4d.EventAdd()

if __name__=='__main__':
    main()
