def addSphereAtEnds(): objs = rs.GetObjects("select lines to convert to lights:", rs.filter.curve) if objs: rs.Prompt("got Objects") rs.EnableRedraw(False) for obj in objs: rs.Prompt("Adding Sphere for obj " + str(obj)) endPoint = rs.CurveEndPoint(obj) startPoint = rs.CurveStartPoint(obj) rs.AddSphere(endPoint, SPHERE_RADIUS) rs.AddSphere(startPoint, SPHERE_RADIUS) rs.EnableRedraw(True)
def user_function(mesh,i): for key, a in mesh.vertices_iter(True): pt = (a['x'], a['y'], a['z']) if a['type'] == 'fixed' or a['type'] == 'free': continue if a['type'] == 'guide': point = rs.coerce3dpoint(pt) rc, t = a['guide_crv'].ClosestPoint(point) pt = a['guide_crv'].PointAt(t) elif a['type'] == 'surface': point = rs.coerce3dpoint(pt) pt = a['guide_srf'].ClosestPoint(point) mesh.vertex[key]['x'] = pt[0] mesh.vertex[key]['y'] = pt[1] mesh.vertex[key]['z'] = pt[2] if vis: if i%vis==0: rs.Prompt(str(i)) draw_light(mesh,temp = True) Rhino.RhinoApp.Wait()
def sortSurfaces(srfs, tol): srfToSelect = [] i = 0 for srf in srfs: if rs.SurfaceArea(srf)[0] < tol: srfToSelect.append(srf) rs.Prompt("Sorting: " + str(i) + "/" + str(len(srfs))) i += 1 return srfToSelect
def curveDivByDiameter(): curve = rs.GetObject("sel curve") point = rs.GetPoint("sel point") num = rs.GetReal("radius") cBool = True # ptDir = rs.GetPoint("set Direction:") numA= num if(cBool): numA = num/2 else: numA = num circle = rs.AddCircle(point,numA) ix = rs.CurveCurveIntersection(curve,circle) rs.AddPoint(ix[0][1]) # or alternatively: # rs.AddPoint(ix[0][1]) # this should get the first intersection curve # rs.AddPoint(ix[1][1]) # this should get the second intersection curve arrPt = [] count = 20 countConst = count #create a check for point by point(x,y,z) value while(True != (ix[0][1] in arrPt) and count > 0): circle = rs.AddCircle(ix[0][1],num) ix = rs.CurveCurveIntersection(curve,circle) arrPt.append(rs.AddPoint(ix[0][1])) count -= 1 rs.Prompt(str(countConst-count)); count = 20 circle = rs.AddCircle(point,numA) ix = rs.CurveCurveIntersection(curve,circle) while(True != (ix[1][1] in arrPt) and count > 0): circle = rs.AddCircle(ix[1][1],num) ix = rs.CurveCurveIntersection(curve,circle) arrPt.append(rs.AddPoint(ix[1][1])) count -= 1 rs.Prompt(str(countConst-count));
def SelectNearDupCrvs(chk_all=True, sel_dup_all=False, crv_divs=25, user_tol=0.1): msgs = Localize(rs.LocaleID()) if chk_all: crvIDs = rs.ObjectsByType(4, state=1) else: crvIDs = rs.GetObjects(msgs[0], 4, preselect=True) if not crvIDs: return if "SelNearDup_Tol" in sc.sticky: user_tol = sc.sticky["SelNearDup_Tol"] tol = sc.doc.ModelAbsoluteTolerance comp_tol = rs.GetReal(msgs[1], user_tol, minimum=tol) if comp_tol is None: return crv_bbs = [] for crvID in crvIDs: crv = sc.doc.Objects.Find(crvID).Geometry bb = crv.GetBoundingBox(True) length = crv.GetLength() crv_bbs.append((crv, bb, length)) rs.EnableRedraw(False) rs.Prompt(msgs[2]) if PC: rs.StatusBarProgressMeterShow(msgs[3], 0, 100, True) #idea - collect indices, not IDs... found_index = set() st = time.time() for i in range(len(crv_bbs) - 1): if PC and i % 100 == 0: rs.StatusBarProgressMeterUpdate(100 * i / len(crv_bbs)) for j in range(i + 1, len(crv_bbs)): #check to see if cuve is already in select list if j in found_index: continue #print "Compare curve {} to curve {}".format(i,j) if IsNearDupCrv(crv_bbs[i], crv_bbs[j], comp_tol, crv_divs): found_index.add(j) if sel_dup_all: found_index.add(i) if PC: rs.StatusBarProgressMeterHide() print msgs[4].format(time.time() - st) if found_index: #need to add list of IDs found = [crvIDs[index] for index in found_index] rs.SelectObjects(found) msg = msgs[5].format(len(found)) else: msg = msgs[6] print msg sc.sticky["SelNearDup_Tol"] = comp_tol
def callback(k, args): if k%10 == 0: rs.Prompt(str(k)) # constrain all non-fixed to a surface for key, attr in mesh.vertices(data=True): if key in fixed: continue srf = attr['srf'] x, y, z = rs.BrepClosestPoint(srf,mesh.vertex_coordinates(key))[0] attr['x'] = x attr['y'] = y attr['z'] = z conduit.redraw()
def main(): srfs = rs.GetObjects("Select objects to sort", 24, True, True, False) lowVal = getSurfaceArea("Select reference surface 1") highVal = getSurfaceArea("Select reference surface 2") tol = rs.GetReal("Enter selection tolerance (ref values: (" + str(lowVal) + " , " + str(highVal) + ")") rs.Prompt("Sorting Surfaces") rs.EnableRedraw(False) selsrf = sortSurfaces(srfs, tol) i = 0 rs.SelectObjects(selsrf) # for srf in selsrf: # rs.SelectObject(srf); # rs.Prompt("Selecting: " + str(i) + "/" + str(len(selsrf))); # i+=1; rs.EnableRedraw(True)
def DistributedSurfaceFitter(): srf_id = rs.GetObject("Surface to fit", 8, True, True) if not srf_id: return pts = rs.GetPointCoordinates("Points to fit to", False) if not pts: return for n in xrange(10000): rs.EnableRedraw(False) nSrf, dTrans, dProx = FitSurface(srf_id, pts) #Call Rhino.DeleteObject(idSrf) rs.EnableRedraw(True) rs.Prompt("Translation = %.2f Deviation = %.2f" % dTrans, dProx) if dTrans < 0.1 or dProx < 0.01: break srf_id = nSrf print "Final deviation = %.4f" % dProx
def SurfaceTensorField(): #Prompt the user for all required data srf_id = rs.GetObject("Surface for tensor curvature field", 8, True, True) if not srf_id: return u = 100 v = 100 s = 10 pListBoxResult = rs.PropertyListBox( ("U-samples", "V-samples", "Smoothing iterations"), \ (u, v, S), "Algorithm settings", "Tensor field") if not pListBoxResult: return #Convert all strings in the PopertyListBox result into numbers again u = int(pListBoxResult[0]) v = int(pListBoxResult[1]) s = int(pListBoxResult[2]) #Make sure the values are within logical limits if u<1 or v<1 or s<0: return #At this point we have all input data collected. #We also know all values are correct #Initiate the Tensor Space T, K = SurfaceTensorField(srf_id, u, v) if not T or not K: print "Unable to construct basis Tensor field" return #Smooth the Tensor Space s times for i in range(s): rs.Prompt("Smoothing tensor field. Iteration: %d" % i) T, K = SmoothTensorField(T, K) #Add all Tensors as line segments Call Rhino.EnableRedraw(False) Dim A, B For i = 0 To u For j = 0 To v A = T(i,j)(0) B = Rhino.PointAdd(A, K(i,j)) Call Rhino.AddLine(A, B) Next
def user_func(mesh,i): pts = [] key_index = {} count = 0 for k, a in mesh.vertices_iter(True): if k in boundary: continue pts.append((a['x'], a['y'], a['z'])) key_index[k] = count count += 1 if pts: points = rs.coerce3dpointlist(pts, True) points = mesh_rhino_obj.PullPointsToMesh(points) if len(pts) == len(points): #print "Yes" for key in key_index: index = key_index[key] mesh.vertex[key]['x'] = points[index][0] mesh.vertex[key]['y'] = points[index][1] mesh.vertex[key]['z'] = points[index][2] else: print "No" pass mesh_smooth_boundary(mesh,fixed,crvs, k=1, d=0.5) if vis: if i%vis==0: rs.Prompt(str(i)) draw_light(mesh,temp = True) Rhino.RhinoApp.Wait()
def RunCommand(): nester = OpenNestContext() rc = nester.GetNestingSettings() if not rc: return sheets = nester.GetSheets() if not sheets: return data = nester.GetObjectsToNest() if not data: return outlines = System.Array.CreateInstance( System.Array[Rhino.Geometry.Polyline], nester.n) for i in xrange(data.Item1.Length): outlines[i] = OpenNestLib.OpenNestUtil.BrepLoops(data.Item1[i]) rs.Prompt("Nesting, please wait") rc = OpenNestLib.Helpers.Nest(sheets, outlines, data, nester) if not rc: print "Nest failed" return print "Nesting done" #def MyFunc(): # OpenNestLib.Helpers.Nest(sheets, outlines, data, nester) #t = Task.Run.Overloads[System.Func[Task]](MyFunc) #print "OpenNest: Nesting... Keep working while the nesting finishes." scriptcontext.doc.Objects.UnselectAll() breps, dictionary = data for b in breps: scriptcontext.doc.Objects.AddBrep(b) for index, guids in zip(dictionary.Keys, dictionary.Values): for guid in guids: scriptcontext.doc.Objects.Select(guid, True, True)
def user_func(mesh,i): #dict((k, i) for i, k in self.vertices_enum()) pts = [] key_index = {} count = 0 for k, a in mesh.vertices_iter(True): if k in fixed: continue pts.append((a['x'], a['y'], a['z'])) key_index[k] = count count += 1 if pts: points = rs.coerce3dpointlist(pts, True) points = brep.Faces[0].PullPointsToFace(points, tolerance) if len(pts) == len(points): #print "Yes" for key in key_index: index = key_index[key] mesh.vertex[key]['x'] = points[index][0] mesh.vertex[key]['y'] = points[index][1] mesh.vertex[key]['z'] = points[index][2] else: print "No" pass if vis: if i%vis==0: rs.Prompt(str(i)) draw_light(mesh,temp = True) Rhino.RhinoApp.Wait()
def callback(k, args): if k % 10 == 0: rs.Prompt(str(k)) # constrain all non-fixed to a surface or guide curves for key, attr in mesh.vertices(data=True): if attr['fixed']: continue if attr['srf']: srf = attr['srf'] x, y, z = rs.BrepClosestPoint(srf, mesh.vertex_coordinates(key))[0] attr['x'] = x attr['y'] = y attr['z'] = z elif attr['crv']: crv = attr['crv'] x, y, z = rs.PointClosestObject(mesh.vertex_coordinates(key), [crv])[1] attr['x'] = x attr['y'] = y attr['z'] = z conduit.redraw()
def callback(k, args): if k % 10 == 0: rs.Prompt(str(k)) conduit.redraw()
def Area_Brep2D(): points = rs.GetObjects("select points to connect:",rs.filter.point); if points: rs.Prompt("points exist") findClosestPointPairs();
attr['hole_polygons'] = holes #create triangular mesh for each face delaunay_meshes = [] count = 1 for fkey, attr in mesh.faces(True): polygon = attr['polygon'] holes = attr['hole_polygons'] #create flat list of all points points = polygon + [item for hole in holes for item in hole] #compute initial delaunay mesh based on all points for the current face faces = delaunay_from_points(points, boundary=polygon, holes=holes) delaunay = Mesh.from_vertices_and_faces(points, faces) rs.Prompt('Computing triangular mesh for face {} of {}'.format( count, mesh.number_of_faces())) #compute the remeshed delaunay for the current face trimesh_remesh(delaunay, target=trg_length, tol=0.05, kmax=300, allow_boundary_split=False, allow_boundary_swap=True, verbose=False) delaunay_meshes.append(delaunay) count += 1 #join all meshes created per face mesh_diagram = join_meshes(delaunay_meshes,
def callback(k, callback_args=None): if k%5 == 0: rs.Prompt('Iteration: {0} '.format(k))
def MultiNestedBoundaryTrimCurves(): msg="Select closed boundary curves for trimming" TCrvs = rs.GetObjects(msg, 4, preselect=False) if not TCrvs: return cCrvs=[crv for crv in TCrvs if rs.IsCurveClosed(crv)] if len(cCrvs)==0: print "No closed trim curves found" return rs.LockObjects(cCrvs) origCrvs = rs.GetObjects("Select curves to trim", 4) rs.UnlockObjects(cCrvs) if not origCrvs : return #plane which is active when trim curve is chosen refPlane = rs.ViewCPlane() if sc.sticky.has_key("TrimSideChoice"): oldTSChoice = sc.sticky["TrimSideChoice"] else: oldTSChoice=True choice = [["Trim", "Outside", "Inside"]] res = rs.GetBoolean("Side to trim away?", choice, [oldTSChoice]) if not res: return trimIns = res[0] #False=Outside tol=sc.doc.ModelAbsoluteTolerance bb=rs.BoundingBox(origCrvs,refPlane) #CPlane box, world coords if not bb: return zVec=refPlane.ZAxis rs.EnableRedraw(False) botPlane=Rhino.Geometry.Plane(bb[0]-zVec,zVec) #check xform=rs.XformPlanarProjection(botPlane) cutCrvs=rs.TransformObjects(cCrvs,xform,True) ccc=CheckPlanarCurvesForCollision(cutCrvs) if ccc: msg="Boundary curves overlap, results may be unpredictable, continue?" res=rs.MessageBox(msg,1+32) if res!= 1: return bSrfs=rs.AddPlanarSrf(cutCrvs) rs.DeleteObjects(cutCrvs) if bSrfs == None: return line=rs.AddLine(bb[0]-zVec,bb[4]+zVec) vols=[] for srf in bSrfs: ext=rs.ExtrudeSurface(srf,line,True) if ext != None: vols.append(ext) rs.DeleteObjects(bSrfs) rs.DeleteObject(line) if len(vols)==0: return exGroup=rs.AddGroup() rs.AddObjectsToGroup(vols,exGroup) rs.Prompt("Splitting curves...") rs.SelectObjects(origCrvs) rs.Command("_Split _-SelGroup " + exGroup + " _Enter", False) splitRes=rs.LastCreatedObjects() rs.DeleteGroup(exGroup) rs.Prompt("Classifying trims...") noSplit=[] for crv in origCrvs: #add curve to list if it has not been split (still exists in doc) id=sc.doc.Objects.Find(crv) if id != None: noSplit.append(crv) errors=0 if splitRes: if len(noSplit)>0: splitRes.extend(noSplit) for crv in splitRes: inside=MultiTestInOrOut(crv,vols) if inside != None: if (inside and trimIns) or (not inside and not trimIns): rs.DeleteObject(crv) else: errors+=1 rs.DeleteObjects(vols) if errors>0: print "Problems with {} curves".format(errors) sc.sticky["TrimSideChoice"] = trimIns
def lineClosestPoints(): points = rs.GetObjects("select points to connect:", rs.filter.point) if points: rs.Prompt("points exist") findClosestPointPairs()
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)
def massBoolUnion(): objs = rs.GetObjects("select objects to union:", rs.filter.polysurface) if objs: rs.Prompt("got Objects") boolUnionList(objs)
if key in boundary: continue cent = centroid(nodes_dict[key]) if cent: mesh.vertex[key]['x'] = cent[0] mesh.vertex[key]['y'] = cent[1] mesh.vertex[key]['z'] = cent[2] #rs.AddPoints(points) #rhino_mesh = draw_light(mesh,temp = False) mesh_smooth_on_local_plane(mesh, k=1, d=0.01) #mesh_pull_to_surface(mesh,brep,max_srf_dis,tolerance) if k%vis==0: rs.Prompt("Iteration {0} of {1} with a maximum deviation of {2}".format(k,kmax,round(max_dev_step,4))) #draw_light(mesh,temp = True) mesh_faces = color_mesh(mesh,max_dev,0) rs.Redraw() Rhino.RhinoApp.Wait() rs.DeleteObjects(mesh_faces) if max_dev_step < dev_threshold or k == kmax: print"Iteration {0} of {1} with a maximum deviation of {2}".format(k,kmax,round(max_dev_step,4)) break #draw_light(mesh,temp = False) mesh_faces = color_mesh(mesh,max_dev,0) rs.AddObjectsToGroup(mesh_faces,rs.AddGroup())
def CombinedMinBBMulti(): #user input #get prev settings if "MinBBSample" in sc.sticky: u_samp = sc.sticky["MinBBSample"] else: u_samp = False #standard sampling if "MinBBStop" in sc.sticky: u_stop = sc.sticky["MinBBStop"] else: u_stop = True #relative volume stop value if "MinBBReports" in sc.sticky: u_rep = sc.sticky["MinBBReports"] else: u_rep = True #intermediate reports shown prec = sc.doc.ModelDistanceDisplayPrecision us = rs.UnitSystemName(abbreviate=True) prompt = "Select objects for minimum bounding box" gf = OT.Point | OT.PointSet | OT.Curve | OT.Surface | OT.Extrusion | OT.Brep | OT.Mesh bool_prompts = ["Sampling", "StopVal", "ReportIntermedResults"] bool_ini = [[u_samp, "Standard", "Fine"], [u_stop, "Absolute", "Relative"], [u_rep, "No", "Yes"]] result = GetObjectsPlus3Boolean(prompt, bool_prompts, bool_ini, gf) if result is None: return objIDs, fine_sample, rel_stop, im_rep = result #objIDs=rs.GetObjects(preselect=True) #if not objIDs: return #EDIT by willemderks to find bbox for each object individually #EDIT by HarriHumppi to copy object name for each bbox for objID in objIDs: objs = [rs.coercegeometry(objID)] name = rs.ObjectName(objID) # pick name HH print "Checking object planarity/coplanarity..." st = time.time() plane = CheckObjCoPlanarity(objs, tol=sc.doc.ModelAbsoluteTolerance) if plane: if len(objs) == 1: msg = "Selected object is planar - " else: msg = "All selected objects are coplanar - " msg += "launching 2D planar bounding rectangle calculation." print msg #launch planar bounding box routine f_bb, curr_area, passes = MinBoundingRectanglePlane( objs, plane, im_rep) #add polyline, report message bbID = rs.AddPolyline( [f_bb[0], f_bb[1], f_bb[2], f_bb[3], f_bb[0]]) fa = round(curr_area, prec) msg = "{} refinement stages. ".format(passes) msg += "Minimum bounding box area = {} sq. {}".format(fa, us) msg += " Elapsed time: {:.2f} sec.".format(time.time() - st) else: #standard sample count=10 --> 1000 boxes per pass #fine sample count=18 --> 5832 boxes per pass if fine_sample: count = 18 else: count = 10 wxy_plane = Rhino.Geometry.Plane.WorldXY if len(objs) == 1: cp_msg = "Selected object is not planar - " else: cp_msg = "Selected objects are not coplanar - " cp_msg += "launching 3D bounding box calculation." print cp_msg rs.Prompt("Calculating... please wait.") #launch 3D bounding box routine curr_bb, curr_vol, passes = Min3DBoundingBox( objs, wxy_plane, count, rel_stop, im_rep) #add box, report message if Rhino.RhinoApp.ExeVersion < 6: output_bbox = sc.doc.Objects.AddBrep(curr_bb.ToBrep()) #legacy else: output_bbox = sc.doc.Objects.AddBox(curr_bb) print name #print name HH rs.ObjectName(output_bbox, name) #give name HH fv = round(curr_vol, prec) msg = "Final volume after {} passes is {} {}3".format( passes, fv, us) msg += " | Elapsed time: {:.2f} sec.".format(time.time() - st) #final result reporting print msg sc.doc.Views.Redraw() #save user settings sc.sticky["MinBBSample"] = fine_sample sc.sticky["MinBBReports"] = im_rep sc.sticky["MinBBStop"] = rel_stop
def boolUnionList(objs): for obj in objs: rs.Prompt(obj)