def get_two_curves(): # get list of selected objects sel = rs.SelectedObjects() # clear selection rs.UnselectAllObjects() # if there were 2 objects selected... if len(sel) == 2: c1, c2 = sel # ...and they are curves... if rs.IsCurve(c1) and rs.IsCurve(c2): # the closed one is the cross-section, the open one is profile if rs.IsCurveClosed(c2): return c1, c2 elif rs.IsCurveClosed(c1): return c2, c1 # none of the things above worked, ask the user profile = rs.GetObject('Pick the profile curve', rs.filter.curve) # let user cancel if profile is None: return None, None cross = rs.GetObject('Pick the cross-section curve', rs.filter.curve) # return the curves return profile, cross
def divideSrfToPattern(srf, facadeType): top, bot, verts = getSrfTopBotVertCrvs(srf) if bot is None: print('bot is None exit') return None if not rs.IsCurve(bot): print('bot is not Curve exit') return None if len(verts) < 1: print('len(verts)<1') return None if not rs.IsCurve(verts[0]): print('verts[0] is not a curve') return None p0 = rs.CurveStartPoint(verts[0]) p1 = rs.CurveEndPoint(verts[0]) if p1[2] > p0[2]: vect = p1 - p0 else: vect = p0 - p1 print(vect) rs.EnableRedraw(False) m = meshExtrudeCrvToPattern(bot, facadeType, vect) rs.DeleteObjects([top, bot]) rs.DeleteObjects(verts) rs.EnableRedraw(True) return m
def main(): rs.EnableRedraw(enable=False) walls = [] parentFolder = rs.CurrentLayer() if re.search("::", parentFolder): parentFolder = parentFolder.rsplit("::", 1)[0] try: walls = rs.ObjectsByLayer(parentFolder + "::A-WALL") except ValueError: print("No Wall Sublayers in this Layer") try: walls.extend(rs.ObjectsByLayer(parentFolder + "::A-AREA-BOUNDARY")) except ValueError: pass if not walls: print("No walls on this floor.") return None curves = [] for wall in walls: if rs.IsCurve(wall): curves.append(wall) rs.SelectObjects(curves) rs.EnableRedraw(enable=True)
def pre_process(): # delete all previous user text all_objs = rs.AllObjects() for obj in all_objs: rh_obj = rs.coercerhinoobject(obj) rh_obj.Attributes.DeleteAllUserStrings() # remove all blocks for block in rs.BlockNames(): rs.DeleteBlock(block) # set current layer rs.CurrentLayer(relevant_layers_dict["buildings"]) # remove redundant layers for layer_name in rs.LayerNames(): if layer_name not in relevant_layers_dict.values(): rs.PurgeLayer(layer_name) # get all objects in building layer building_objs = rs.ObjectsByLayer(relevant_layers_dict["buildings"]) for building_obj in building_objs: if rs.IsCurve(building_obj) and rs.IsCurveClosed(building_obj): # flatten curve to XY plane matrix = rs.XformPlanarProjection(rg.Plane.WorldXY) rs.TransformObject(building_obj, matrix, copy=False) # delete all object with a surface grater or smaller from MIN_BUILDING_AREA_SQ by TOLERANCE or just smaller than MIN_BUILDING_AREA_SQ TOLERANCE = 2 if rs.CurveArea(building_obj)[0] < MIN_BUILDING_AREA_SQM or abs( rs.CurveArea(building_obj)[0] - MIN_BUILDING_AREA_SQM) < TOLERANCE: rs.DeleteObject(building_obj)
def main(): rs.EnableRedraw(enable=False) walls = [] parentFolder = rs.CurrentLayer() if re.search("::", parentFolder): parentFolder = parentFolder.rsplit("::", 1)[0] walls = [] for wallLayer in wallLayers: try: walls.extend(rs.ObjectsByLayer(parentFolder + "::" + wallLayer)) except ValueError: print("No curves on layer " + parentFolder + "::" + wallLayer) pass if not walls: print("No walls on this floor.") return None curves = [] for wall in walls: if rs.IsCurve(wall): curves.append(wall) rs.SelectObjects(curves) rs.EnableRedraw(enable=True)
def checkCurvePosition(objs): layers = [] for obj in objs: if rs.IsCurve(obj): if not isCurveOnCPlane(obj): # print "Curve {} not on Cplane".format(obj) rs.SelectObject(obj) appendLayer(layers, obj) elif rs.IsPoint(obj): if not isPointOnCplane(obj): # print "Curve {} not on Cplane".format(obj) rs.SelectObject(obj) appendLayer(layers, obj) else: print "object {} is not a curve or point".format(obj) # when an object is found on > 0 layers, prompt for proceed if len(layers) > 0: msg = "there were curves found on layers:\n" for layer in layers: msg = msg + "- " + layer + " \n" if rs.MessageBox(msg, 1) != 1: return False # else return True
def setObjZPair(obj): if rs.IsBlockInstance(obj): # pt = rs.CreatePoint(obj) return [obj, round(objBBPts(obj)[0].Z, 3)] elif rs.IsCurve(obj): return crvPtZpair(obj) elif rs.IsPolysurfaceClosed(obj): return brepPtZPair(obj) elif rs.IsSurface(obj): return srfPtZPair(obj) elif rs.IsPoint(obj): pt = rs.CreatePoint(obj) return [obj, round(pt.Z, 3)] # elif rs.IsBlockInstance(obj): # # pt = rs.CreatePoint(obj) # return [obj, round(objBBPts(obj)[0].Z, 3)] else: pass
def checkCurvePosition(objs): layers = [] selection = [] for obj in objs: if rs.IsCurve(obj): if not isCurveOnCPlane(obj): # print "Curve {} not on Cplane".format(obj) selection.append(obj) appendLayer(layers, obj) elif rs.IsPoint(obj): if not isPointOnCplane(obj): # print "Curve {} not on Cplane".format(obj) rs.SelectObject(obj) appendLayer(layers, obj) else: print "object {} is not a curve or point. {}".format( obj, rs.ObjectType(obj)) if len(selection) > 0: rs.SelectObjects(selection) # when an object is found on > 0 layers, prompt for proceed if len(layers) > 0: msg = "there were non-planar or elevated curves found on layers:\n" for layer in layers: msg = msg + "- " + layer + " \n" msg = msg + '\n Do you want to proceed?' if rs.MessageBox(msg, 1) != 1: return False # else return True
def filterObjects(objs): new_list = [] for obj in objs: if rs.LayerVisible( rs.ObjectLayer(obj) ): # only export visible layers if rs.IsCurve(obj): new_list.append(obj) elif rs.IsPoint(obj): # convert to circle layer = rs.ObjectLayer(obj) point=rs.coerce3dpoint(obj) circle = rs.AddCircle(rs.WorldXYPlane(),3) rs.ObjectLayer(circle, layer) rs.MoveObject(circle, [point.X, point.Y, point.Z]) new_list.append(circle) rs.DeleteObject(obj) # rs.DeleteObject(point) else: # remove from obj list rs.DeleteObject(obj) else: # remove from obj list rs.DeleteObject(obj) return new_list
def sweepMult(): crvProfiles = rs.GetObjects("select Curves to Sweep", 4); #get rail profile crvRail = rs.GetObject("select rail to sweep through",4); #for each curve in crvProfiles, sweep the curve for crv in crvProfiles: if(rs.IsCurve(crv)): rs.AddSweep1(crvRail,crv);
def FindMostDistantPointInCurve(obj, resolution = 20): """ Returns the approximately most distant point within a closed curve inputs: obj (curve): closed planar curves resolution (int)[optional]: numbers of sample points in a resolutionXresolution grid returns: point (point): point furthest from curve """ if rs.IsCurve(obj) == False: print "Curves supported only" return None if rs.IsCurvePlanar(obj) == False: print "Curve not planar" return None if rs.IsCurveClosed(obj) == False: print "Curve not closed" return None rhobj = rs.coercecurve(obj) bbox = rhobj.GetBoundingBox(rs.WorldXYPlane()) minX = bbox.Min[0] minY = bbox.Min[1] minZ = bbox.Min[2] maxX = bbox.Max[0] maxY = bbox.Max[1] maxZ = bbox.Max[2] xVals = [] yVals = [] for i in range(resolution): xVals.append(i) yVals.append(i) newXvals = RemapList(xVals, minX, maxX) newYvals = RemapList(yVals, minY, maxY) furthestPt = None furthestDist = 0 maxDist = 99999 for xVal in newXvals: for yVal in newYvals: newPt = rc.Geometry.Point3d(xVal, yVal, minZ) result = rhobj.Contains(newPt, rs.WorldXYPlane()) if result == rc.Geometry.PointContainment.Inside: param = rhobj.ClosestPoint(newPt, maxDist) crvPt = rhobj.PointAt(param[1]) dist = rs.Distance(crvPt, newPt) if dist > furthestDist: furthestPt = newPt furthestDist = dist if furthestDist == 0: return None return furthestPt
def add_element_set(structure, guids, name): """ Adds element set information from Rhino curve and mesh guids. Parameters ---------- structure : obj Structure object to update. guids : list Rhino curve and Rhino mesh guids. name : str Name of the new element set. Returns ------- None Notes ----- - Meshes representing solids must have 'solid' in their name. """ elements = [] for guid in guids: if rs.IsCurve(guid): sp = structure.check_node_exists(rs.CurveStartPoint(guid)) ep = structure.check_node_exists(rs.CurveEndPoint(guid)) element = structure.check_element_exists([sp, ep]) if element is not None: elements.append(element) if rs.IsMesh(guid): vertices = rs.MeshVertices(guid) faces = rs.MeshFaceVertices(guid) if 'solid' in rs.ObjectName(guid): nodes = [structure.check_node_exists(i) for i in vertices] element = structure.check_element_exists(nodes) if element is not None: elements.append(element) else: for face in faces: nodes = [ structure.check_node_exists(vertices[i]) for i in face ] if nodes[2] == nodes[3]: nodes = nodes[:-1] element = structure.check_element_exists(nodes) if element is not None: elements.append(element) structure.add_set(name=name, type='element', selection=elements)
def del_noattr_plt(): # get all objects in plots layer plot_objs = rs.ObjectsByLayer(relevant_layers_dict["plots"]) for plot_obj in plot_objs: if rs.IsCurve(plot_obj) and rs.IsCurveClosed(plot_obj): some_attrib = rs.GetUserText(plot_obj, plot_attribs_list[0]) if some_attrib == None: rs.DeleteObject(plot_obj)
def ColorBySize(): try: objs = rs.GetObjects("Select objects to color", 1073815613, preselect=True) if objs is None: return print "Select First Color" firstColor = rs.GetColor() if firstColor is None: return print "Select Second Color" secondColor = rs.GetColor(firstColor) if secondColor is None: return rs.EnableRedraw(False) colorLine = rs.AddLine(firstColor, secondColor) areas = [] for obj in objs: if rs.IsCurve(obj): if rs.IsCurveClosed(obj): areas.append(rs.CurveArea(obj)[0]) else: areas.append(rs.CurveLength(obj)) elif rs.IsSurface(obj): areas.append(rs.SurfaceArea(obj)[0]) elif rs.IsPolysurface(obj): if rs.IsPolysurfaceClosed(obj): areas.append(rs.SurfaceVolume(obj)[0]) elif rs.IsHatch(obj): areas.append(rs.Area(obj)) else: print "Only curves, hatches, and surfaces supported" return newAreas = list(areas) objAreas = zip(newAreas, objs) objAreas.sort() objSorted = [objs for newAreas, objs in objAreas] areas.sort() normalParams = utils.RemapList(areas, 0, 1) colors = [] for t in normalParams: param = rs.CurveParameter(colorLine, t) colors.append(rs.EvaluateCurve(colorLine, param)) for i, obj in enumerate(objSorted): rs.ObjectColor(obj, (colors[i].X, colors[i].Y, colors[i].Z)) rs.DeleteObject(colorLine) rs.EnableRedraw(True) return True except: return False
def setObjZPair(obj): if rs.IsCurve(obj): return crvPtZpair(obj) elif rs.IsSurface(obj): return srfPtZPair(obj) elif rs.IsPoint(obj): pt = rs.CreatePoint(obj) return [obj, round(pt.Z, 3)] else: pass
def filterObjects(objs): new_list = [] for obj in objs: if rs.IsCurve(obj) or rs.IsPoint(obj): new_list.append(obj) else: # remove from obj list rs.DeleteObject(obj) return new_list
def revol(r): if rh.IsCurve(r): return native_ref(rh.AddRevSrf(r, axis, start, end)) elif rh.IsSurface(r) or rh.IsPolysurface(r): out_refs = revolve_borders(r, axis, start, end, True) in_refs = revolve_borders(r, axis, start, end, False) return subtract_refs(single_ref_or_union(out_refs), [native_ref(r) for r in in_refs], shape) else: raise RuntimeError("Can't revolve the shape")
def ExportLighthouseSensorsToJSON(filename): print "Writing", filename #objectIds = rs.GetObjects("Select Sensors",rs.filter.curves,True,True) #if( objectIds==None ): return3 # Find all circle and all lines in scene circles = [] lines = [] for obj in rs.AllObjects(): # Skip hidden objects, and invisible layers # TODO: Recuse up layet hierarchy? if rs.IsObjectHidden(obj): continue layer = rs.ObjectLayer(obj) if layer and not rs.IsLayerVisible(layer): continue if rs.IsCurve(obj): if rs.IsCircle(obj): circles.append((obj, rs.CircleCenterPoint(obj))) elif rs.IsLine(obj): verts = rs.PolylineVertices(obj) if len(verts) == 2: lines.append((obj, verts)) print 'found', len(circles), 'sensor candidates (circles) in scene' print 'found', len(lines), 'sensor candidates (normals) in scene' modelJSON = {'modelNormals': [], 'modelPoints': []} # TODO: Better sort order? Perhaps based on winding around origin? for circleObj, circleCenter in reversed(circles): for line, lineVerts in lines: pos, normal = GetSensorPosAndNormal(circleCenter, lineVerts) if pos is None: continue else: modelJSON['modelNormals'].append([float(x) for x in normal]) modelJSON['modelPoints'].append( [float(x) / 1000.0 for x in pos]) break modelJSON['channelMap'] = range(len(modelJSON['modelNormals'])) print "Extracted", len(modelJSON['channelMap']), "sensors" if len(modelJSON['modelNormals']) > 0: outputFile = file(filename, 'w') jsonText = json.dumps(modelJSON, indent=4, sort_keys=True) outputFile.write(jsonText) outputFile.close() print "Wrote", filename else: print "Error: No sensors found in scene"
def _extract_line_guids(self, guids): """Receives: [guid, ...] Returns: [guid, ...] a list of line guids """ line_guids = [] for guid in guids: if rs.IsCurve(guid): line_guids.append(guid) return line_guids
def tangents(self, points): tangents = [] if rs.IsPolyCurve(self.guid): pass elif rs.IsCurve(self.guid): for point in points: param = rs.CurveClosestPoint(self.guid, point) vector = list(rs.CurveTangent(self.guid, param)) tangents.append(vector) else: raise Exception('Object is not a curve.') return tangents
def importComponent(path): imported=rs.Command("-Insert "+path+' Objects Enter 0,0,0 1 0') if imported: components=rs.LastCreatedObjects() polys=[] breps=[] for comp in components: if rs.IsCurve(comp):polys.append(comp) if rs.IsBrep(comp):breps.append(comp) print ('polys \n',polys) print ('breps \n',breps) return [breps,polys]
def tangents(self, points): tangents = [] if rs.IsPolyCurve(self.guid): pass elif rs.IsCurve(self.guid): for point in points: param = rs.CurveClosestPoint(self.guid, point) vector = list(rs.CurveTangent(self.guid, param)) tangents.append((point, vector)) else: raise RhinoCurveError('object is not a curve') return tangents
def joinLayCrvs(): origLayer = rs.CurrentLayer() #shortName = rs.LayerName(origLayer, fullpath = False) fullname = rs.LayerName(origLayer) objs = rs.ObjectsByLayer(fullname) curves = [] for obj in objs: if (rs.IsCurve(obj)): curves.append(obj) if (len(curves) > 1): rs.JoinCurves(curves, True)
def importComponent(path): if path is None: return None imported = rs.Command("-Insert " + path + ' Objects Enter 0,0,0 1 0') outComponent = AttrDict() if imported: components = rs.LastCreatedObjects() outComponent.polys = [] outComponent.breps = [] for comp in components: if rs.IsCurve(comp): outComponent.polys.append(comp) if rs.IsBrep(comp): outComponent.breps.append(comp) return outComponent
def checkCurveIntegrity(objs): layers = [] selection = [] delete_objs = [] for i, obj in enumerate(objs): if rs.IsCurve(obj): layer_name = rs.ObjectLayer(obj) # check for disconnected endpoints if (re.search('contour', layer_name, re.IGNORECASE) or re.search('Pocket', layer_name, re.IGNORECASE)) and not rs.IsCurveClosed(obj): selection.append(obj) appendLayer(layers, obj) delete_objs.append(rs.AddPoint(rs.CurveStartPoint(obj))) delete_objs.append(rs.AddPoint(rs.CurveEndPoint(obj))) rs.Command("'_printDisplay _state _on _Enter") for i in range(0, 3): temp_circle = rs.AddCircle(rs.WorldXYPlane(), 80.0 * i + 1) rs.MoveObject(temp_circle, rs.CurveStartPoint(obj)) rs.ObjectPrintWidth(temp_circle, 2.0) delete_objs.append(temp_circle) if len(selection) > 0: rs.SelectObjects(selection) rs.ZoomSelected() redraw() # when an object is found on > 0 layers, prompt for proceed if len(layers) > 0: msg = "See selection: curves and contours should always be closed:\n" for layer in layers: msg = msg + "- " + layer + " \n" msg = msg + '\n Do you want to proceed?' rs.DeleteObjects(delete_objs) if rs.MessageBox(msg, 1) != 1: # do not proceed with export return False # else return True
def setCurveDir(objs): count = 0 for obj in objs: # if rs.IsCurve(obj) and rs.IsCurvePlanar(obj): if rs.IsCurve(obj): normal = rs.CurveNormal(obj) if normal and normal[2] < 0: count += 1 rs.ReverseCurve(obj) # print "Curve {} flipped {}{}".format(obj, normal, normal2) print "reversed " + str(count) + " curves"
def intersect_surfaces(guids): """Intersects all surfaces in model. Uses python cmd line, not api.""" sc.doc.Views.Redraw() rs.UnselectAllObjects() layer('INTS_BOX') rs.SelectObjects(guids.boxes) rs.Command('_Intersect', echo=False) rs.UnselectAllObjects() layer('INTS') rs.SelectObjects(guids.fractures) rs.Command('_Intersect', echo=False) frac_isect_ids = rs.LastCreatedObjects() rs.UnselectAllObjects() if frac_isect_ids: for intid in frac_isect_ids: if rs.IsCurve(intid): rs.AddPoint(rs.CurveStartPoint(intid)) rs.AddPoint(rs.CurveEndPoint(intid)) if len(frac_isect_ids) > 1: rs.SelectObjects(frac_isect_ids) rs.Command('_Intersect', echo=False) if rs.IsLayer('INTS_BOX_INT'): layer('INTS_BOX_INT') rs.UnselectAllObjects() rs.SelectObjects(guids.boxes_int) rs.SelectObjects(guids.fractures) rs.Command('_Intersect', echo=False) frac_isect_ids = rs.LastCreatedObjects() rs.UnselectAllObjects() if frac_isect_ids: for intid in frac_isect_ids: if rs.IsCurve(intid): rs.AddPoint(rs.CurveStartPoint(intid)) rs.AddPoint(rs.CurveEndPoint(intid)) if len(frac_isect_ids) > 1: rs.SelectObjects(frac_isect_ids) rs.Command('_Intersect', echo=False)
def del_noattr_bld(): # get all objects in plots layer building_objs = rs.ObjectsByLayer(relevant_layers_dict["buildings"]) attribute_labels_list = [] with open(proc_attributes_path, "r") as input_handle: rdr = csv.reader(input_handle) attribute_labels_list = next(rdr) for building_obj in building_objs: if rs.IsCurve(building_obj) and rs.IsCurveClosed(building_obj): some_attrib = rs.GetUserText(building_obj, attribute_labels_list[0]) if some_attrib == None: rs.DeleteObject(building_obj)
def extrude(r): if rh.IsCurve(r): return db.AddSurface( geo.Surface.CreateExtrusion(db.Find(r).Geometry, vec)) else: c = rh.SurfaceAreaCentroid(r)[0] curve = rh.AddLine(c, c + vec) brep = _brep_from_id(r) c = db.Find(curve).Geometry r = single_ref_or_union([ db.AddBrep(face.CreateExtrusion(c, True)) for face in brep.Faces ]) rh.DeleteObject(curve) return r
def extr_bld_flr(): # Extrude all buildings according to NUM_FLOORS attribute multiplied by FLOOR_HEIGHT constant # get all objects in building layer building_objs = rs.ObjectsByLayer(relevant_layers_dict["buildings"]) for building_obj in building_objs: if rs.IsCurve(building_obj) and rs.IsCurveClosed( building_obj ) and rs.CurveArea(building_obj)[0] > MIN_BUILDING_AREA_SQM: crv = rs.coercecurve(building_obj) num_of_floors = rs.GetUserText(building_obj, "NUM_FLOORS") building_height = FLOOR_HEIGHT_M * int(num_of_floors) srf = rs.ExtrudeCurveStraight(crv, (0, 0, 0), (0, 0, building_height)) rs.CapPlanarHoles(srf) rs.ViewDisplayMode(rs.CurrentView(), "Shaded")