def relax_mesh_on_surface():
    
    srf = rs.ObjectsByLayer("re_01_trg_srf")[0]
    srf_id = rs.coerceguid(srf, True)
    brep = rs.coercebrep(srf_id, False)
    
    polylines = rs.ObjectsByLayer("re_02_polys")
    pts_objs = rs.ObjectsByLayer("re_03_points")
    guides = rs.ObjectsByLayer("re_04_guides")
    
    vis = 1
    
    rs.LayerVisible("re_02_polys", False)
    rs.LayerVisible("re_03_points", False)
    
    pts = get_points_coordinates(pts_objs)
    
    mesh = Mesh()
    
    for i,pt in enumerate(pts):
        color = rs.ObjectColor(pts_objs[i])
        type, guide_srf,guide_crv = None, None, None

        if [rs.ColorRedValue(color),rs.ColorGreenValue(color),rs.ColorBlueValue(color)] == [255,0,0]:
            type = 'fixed'
        elif [rs.ColorRedValue(color),rs.ColorGreenValue(color),rs.ColorBlueValue(color)] == [255,255,255]:
            type = 'free'
        elif [rs.ColorRedValue(color),rs.ColorGreenValue(color),rs.ColorBlueValue(color)] == [0,0,0]:
            type = 'surface'
            guide_srf = brep
        else:
            type = 'guide'
            for guide in guides:
                if rs.ObjectColor(guide) == color:
                    crv_id = rs.coerceguid(guide, True)
                    crv = rs.coercecurve(crv_id, False)
                    guide_crv = crv
                    break       
            
        mesh.add_vertex(str(i),{'x' : pt[0], 'y' : pt[1], 'z' : pt[2], 'color' : color, 'type' : type,'guide_srf' : guide_srf,'guide_crv' : guide_crv})
    

    
    polys = get_polyline_points(polylines)
    tris = get_faces_from_polylines(polys,pts)
    
    for tri in tris:
        mesh.add_face(tri)     
     
     
        
    user_function = wrapper(vis)    
    fixed = [key for key, a in mesh.vertices_iter(True) if a['type'] == 'fixed']
    
    mesh_smooth_centerofmass(mesh, fixed=fixed, kmax=150, d=1.0, ufunc=user_function)
    
    #mesh_smooth_angle(mesh, fixed=fixed, kmax=150, ufunc=user_function)
    
    #mesh_smooth_centroid(mesh, fixed=fixed, kmax=150, d=1.0, ufunc=user_function)
    
    #mesh_smooth_area(mesh, fixed=fixed, kmax=150, d=1.0, ufunc=user_function)
    
    
    #draw_light(mesh,temp = False)
    
    draw(mesh,"re_03_points","re_02_polys")
def relax_mesh_on_surface():

    polylines = rs.ObjectsByLayer("re_02_polys")
    pts_objs = rs.ObjectsByLayer("re_03_points")

    vis = 5
    kmax = 2000
    dis = 0.3
    dev_threshold = 0.003
    angle_max = 30

    pts = get_points_coordinates(pts_objs)

    mesh = Mesh()

    for i, pt in enumerate(pts):
        mesh.add_vertex(str(i), {'x': pt[0], 'y': pt[1], 'z': pt[2]})

    polys = get_polyline_points(polylines)
    tris = get_faces_from_polylines(polys, pts)

    for tri in tris:
        mesh.add_face(tri)

    rs.EnableRedraw(False)

    pts = []
    for key, a in mesh.vertices_iter(True):

        pt1 = (a['x'], a['y'], a['z'])
        pts.append(pt1)
        vec = mesh.vertex_normal(key)
        vec = scale(normalize(vec), dis)
        pt2 = add_vectors(pt1, vec)

        pt2 = add_vectors(pt1, vec)
        a['x2'] = pt2[0]
        a['y2'] = pt2[1]
        a['z2'] = pt2[2]

        a['normal'] = vec
        #rs.AddLine(pt1,pt2)

    faces_1 = draw(mesh, dev_threshold)
    rs.HideObjects(faces_1)

    for k in range(kmax):
        nodes_top_dict = {key: [] for key in mesh.vertices()}
        polys = []
        max_distances = []
        for u, v in mesh.edges():
            pt1 = mesh.vertex_coordinates(u)
            pt2 = mesh.vertex_coordinates(v)
            pt3 = mesh.vertex[u]['x2'], mesh.vertex[u]['y2'], mesh.vertex[u][
                'z2']
            pt4 = mesh.vertex[v]['x2'], mesh.vertex[v]['y2'], mesh.vertex[v][
                'z2']
            points = [pt1, pt2, pt3, pt4]

            points = rs.coerce3dpointlist(points, True)
            rc, plane = Rhino.Geometry.Plane.FitPlaneToPoints(points)
            pt3, pt4 = [plane.ClosestPoint(pt) for pt in points[2:]]

            vec = scale(normalize(subtract_vectors(pt3, pt1)), dis)
            pt3 = add_vectors(pt1, vec)

            vec = scale(normalize(subtract_vectors(pt4, pt2)), dis)
            pt4 = add_vectors(pt2, vec)

            nodes_top_dict[u].append(pt3)
            nodes_top_dict[v].append(pt4)

            distances = [
                distance(pt1, pt2) for pt1, pt2 in zip(points[2:], [pt3, pt4])
            ]
            max_distances.append(max(distances))

        for key, a in mesh.vertices_iter(True):
            cent = centroid(nodes_top_dict[key])
            pt = mesh.vertex_coordinates(key)
            vec = subtract_vectors(cent, pt)
            norm = a['normal']

            if angle_smallest(vec, norm) < angle_max:
                a['x2'] = cent[0]
                a['y2'] = cent[1]
                a['z2'] = cent[2]

        if k % vis == 0:
            rs.Prompt(
                "Iteration {0} of {1} with with deviation sum {2}".format(
                    k, kmax, round(sum(max_distances), 4)))
            draw_light(mesh, temp=True)
        if max(max_distances) < dev_threshold or k == kmax:
            print "Iteration {0} of {1} with deviation sum {2}".format(
                k, kmax, round(sum(max_distances), 4))
            break

    dfaces_2 = draw(mesh, dev_threshold)
    rs.ShowObjects(faces_1)
    rs.EnableRedraw(True)
    print max(max_distances)