示例#1
0
def AddPolyline(points, layer, replace_id=None):
    """Adds a polyline curve to the current model
    Parameters:
      points = list of 3D points. Duplicate, consecutive points found in
               the array will be removed. The array must contain at least
               two points. If the array contains less than four points,
               then the first point and the last point must be different.
      replace_id[opt] = If set to the id of an existing object, the object
               will be replaced by this polyline
    Returns:
      id of the new curve object if successful
    """

    points = rs.coerce3dpointlist(points, True)
    if replace_id:
        replace_id = rs.coerceguid(replace_id, True)

    rc = System.Guid.Empty
    if replace_id:
        pl = Rhino.Geometry.Polyline(points)
        if scriptcontext.doc.Objects.Replace(replace_id, pl):
            rc = replace_id
    else:
        rc = scriptcontext.doc.Objects.AddPolyline(points)

    if rc == System.Guid.Empty:
        raise Exception("Unable to add polyline to document")

    rs.ObjectName(rc, 'Layer: ' + str(layer))

    return rc
示例#2
0
 def __init__(self, skNum, numFrames):
     self.numFrames = numFrames
     self.skNumID = r'9307b2df-e6e2-4c74-8671-b350783d5ff0'
     self.textID = r'7bd51e90-2a02-4532-ab53-563ec9ad6351'
     self.param1ID = r'806cc725-66fb-4d1e-b58e-399232a82585'
     self.param2ID = r'0f1272f2-e148-44e6-8aad-6c4df5ddd485'
     self.param3ID = r'b5089d05-07b4-460c-ae65-8ffcb8b3e8f7'
     self.skNum = rs.coercerhinoobject(self.skNumID)
     self.param1 = rs.coercerhinoobject(self.param1ID)
     self.param2 = rs.coercerhinoobject(self.param2ID)
     self.param3 = rs.coercerhinoobject(self.param3ID)
     self.text = rs.coercerhinoobject(self.textID)
     
     self.progressBarID = r'e0ac605f-ff4d-471d-a5eb-65e1f8b6be94'
     self.progress = rs.coercerhinoobject(self.progressBarID).BrepGeometry
     self.plane = rg.Plane.WorldXY
     self.plane.Origin = rg.Point3d(5,100,85.913)
     
     self.skNum.Geometry.Text = 'sk'+str(skNum)
     self.skNum.CommitChanges()
     self.param1.Geometry.Text = ' '
     self.param1.CommitChanges()
     self.param2.Geometry.Text = ' '
     self.param2.CommitChanges()
     self.param3.Geometry.Text = ' '
     self.param3.CommitChanges()
     
     bbox = self.progress.GetBoundingBox(rg.Plane.WorldXY)
     currLength = bbox.Max.X - bbox.Min.X
     xScale = 1 / currLength
     xform = rg.Transform.Scale(self.plane, xScale, 1, 1)
     self.progress.Transform(xform)
     sc.doc.Objects.Replace(rs.coerceguid(self.progressBarID), self.progress)
def apply_xf(xf, obj_ids):
    new_obj_ids = []
    for guid in obj_ids:
        obj_ref = rs.coerceguid(guid, False)
        id = sc.doc.Objects.Transform(obj_ref, xf, False)
        if id != System.Guid.Empty: new_obj_ids.append(id)
    #if new_obj_ids: sc.doc.Views.Redraw()
    return (new_obj_ids)
示例#4
0
def CollapseRootLayers(roots):
    rs.EnableRedraw(False)
    for root in roots:
        try:
            rootLay = sc.doc.Layers.FindId(rs.coerceguid(rs.LayerId(root)))
            rootLay.IsExpanded = False
        except:
            pass
    rs.EnableRedraw(True)
示例#5
0
 def UpdateScaleBar(self):
     stepSize = 90/self.numFrames
     self.progress = rs.coercerhinoobject(self.progressBarID).BrepGeometry
     bbox = self.progress.GetBoundingBox(rg.Plane.WorldXY)
     currLength = bbox.Max.X - bbox.Min.X
     xScale = (currLength + stepSize) / currLength
     xform = rg.Transform.Scale(self.plane, xScale, 1, 1)
     self.progress.Transform(xform)
     sc.doc.Objects.Replace(rs.coerceguid(self.progressBarID), self.progress)
示例#6
0
def UpdateAreaTag():
    objs = rs.GetObjects('Select area tags to update', preselect = True)
    if objs is None: return

    successfulObjsRun = 0
    failedObjsRun = 0
    for obj in objs:
        try:
            host = rs.GetUserText(obj, 'hostGUID')
            if host is None:
                print "Could not find associated geometry"
                return None

            #Get number of dec places
            text = rs.TextObjectText(obj)
            splitText = text.Split(" ")

            numberString = splitText[0]
            units = splitText[-1]

            try:
                decPlaces = len(numberString.Split(".")[1])
            except:
                decPlaces = 0

            #Get area
            if rs.UnitSystem() == 8:
                area = rs.Area(rs.coerceguid(host))*0.0069444444444444
                areaText = utils.RoundNumber(area, decPlaces) + " " + units
            else:
                print "WARNING: Your units are not in inches"
                area = rs.Area(rs.coerceguid(host))
                areaText = area + ' ' + rs.UnitSystemName(False, True, True)

            rs.TextObjectText(obj, areaText)

            successfulObjsRun += 1
        except:
            failedObjsRun += 1
            print "Tag failed"

    utils.SaveFunctionData('Drawing-Update Area Tag', [__version__, successfulObjsRun, failedObjsRun])

    return successfulObjsRun
示例#7
0
def mesh_to_mesh(rhino_mesh,trg_len,vis):
    
    print rhino_mesh
    crvs = rs.DuplicateMeshBorder(rhino_mesh)
    
    
    
    vertices = [map(float, vertex) for vertex in rs.MeshVertices(rhino_mesh)]
    faces = map(list, rs.MeshFaceVertices(rhino_mesh))
    
    mesh  = Mesh.from_vertices_and_faces(vertices, faces)
    
    
    pts_objs = rs.GetObjects("Fixed Points",1)
    rs.EnableRedraw(False)
    if pts_objs:
        pts_fixed = [rs.PointCoordinates(obj) for obj in pts_objs]
        
        pts = []
        index_key = {}
        count = 0
        for k, a in mesh.vertices_iter(True):
            pts.append((a['x'], a['y'], a['z'])) 
            index_key[count] = k
            count += 1
        
        fixed = [] 
        for pt_fix in pts_fixed:
            index = rs.PointArrayClosestPoint(pts,pt_fix)
            fixed.append(index_key[index])
    
    

      
    edge_lengths = []
    for u, v in mesh.edges():
        edge_lengths.append(mesh.edge_length(u, v))
    target_start = max(edge_lengths)/2  
     
    id = rs.coerceguid(rhino_mesh, True)
    mesh_rhino_obj = rs.coercemesh(id, False)
    
    boundary = set(mesh.vertices_on_boundary())
    user_func = wrapper_2(crvs,mesh_rhino_obj,fixed,boundary,vis)
        
    rs.HideObject(rhino_mesh)
        
    remesh(mesh,trg_len,
       tol=0.1, divergence=0.01, kmax=400,
       target_start=target_start, kmax_approach=200,
       verbose=False, allow_boundary=True,
       ufunc=user_func)  
        
    rs.DeleteObject(rhino_mesh)
    return draw_light(mesh,temp = False) 
示例#8
0
    def getBrepIdsAndFaceEdgeIdxs(objrefs_Face):
        gBs = []
        idxs_Fs_perB = []

        for objref_Face in objrefs_Face:
            gBrep_withFaceToSplit = rs.coerceguid(objref_Face)
            if gBrep_withFaceToSplit in gBs:
                iB = gBs.index(gBrep_withFaceToSplit)
                idxs_Fs_perB[iB].extend(
                    list(objref_Face.Face().AdjacentEdges()))
            else:
                gBs.append(gBrep_withFaceToSplit)
                idxs_Fs_perB.append(list(objref_Face.Face().AdjacentEdges()))

        return gBs, idxs_Fs_perB
示例#9
0
def save_hatch_options(obj, defaults):
    curve_id = rs.GetUserText(obj, KEY_ORIGIN)
    curve_id = rs.coerceguid(curve_id)
    curve_obj = sc.doc.Objects.FindId(curve_id)
    hatch = obj.Geometry

    rotation = math.degrees(hatch.PatternRotation)
    default_rotation = defaults.get(KEY_ROT)
    if rotation != default_rotation:
        rs.SetUserText(curve_id, KEY_ROT, rotation)

    basepoint = hatch.BasePoint
    default_basepoint = rs.coerce3dpoint(defaults.get(KEY_BASEPOINT))
    if basepoint != default_basepoint:
        rs.SetUserText(curve_id, KEY_BASEPOINT, basepoint.ToString())
示例#10
0
def AddPolyline(points,
                layer,
                replace_id=None,
                objColor=(0, 0, 0),
                segment=''):
    """Adds a polyline to the current CAD scene
    Parameters:
      points = list of 3D points. Duplicate, consecutive points found in
               the array will be removed. The array must contain at least
               two points. If the array contains less than four points,
               then the first point and the last point must be different.
      replace_id[opt] = If set to the id of an existing object, the object
                        will be replaced by this polyline
    Returns:
      id of the new curve object if successful
    """

    points = rs.coerce3dpointlist(points, True)
    if replace_id:
        replace_id = rs.coerceguid(replace_id, True)

    rc = System.Guid.Empty
    if replace_id:
        pl = Rhino.Geometry.Polyline(points)
        plColor = Rhino.Input.Custom.GetObject.Color
        if scriptcontext.doc.Objects.Replace(replace_id, pl):
            rc = replace_id
    else:
        rc = Polyline(points)
        attributes = ObjectAttributes()
        attributes.ObjectColor = ColorTranslator.FromOle(getIfromRGB(objColor))
        attributes.ColorSource = ObjectColorSource.ColorFromObject
        zero_str = '000000'
        objName = 'Layer: ' + zero_str[:-len(str(layer))] + str(
            layer) + ' ' + segment  # str(layer)
        attributes.Name = objName
        lIdx = scriptcontext.doc.Layers.Find('MW 3D Printer Perimeter', 1)
        attributes.LayerIndex = lIdx
        doc.Objects.AddPolyline(rc, attributes)

    if rc == System.Guid.Empty:
        raise Exception("Unable to add polyline to document")

    return rc
示例#11
0
    def bakeGeo(geo_list, layer):

        rs.EnableRedraw(False)
        prev_doc = sc.doc
        sc.doc = rc.RhinoDoc.ActiveDoc
        if "SavedGeo" + layer not in sc.sticky:
            sc.sticky["SavedGeo" + layer] = []

        # delete previous objects from scene
        for obj in sc.sticky["SavedGeo" + layer]:
            rs.DeleteObject(obj)

        currLayer = rs.CurrentLayer()
        rs.AddLayer(layer)
        rs.CurrentLayer(layer)

        #add new objects to scene
        massingObjects = []
        for geo in geo_list:
            #print geo.GetType()
            if geo.GetType() == rc.Geometry.Curve:
                objDoc = sc.doc.Objects.AddCurve(geo)
            if geo.GetType() == rc.Geometry.NurbsCurve:
                objDoc = sc.doc.Objects.AddCurve(geo)
            elif geo.GetType() == rc.Geometry.Point3d:
                objDoc = sc.doc.Objects.AddPoint(geo)
            elif geo.GetType() == rc.Geometry.Circle:
                objDoc = sc.doc.Objects.AddCircle(geo)
            elif geo.GetType() == rc.Geometry.Arc:
                objDoc = sc.doc.Objects.AddArc(geo)
            elif geo.GetType() == rc.Geometry.Mesh:
                objDoc = sc.doc.Objects.AddMesh(geo)
            else:
                continue
            massingObjects += [rs.coerceguid(objDoc)]

        #store objects in sticky for deletion
        sc.sticky["SavedGeo" + layer] = massingObjects
        rs.CurrentLayer(currLayer)

        sc.doc = prev_doc
        rs.EnableRedraw(True)
def project_text0(vase):
    size = Rhino.Geometry.Surface.GetSurfaceSize(rs.coercesurface(vase))
    boundary = rs.AddRectangle(rs.WorldXYPlane(), size[1], size[2])

    curves = create_text_curves("naama")
    new_curves = apply_crv(vase, boundary, curves)

    # rs.DeleteObjects(text_obj)
    # rs.DeleteObjects(boundary)

    id = rs.coerceguid(new_curves[2], True)
    new_srf = split_srf(vase, [id])

    strid = new_srf[1].Id.ToString()
    rs.FlipSurface(new_srf[1].Id, flip=True)
    bb = rs.coerceboundingbox(rs.BoundingBox(strid))
    normal = rs.SurfaceNormal(strid, rs.SurfaceClosestPoint(strid, bb.Center))
    cmd = "_ExtrudeSrf _SelID %s _Enter Direction %s %s 0.1 _Enter" % (strid, point2str(normal), point2str(bb.Center))

    print cmd
    rs.Command(cmd)

    return True
示例#13
0
    try:
        valStr = str(value)
        if valStr[0] == '#':
            return True
        else:
            return False
    except:
        return False


if __name__ == "__main__":
    attr0 = rc.DocObjects.ObjectAttributes()
    attr0.ColorSource = rc.DocObjects.ObjectColorSource.ColorFromObject
    attr0.ObjectColor = drawing.Color.White

    id0 = rs.coerceguid("fc9f0f50-68f7-483b-88ef-55c7e38c3bab")
    id1 = rs.coerceguid("e4fb7017-3d8b-4ae0-8a50-8be50ad38476")
    id2 = rs.coerceguid("dae1b0b6-0c67-4659-956d-196e38c93898")
    attr0.ObjectColor = GetRandomNamedColor()
    attr1 = attr0.Duplicate()
    attr2 = attr0.Duplicate()
    for i in range(100):
        attr1.ObjectColor = ChangeColorBrightness(attr1.ObjectColor, 1.1)
        attr2.ObjectColor = ChangeColorBrightness(attr2.ObjectColor, .9)

        sc.doc.Objects.ModifyAttributes(id0, attr0, True)
        sc.doc.Objects.ModifyAttributes(id1, attr1, True)
        sc.doc.Objects.ModifyAttributes(id2, attr2, True)
        sc.doc.Views.Redraw()
        rs.Sleep(10)
def get_command_objects(serial):
    objs = list(scriptcontext.doc.Objects.AllObjectsSince(serial))
    return map(lambda x: rs.coerceguid(x, True), objs)
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")
示例#16
0
def rc_collapse_box():

    go = Rhino.Input.Custom.GetObject()
    go.GeometryFilter = Rhino.DocObjects.ObjectType.Brep

    default_KeepLayer = sc.sticky["KeepLayer"] if sc.sticky.has_key(
        "KeepLayer") else False
    default_IgnoreOpen = sc.sticky["IgnoreOpen"] if sc.sticky.has_key(
        "IgnoreOpen") else False
    opt_KeepLayer = Rhino.Input.Custom.OptionToggle(default_KeepLayer, "No",
                                                    "Yes")
    opt_IgnoreOpen = Rhino.Input.Custom.OptionToggle(default_IgnoreOpen, "No",
                                                     "Yes")

    go.SetCommandPrompt("Select Breps")
    go.AddOptionToggle("KeepLayer", opt_KeepLayer)
    go.AddOptionToggle("IgnoreOpenBreps", opt_IgnoreOpen)

    go.GroupSelect = True
    go.SubObjectSelect = False
    go.AcceptEnterWhenDone(True)
    go.AcceptNothing(True)
    go.EnableClearObjectsOnEntry(False)
    go.EnableUnselectObjectsOnExit(False)
    go.GroupSelect = True
    go.SubObjectSelect = False
    go.DeselectAllBeforePostSelect = False

    res = None
    bHavePreselectedObjects = True

    while True:
        res = go.GetMultiple(1, 0)
        if res == Rhino.Input.GetResult.Option:
            go.EnablePreSelect(False, True)
            continue
        #If not correct
        elif res != Rhino.Input.GetResult.Object:
            rs.Redraw()
            print "No breps were selected!"
            return Rhino.Commands.Result.Cancel
        if go.ObjectsWerePreselected:
            rs.Redraw()
            bHavePreselectedObjects = True
            go.EnablePreSelect(False, True)
            continue
        break

    OPT_IGNORE_OPEN = opt_IgnoreOpen.CurrentValue
    OPT_KEEP_LAYER = opt_KeepLayer.CurrentValue
    sticky["IgnoreOpen"] = OPT_IGNORE_OPEN
    sticky["KeepLayer"] = OPT_KEEP_LAYER

    rs.EnableRedraw(False)

    input_breps = []
    for i in xrange(go.ObjectCount):
        b_obj = go.Object(i).Object()
        input_breps.append(b_obj.Id)

    current_cplane = sc.doc.Views.ActiveView.ActiveViewport.GetConstructionPlane(
    )
    temp_cplane = current_cplane.Plane
    current_cplane.Plane = rs.WorldXYPlane()

    solid_brep_count = 0
    for brep in input_breps:

        if not rs.IsObjectSolid(brep):
            solid_brep_count += 1
            if OPT_IGNORE_OPEN: continue

        if OPT_KEEP_LAYER: brep_layer = rs.ObjectLayer(rs.coerceguid(brep))

        exploded = rs.ExplodePolysurfaces(brep, True)
        remaining_srfs = []
        for srf in exploded:
            norm = rs.SurfaceNormal(srf, [0.5, 0.5])
            if 10 > rs.VectorAngle(norm, [0, 0, 1]) or 10 > rs.VectorAngle(
                    norm, [0, 0, -1]):
                rs.DeleteObject(srf)
            else:
                remaining_srfs.append(srf)
        areas = [rs.SurfaceArea(s) for s in remaining_srfs]
        areas = [x[0] for x in areas]
        srfs, areas = zip(
            *sorted(zip(remaining_srfs, areas), key=lambda x: x[1]))
        pt1, _ = rs.SurfaceAreaCentroid(srfs[-1])
        pt2, _ = rs.SurfaceAreaCentroid(srfs[-2])
        vect = rs.VectorCreate(pt2, pt1)
        vect = rs.VectorDivide(vect, 2)
        rs.MoveObject(srfs[-1], vect)

        if OPT_KEEP_LAYER: rs.ObjectLayer(srfs[-1], brep_layer)
        rs.SelectObjects(srfs[-1])
        rs.DeleteObjects(srfs[:-1])

    rs.EnableRedraw(True)
    rs.Redraw()

    current_cplane.Plane = temp_cplane
    if solid_brep_count > 0:
        outcome = " and were not collapsed." if OPT_IGNORE_OPEN else " and may have been flattened incorrectly. Check input geometry."
        report = str(solid_brep_count) + " brep(s) were not closed" + outcome
        print report
示例#17
0
def nurbs_to_mesh(srf,trg_len,vis):
    
    crvs = rs.DuplicateEdgeCurves(srf) 
    
    if len(crvs)>1:
        joint = rs.JoinCurves(crvs,True)
        if joint:
            if len(joint) > 2:
                print "hole" 
    else:
        if rs.IsCurveClosed(crvs[0]):
            joint = [crvs[0]]
            print "closed"#e.g. if it is a disk
        else:
            print "Surface need to be split"#e.g. if it is a sphere
            return None
         

    
    #sort curves (this is cheating: the longer curve is not necessarily the outer boundary!) 
    #todo: an inside outside comparison in uv space
    crvs_len = [rs.CurveLength(crv) for crv in joint] 
    crvs  = [x for (_,x) in sorted(zip(crvs_len,joint))]
    
    outer_crv =  crvs[-1]
    inner_crvs = crvs[:-1]
    
    outer_bound_pts = get_boundary_points(outer_crv,trg_len)
    if inner_crvs: inner_bounds_pts = [get_boundary_points(crvs,trg_len) for crvs in inner_crvs]
    
    all_pts = copy.copy(outer_bound_pts)
    if inner_crvs: 
        for pts in inner_bounds_pts:
            all_pts += pts
    
    outbound_keys = get_boundary_indecies(outer_bound_pts,all_pts)

    inbounds_keys = []
    if inner_crvs:
        for inner_bound_pts in inner_bounds_pts:
            inbounds_keys.append(get_boundary_indecies(inner_bound_pts,all_pts))   
     

    rs.DeleteObjects(crvs)        

    all_pts_uv = convert_to_uv_space(srf,all_pts) 
    tris = delaunay(all_pts_uv,outbound_keys,inbounds_keys)
    
    mesh = Mesh()
    
    for i,pt in enumerate(all_pts):
        mesh.add_vertex(str(i),{'x' : pt[0], 'y' : pt[1], 'z' : pt[2]})
    for tri in tris:
        mesh.add_face(tri)  
    
    edge_lengths = []
    for u, v in mesh.edges():
        edge_lengths.append(mesh.edge_length(u, v))
    
    target_start = max(edge_lengths)/2

    rs.EnableRedraw(False)
    
    srf_id = rs.coerceguid(srf, True)
    brep = rs.coercebrep(srf_id, False)   
    tolerance = rs.UnitAbsoluteTolerance()
    
    fixed = outbound_keys+[item for sublist in inbounds_keys for item in sublist]
    user_func = wrapper(brep,tolerance,fixed,vis)
    

    remesh(mesh,trg_len,
       tol=0.1, divergence=0.01, kmax=300,
       target_start=target_start, kmax_approach=150,
       verbose=False, allow_boundary=False,
       ufunc=user_func)
 
    for k in xrange(10):
        mesh_smooth_centroid(mesh,fixed=fixed,kmax=1) 
        user_func(mesh,k)
    
    return draw_light(mesh,temp = False) 
    

    
    
    


    
示例#18
0
def importCAD(filePath, scaleDWG = False):
    explodeBlockBoo = True

    #setup the layers
    importLayerNumber = 6000
    importLayerObj = layers.AddLayerByNumber(importLayerNumber, False)
    importLayerName = layers.GetLayerNameByNumber(importLayerNumber)

    #Shorten cad file name
    fileNameExt = os.path.basename(filePath)
    fileName = os.path.splitext(fileNameExt)[0]

    #create layer name
    time = utils.GetDatePrefix()
    iter = "01"
    layerName = time+"_"+fileName+"_"+iter

    #Check if this layer already exists
    while rs.IsLayer(importLayerName + "::" + time + "_" + fileName + "_" + iter):
        iterInt = int(iter)+1
        if len(str(iterInt))<2:
            iter = "0" + str(iterInt)
        else:
            iter = str(iterInt)

    elementLayerName = importLayerName + "::" + time + "_" + fileName + "_" + iter
    elementLayer = rs.AddLayer(elementLayerName)

    rs.CurrentLayer(elementLayer)

    #get intial list of all layers in the file
    currentLayers = rs.LayerNames()

    rs.Command('_-Import "' + filePath + '" _IgnoreThickness=Yes _ModelUnits=Inches _Enter', False)

    #get new layers added
    endLayersNames = rs.LayerNames()
    newLayers = diff(endLayersNames, currentLayers)

    for layer in newLayers:
        rs.ParentLayer(layer, elementLayer)
        objects = rs.ObjectsByLayer(layer)
        if rs.IsLayerEmpty(layer):
            rs.DeleteLayer(layer)
        else:
            for obj in objects:
                if rs.IsDimension(obj):
                    rs.DeleteObject(obj)
                elif rs.IsHatch(obj):
                    rs.DeleteObject(obj)

    #Get all the imported geometry
    allObjects = []
    finalLayers = rs.LayerChildren(rs.CurrentLayer())
    blockNames = []
    for finalLayer in finalLayers:
        layerObjects = rs.ObjectsByLayer(finalLayer)
        for layerObject in layerObjects:
            if rs.IsBlockInstance(layerObject):
                blockNames.append(rs.BlockInstanceName(layerObject))
                allObjects.append(rs.ExplodeBlockInstance(layerObject, True))
            else:
                allObjects.append(layerObject)
    finalAllObjects = list(flatten(allObjects))

    for eachBlock in blockNames:
        try:
            rs.DeleteBlock(eachBlock)
        except:
            pass

    #Scale objects
    if scaleDWG:
        rs.ScaleObjects(finalAllObjects, [0,0,0], [.001, .001, .001])

    #Collapse layers
    try:
        rootLay = sc.doc.Layers.FindId(rs.coerceguid(rs.LayerId(elementLayerName)))
        rootLay.IsExpanded = False
    except:
        pass
    print "Import Successful"
    return finalAllObjects
示例#19
0
def nurbs_to_mesh_ani(srf,trg_len_min,trg_len_max,vis):
    trg_len = trg_len_max
    
    
    u_div = 30
    v_div = 30
    u_domain = rs.SurfaceDomain(srf, 0)
    v_domain = rs.SurfaceDomain(srf, 1)
    u = (u_domain[1] - u_domain[0]) / (u_div - 1)
    v = (v_domain[1] - v_domain[0]) / (v_div - 1)
    

    gauss = []
    for i in xrange(u_div):
        for j in xrange(v_div):
            data = rs.SurfaceCurvature (srf, (u_domain[0] + u * i, v_domain[0] + v * j))
            gauss.append(abs(data[7]))
            pt = rs.EvaluateSurface(srf,u_domain[0] + u * i, v_domain[0] + v * j)
            #rs.AddTextDot(round(abs(data[7]),3),pt)
    gauss_max = max(gauss)
    gauss_min = min(gauss)
    
    print gauss_max
    print gauss_min
    

            
    crvs = rs.DuplicateEdgeCurves(srf) 
    
    if len(crvs)>1:
        joint = rs.JoinCurves(crvs,True)
        if joint:
            if len(joint) > 2:
                print "hole" 
    else:
        if rs.IsCurveClosed(crvs[0]):
            joint = [crvs[0]]
            print "closed"#e.g. if it is a disk
        else:
            print "Surface need to be split"#e.g. if it is a sphere
            return None
         

    
    #sort curves (this is cheating: the longer curve is not necessarily the outer boundary!) 
    #todo: an inside outside comparison in uv space
    crvs_len = [rs.CurveLength(crv) for crv in joint] 
    crvs  = [x for (_,x) in sorted(zip(crvs_len,joint))]
    
    outer_crv =  crvs[-1]
    inner_crvs = crvs[:-1]
    
    outer_bound_pts = get_boundary_points(outer_crv,trg_len)
    if inner_crvs: inner_bounds_pts = [get_boundary_points(crvs,trg_len) for crvs in inner_crvs]
    
    all_pts = copy.copy(outer_bound_pts)
    if inner_crvs: 
        for pts in inner_bounds_pts:
            all_pts += pts
    
    outbound_keys = get_boundary_indecies(outer_bound_pts,all_pts)

    inbounds_keys = []
    if inner_crvs:
        for inner_bound_pts in inner_bounds_pts:
            inbounds_keys.append(get_boundary_indecies(inner_bound_pts,all_pts))   
     

    rs.DeleteObjects(crvs)        

    all_pts_uv = convert_to_uv_space(srf,all_pts) 
    tris = delaunay(all_pts_uv,outbound_keys,inbounds_keys)
    
    mesh = Mesh()
    
    for i,pt in enumerate(all_pts):
        mesh.add_vertex(str(i),{'x' : pt[0], 'y' : pt[1], 'z' : pt[2]})
    for tri in tris:
        mesh.add_face(tri)  
    
    edge_lengths = []
    for u, v in mesh.edges():
        edge_lengths.append(mesh.edge_length(u, v))
    
    target_start = max(edge_lengths)/22

    rs.EnableRedraw(False)
    
    srf_id = rs.coerceguid(srf, True)
    brep = rs.coercebrep(srf_id, False)   
    tolerance = rs.UnitAbsoluteTolerance()
    
    fixed = outbound_keys+[item for sublist in inbounds_keys for item in sublist]
    user_func = wrapper(brep,tolerance,fixed,vis)
    

    remesh_ani(srf,mesh,trg_len_min,trg_len_max,gauss_min,gauss_max,
       tol=0.1, divergence=0.008, kmax=400,
       target_start=target_start, kmax_approach=200,
       verbose=False, allow_boundary=False,
       ufunc=user_func)
 
    for k in xrange(1):
        mesh_smooth_on_local_plane(mesh,k=1,d=0.2,fixed=fixed)  
        user_func(mesh,k)
    
    return draw_light(mesh,temp = False)    
    
    


    
示例#20
0
import rhinoscriptsyntax as rs
import ghpythonlib.treehelpers as th
import scriptcontext as sc
import Rhino as rc
import System.Guid as Guid
# import Grasshopper as gh

# sc.doc = rc.RhinoDoc.ActiveDoc
# # rc.RhinoDoc.Objects.
# sc.doc = rc.RhinoDoc.ActiveDoc
# rc.RhinoDoc.SelectObjects
# rs.object
print(rs.coercerhinoobject(guids[0]))
print(type(srfs[0]))
print(rs.SurfaceAreaCentroid(srfs[0]))
print(rs.coerceguid(srfs[0]))

seq = [x * dist + dist for x in range(count)]
intervals = [(x - dist, x) for x in seq]


def groupByPosition(pairs):
    # values = set(map(lambda x:x[1], pairs))
    newpairs = [[y for y in pairs if min(x) < y[1] < max(x)]
                for x in intervals]
    # print newpairs
    return sorted(newpairs, key=lambda x: x[0][1])


srfpairs = [[x, rs.SurfaceAreaCentroid(x)[0][axis], str(x)] for x in srfs]
# guidout = [rs.coercerhinoobject(x) for x in guids]