###################################
### DM2_w23 # AGruber@tugraz.at ###
### finale CC_100 / timon.T.    ###
### project atom 2 screen       ###
###################################


##############################
import rhinoscriptsyntax as rs
import random, time, sys, os   ###
sys.path.append("/Users/Titi/Desktop/DM2 End:/")     ###
sys.path.append("P:/")     ###
import DM_lib as dm        ### reload( dm )
import davidCoordsList as davi
##############################      

##################
rs.UnitSystem(4)                                        # km = 5, meters = 4, cm = 3 etc
rs.ShowGrid(None, 0)                                    # grid > 0 = off
rs.ShowGridAxes(None, 0)                                # y/y/z axen display > 0/1 = off/on
rs.ViewDisplayMode(rs.CurrentView(), "wireframe")
#rs.ViewDisplayMode(rs.CurrentView(), "ghosted")
rs.Command("cplane w t enter", 0)						# cPlane World Top
dm.PointRadius(displayModeX=0, rad=1, styl=1)
dm.PointRadius(displayModeX=1, rad=1, styl=1)
dm.PointRadius(displayModeX=3, rad=1, styl=1)
dm.printDisplay(1)                                      # nomen est omen
rs.EnableRedraw(0)
##################

def makeName( name="tst", frameNumber=1110, anzahl=4, format="png"):
    pre = ("0"*10 + str(frameNumber))[-anzahl:]
    name = pre+"_"+name+"."+format
    return name


capture = 0
name = "tstT"
path = "P:/WWW/tmanguy/dm2/animate/"
if not os.path.exists(path): os.makedirs(path)
fram = 0
davidCoords = davi.davidCoords

#davidCoords = [ rs.VectorAdd(cor, [0,0, 0.3 ]) for cor in davidCoords]

print "len(davidCoords)", len(davidCoords)
#rs.AddPoints( davidCoords )

def makeAtomKern (position=[1,2,3], radius=0.1, dichte=32):
    arcs = []
    for i in range(dichte):
        pX = [ random.uniform(-1001,1001) for i in range(3) ]
        pY = [ random.uniform(-1001,1001) for i in range(3) ]
        planeX = rs.PlaneFromPoints(position, pX, pY)
        arc = rs.AddArc(planeX, radius, 180.0)
        arcs.append( arc )
    return arcs





screen1 = rs.ObjectsByName("Surface")[0]

rs.ShowObjects( rs.AllObjects() )
dm.newEmptyLayer("PROJ::conti", [100,250,0])
dm.newEmptyLayer("PROJ::conti::small", [100,150,200])
dm.newEmptyLayer("PROJ::points", [0,0,200] )
dm.newEmptyLayer("PROJ::surface", [0 ,0,200] )

coordssurface = dm.getSurfacePoints(screen1)
#rs.AddPoints( coordssurface )
#dm.textDots(coordssurface)
center = dm.pntInbetween(coordssurface[0], coordssurface[3])
print "center", center[0]


coords = [ dm.pnt2cor( cor  ) for cor in coordssurface ]

#print coordssurface

#######
scalFac = [2.5, 5, 2.5]
scalMov = -1.5

if 1:
    random.shuffle(davidCoords)
    arcs = []
    for i,cor in enumerate( davidCoords[0:804] ):
        arcs.extend(makeAtomKern (position=cor, radius=0.05, dichte=3))
        if i%50==0: rs.Redraw()
    projected = rs.ProjectCurveToSurface(arcs, [screen1], [1,0,0])
    center[2] += scalMov

    rs.ScaleObjects(projected, center, scalFac )
    rs.ObjectColor(projected, [230,230,230])
    rs.HideObject(projected)
    #dm.zA()
####################
anzahl = 12
fac = 1/anzahl
####################
dm.setTime()
lenx = len(arcs)
screenDist = center[0]


copList = []

if 1: ### make projection
    rs.HideObjects( arcs )
    print "len(arcs)", len(arcs)
    print "len(projected)", len(projected)
    for j in range(1,anzahl+1):
        dm.esc()
        for i,arc in enumerate(arcs):
            dm.esc()
            coordsA1 = rs.CurveEditPoints( arcs[i] )
            coordsP1 = rs.CurveEditPoints( projected[i] )
            #rs.AddLine( coordsA1[0],  coordsP1[0] )

            pX = dm.pntInbetween(coordsA1[0], coordsP1[0], fac*j)
            if random.uniform(0,100) < 30:
                pX[0] += random.uniform(-5,0)
            
            
            #rs.AddPoint( pX )
            cop = rs.CopyObject( arcs[i], rs.VectorSubtract(pX, coordsA1[0] ) )
            copList.append( cop )
            coords = rs.CurvePoints( cop )

            if j==anzahl: ### alle coords auf screen projiziert
                coords = [ [screenDist, cor[1], cor[2]] for cor in coords ] ## die letzten punkte auf screen 
            p0 = dm.pntInbetween( coords[0], coords[1], fac*j)
            p5 = dm.pntInbetween( coords[4], coords[3], fac*j)

            coords[0] = p0
            coords[4] = p5
            crv = rs.AddCurve( coords, 2 )
            rs.ObjectColor( crv, [20,220,200] )
            rs.ObjectName( crv, "zwischenCrv_"+str(j))
            ##################################################
            ### points, zunehmend mit j, also in richtg screen
            if random.uniform(0, anzahl) < j:
                #if j: print anzahl/j
                ###cors = random.choice( coords )
                numX = int(dm.reMap(j, 0, anzahl, 1, anzahl-2))
                cors = coords[0:numX-1]
                cors = coords[0:numX-1]
                lenx =len(cors)
                if lenx:
                    cors = rs.CullDuplicatePoints( cors )
                    #print "lenx=", lenx, ">>", len(cors)
                    pnts = rs.AddPoints( cors )
                    rs.ObjectColor(pnts, [anzahl*(j+2)*1, anzahl*(j+2)*1, anzahl*(j+2)*1])
                    rs.ObjectName( pnts, "zwischenPnt_"+str(j))

                    if random.uniform(0,100) < 5 and capture:
                        rs.Redraw()
                        fram += 1
                        imageName = makeName( name=name, frameNumber=fram)
                        rs.Command("-_viewCaptureToFile Unit=pixels Width=960  Height=540  Scale=2  LockAspectRatio=No TransparentBackground=No "+ path+imageName, 0)
                    
        rs.Redraw()
        fram += 1
        imageName = makeName( name=name, frameNumber=fram)
        
        ################################################
        camPosStart = [-1.2611872, -39.69160621, 5.0]
        tarPosStart = [-113.37868708, 153.13141721, 2.0]
        dm.setCameraTarget( camPosStart, tarPosStart , lens=19.99999999, rota=0, upVec=[0,0,1] ) # ... danke, andi !
        ################################################

        if  1 or capture:
            print imageName
            camPos = rs.VectorAdd( camPosStart, [-fram, 0,0] )
            tarPos = rs.VectorAdd( tarPosStart, [-fram*1.5, 0,0] )
            dm.setCameraTarget( camPos, tarPos , lens=19.99999999, rota=0, upVec=[0,0,1] ) # ... danke, andi !
            #rs.Redraw()
            #rs.Command("-_viewCaptureToFile Unit=pixels Width=960  Height=540  Scale=2  LockAspectRatio=No TransparentBackground=No "+ path+imageName, 0)

        if 0: ### delete von_hinten
            ab_Wann = 4
            redraw_Wann = 10 ### je hoeher desto oft !
            if j>ab_Wann: ### ab wann soll deleted werden ?
                num = j-ab_Wann-1
                objs = ( rs.ObjectsByName("*_"+str(num)) )
                
                objPos = []
                for obj in objs:
                    if rs.ObjectType(obj) == 1:
                        objPos.append( [obj, rs.PointCoordinates(obj)] )
                    if rs.ObjectType(obj) == 4:
                        objPos.append( [obj, rs.CurveMidPoint(obj)] )
                objPos = sorted(objPos, key=lambda sortKey: (sortKey[1][0]) )
                objPos.reverse()
                objs = [ obj[0] for obj in objPos ]
                
                for ii,obj in enumerate(objs):
                    dm.esc()
                    rs.DeleteObject( obj )
                    if ii%int(len(objs)/redraw_Wann) == 0:
                        pass
                        #rs.Redraw()
                        if random.uniform(0,100) < 5 and capture:
                            rs.Redraw()
                            fram += 1
                            imageName = makeName( name=name, frameNumber=fram)
                            rs.Command("-_viewCaptureToFile Unit=pixels Width=960  Height=540  Scale=2  LockAspectRatio=No TransparentBackground=No "+ path+imageName, 0)

                        #print ii
                        ### capture !
                print "num", num, "objs =", len(objs)
        rs.Redraw()
if 0: ### delete die restlichen von_hinten
    for num in range(num+1, anzahl):
        objs = ( rs.ObjectsByName("*_"+str(num)) )
        rs.ZoomBoundingBox( rs.BoundingBox( objs ))
        for obj in objs:
            if rs.ObjectType(obj) == 1:
                objPos.append( [obj, rs.PointCoordinates(obj)] )
            if rs.ObjectType(obj) == 4:
                objPos.append( [obj, rs.CurveMidPoint(obj)] )
        objPos = sorted(objPos, key=lambda sortKey: (sortKey[1][0]) )
        objPos.reverse()
        objs = [ obj[0] for obj in objPos ]

        for ii,obj in enumerate(objs):
            dm.esc()
            rs.DeleteObject( obj )
            if ii%int(len(objs)/redraw_Wann)==0:
                if random.uniform(0,100) < 5 and capture:
                    rs.Redraw()
                    fram += 1
                    imageName = makeName( name=name, frameNumber=fram)
                    rs.Command("-_viewCaptureToFile Unit=pixels Width=960  Height=540  Scale=2  LockAspectRatio=No TransparentBackground=No "+ path+imageName, 0)
                ### capture !
        print "num", num, "objs =", len(objs)
        rs.Redraw()
    rs.ShowObjects(rs.AllObjects())
    rs.DeleteObjects(copList)
    rs.DeleteObjects(arcs)
    rs.DeleteObjects(projected)
        
        
if 0: ### contour / silhouette
    if 1: 
        rs.CurrentLayer("PROJ::conti")
        david = rs.ObjectsByName( "david" )[0]
        distOfContis = 0.2
        rs.Command("-_contour selID "+str(david)+" enter -0.5,0,0 -2,0,0 "+str(distOfContis)+" enter", 0)
        conti = rs.SelectedObjects()
        rs.Redraw()
        rs.UnselectAllObjects()
        projected = rs.ProjectCurveToSurface( conti, [screen1], [1,0,0])
        rs.ScaleObjects(projected, center, scalFac )
        rs.DeleteObjects( conti )
        for crv in projected:
            if not rs.IsCurveClosed(crv):
                rs.DeleteObject( crv )
                rs.Redraw()
    
    if 0: 
        projected = rs.ObjectsByLayer("PROJ::conti")
        for cont in projected:
            if rs.CurveArea( cont )[0] < 2.3:
                pass
                #rs.DeleteObject( cont )
                #rs.ObjectColor(cont, [200,0,0])
                rs.ObjectLayer( cont, "PROJ::conti::small" )
        projected = rs.ObjectsByLayer("PROJ::conti")
        rs.UnselectAllObjects()
        for pro in projected:
            rs.Command("-_selBoundary selID "+str(pro)+" enter SelectionMode=Window enter", 0)
        #rs.DeleteObjects(rs.SelectedObjects())
        projected = rs.ObjectsByLayer("PROJ::conti")
    
    if 0:
        rs.UnselectAllObjects()
        tmpSrf = rs.CopyObject( screen1, [0,0,0] )
        rs.ObjectName( tmpSrf, "tmpSrf")
        rs.Command("-split selID "+str(tmpSrf)+" enter -SelLayer \"PROJ::conti\" enter enter", 0)
        rs.Redraw()
    
    if 0:
        for srf in rs.ObjectsByName("tmpSrf"):
            crv = rs.DuplicateSurfaceBorder( srf )
            rs.ObjectName( crv, "border" )
            rs.DeleteObject( srf )
    if 0:
        for crv in rs.ObjectsByName("border"):
            if not rs.IsCurveClosed(crv):
                rs.DeleteObject( crv )
                rs.Redraw()
    if 0:
        rs.ObjectColor(rs.ObjectsByName("border"), [200,200,200])
        if 1: ### Length = 76.*** meters
            for i,crv in enumerate(rs.ObjectsByName("border")):
                #print i, "-", rs.CurveLength( crv ) #areaX
                if rs.CurveLength(crv) > 80 or rs.CurveLength(crv) < 70:
                    rs.DeleteObject( crv )
                    rs.Redraw()
        umriss = rs.ObjectsByName("border")[0]
        rs.ObjectPrintWidth(umriss, 1.0) 
    
    rs.ZoomBoundingBox(rs.BoundingBox(screen1))
    #rs.DeleteObject( rs.ObjectsByName("surface")[0] )

#dm.zA()
rs.CurrentLayer("Default")
#dm.eDup(1)
dm.printDisplay(1)                                     
rs.EnableRedraw(1)