#############################
### diag @ IAM @ DM2_w25  ###
### hu_02 setUp_ver00_demo_04
#############################


##############################
import rhinoscriptsyntax as rs
import random, time, sys   ###
sys.path.append("P:/")     ###                  ### diag's path to DM_lib.py  .. please keep it !                                               
sys.path.append("P:/TUGonlineUsernam/dm2/")     ### *your* path to DM_lib.py                                            
sys.path.append("P:/WWW/TUGonlineUsernam/dm2/") ### *your* path to DM_lib.py                                            
sys.path.append("/Users/macpro/Desktop/DM2")    ### *your* path to DM_lib.py      
import DM_lib as dm        ###                  ### "dm" is alias for DM_lib / for adressing definitions etc in "DM_lib.py"
############################## reload(dm)

rs.ShowGrid(show=0)
rs.ShowGridAxes(show=0)
rs.ViewDisplayMode(mode="Wireframe")
rs.EnableRedraw(0)

dm.PointRadius(displayModeX=0, rad=2, styl=3)                   ### displayModeX=0="Wireframe" / rad=size of points / styl=pointStyle (try 0..5) / default 3, 3
dm.printDisplay(state=1, scale=0.2, thickness=1, color="Display") ### state=0/1 = off/on / for showing printWidth etc

rs.DeleteObjects(rs.AllObjects())

### BASIC SETUP / mandatory input:
### return_value of definition "dm.setUp_hu_02(..)" is 1 array containing 2 coord_arrays: [ [coordsCir], [coordsSqu] ] (circle & square)
### anzahl == number of coords: range from 8 to 1001 / 4*250 / default = 4*32 
### rotateSqu .. rotation of square_coords: may be set to/try (0, 0)..(-90,90) .. etc / default = (-90, 90)
allCoords = dm.setUp_hu_02( anzahl=4*24,  rotateSqu=random.uniform(-90,90) )
coordsCir=allCoords[0]
coordsSqu=allCoords[1]

##### check setup - just visualization of coords
##### don't execute  @ final version of homework
if 0: ### 0 for *your* final version !
    if 1:
        rs.AddPoints( coordsCir )
        rs.AddPoints( coordsSqu )
    if 0:
        rs.ObjectColor(dm.textDots(coordsCir), [111,0,11])
        rs.ObjectColor(dm.textDots(coordsSqu), [11,0,111])
    if 0:
        rs.AddCurve( coordsCir, 1)
        rs.AddCurve( coordsSqu, 1)
        for i in range( len(coordsSqu) ):
            p0  = coordsCir[i]
            p1  = coordsSqu[i]
            lin = rs.AddLine(p0, p1)
            rs.ObjectColor(lin, [222*(i!=0), 22*(i!=0), 222])
            rs.ObjectPrintWidth( lin, 1.0*(i==0) )
##### end check setup

#######################################
################ HERE YOU GO AS YOU GO:
dm.setTime()
    
#### immer gut zu wissen:
anzahl   = len(coordsSqu)
side_len = rs.Distance(coordsSqu[0], coordsSqu[int(anzahl/4)])
print "lenx of square_side =", side_len


### like 'sandUhr' / just 4 fun
coordsCir.reverse() 

### connect coordsCir..coordsSqu
allLines = [] ### leeres array
for i in range(anzahl):
    p0 = coordsCir[i]
    p1 = coordsSqu[i]
    lin = rs.AddLine( p0, p1 )  ### rs.AddLine(..) returns ID of line > saved 2 variable "lin"
    allLines.append( lin )      ### die ID 'lin' an array allLines anhaengen
    rs.ZoomExtents()
    rs.Redraw()

#######################################
#### den "mantel" mit curves bestuecken

### 1. auf den erzeugenden points/coords berechnen
###    und in array allCoords[] speichern
allCoords = []
for lin in allLines:
    coords = rs.DivideCurve( lin, 8, create_points=1 )
    allCoords.extend( coords )  ### extend ! .. liste+liste+lsite... .. not: append !
    rs.Redraw()
rs.ZoomExtents()
rs.Redraw()
combis = dm.combinate(allCoords, 2)
print "number of possible combinations/pairs =", len(combis)
### alle points (type=1) und/or  curves (type=4) entfernen
rs.DeleteObjects( rs.ObjectsByType( 1+4 ) )
#rs.Redraw()

##### sortiert nach laenge / geordnet
if 0:
    ### die moeglichen combinations/pairs nach laenge sortieren
    ### eine liste aus [comb, lenght_of_comb]
    combis_dists = [ [combi, rs.Distance( combi[0], combi[1] )] for combi in combis ]  ### smart listing
    
    ### diese liste nach val[1] (= lenght_of_combi) sortiert
    ### sodass die kuerzeren (== am 'mantel') gewaehlt werden koennen
    tim = float(time.time())
    sorted_combis = sorted(combis_dists, key=lambda val: val[1]) ### that's essential !  sort_val val[0][0][2]: sort by z_coord of combi[0]
    print "sorting took "+str(round(float(time.time()) - tim, 2))+"s"
    print "die laengen der combinations erstrecken sich von", round(sorted_combis[0][1], 2), "bis", round(sorted_combis[-1][1], 2)
    #sorted_combis.reverse() ### die laengeren voran !? curves eher im inneren 
    #random.shuffle(sorted_combis) ### durcheinandergewirbelt !? (dafuer brauchts kein sorting :)
    for i,entry in enumerate(sorted_combis[0:]):
        dm.esc()                                       ### [Esc]_key breaks the loop
        rs.ObjectColor( rs.AddCurve( entry[0] ), [222, 111, random.randint(0,222)])
        if i%500==0:                                   ### % = 'modulo' / restwert_division
            rs.Redraw()
        if i > 10001:
            print "*** brrrrrrrrrrrrrrrrr..."
            break

##### un_sortiert / random.shuffle
if 1:
    rs.Sleep(2000)
    rs.DeleteObjects(rs.ObjectsByType(4))
    ### borderlines
    rs.AddCurve( coordsSqu+coordsCir )                  ### degree=3 (default !)
    rs.ObjectColor( rs.AllObjects()[0], [111,111,111])    ### rs.AllObjects()[0] == zuletzt generiertes object
    rs.ObjectPrintWidth( rs.AllObjects()[0], 0.5 )      ### check dm.printDisplay(..)
    rs.ObjectName( rs.AllObjects()[0], "borderLine" )
    borderLine = rs.AllObjects()[0]                     ### ID der curve in var 'borderLine' schreiben
    rs.Redraw()
    
    random.shuffle(combis)

    lenx = rs.Distance( coordsSqu[0], coordsSqu[1] )    ### distanz der square_points / zwecks bezug zum setUp

    for i,comb in enumerate(combis[0:]):
        dm.esc()                                        ### [Esc]_key breaks the loop
        if rs.Distance( comb[0], comb[1]) < lenx*8:
            crv = rs.AddCurve( comb,2 )
            rs.ObjectName( crv, "crv_"+str(i) )
        if i%500 == 0:                                   ### % = 'modulo' / restwert_division
            print "i_"+str(i)+" anz crvs "+str( len( rs.ObjectsByType( 4 ) ))
            rs.Redraw()
        if len( rs.ObjectsByName("crv_*") ) > 1001:
            print i, len( rs.ObjectsByName("crv_*") ), "*** brrrrr..."
            break
    
    rs.Redraw()
    rs.Sleep(2000)
    
#    ### change print_width of curves according curve_length
#    for i,crv in enumerate(rs.ObjectsByName("crv_*")):
#        dm.esc()                                        ### [Esc]_key breaks the loop
#        lenx = rs.CurveLength( crv )
#        widx = (lenx*0.2)**2
#        rs.ObjectPrintWidth( crv, widx )
#        if i%10 == 0:                                   ### % = 'modulo' / restwert_division
#            rs.Redraw()

#################
#rs.ZoomExtents()
dm.getTime( 1 )
rs.Command("-zoom extents enter -zoom Factor 0.9 enter", 0) # change zoom for better framing
