def cutInsets(brepId, cutterId): dotCount = rs.GetUserText(brepId, "Dot_Marker_Count") brep = rs.coercebrep(brepId, True) cutter = rs.coercebrep(cutterId, True) tolerance = 0.5 pieces = brep.Split(cutter, tolerance) if not pieces: return brepId newBrep = getLargestPiece(pieces) newBrep = scriptcontext.doc.Objects.AddBrep(newBrep) if str(newBrep).startswith("00000000"): return brepId if dotCount: rs.SetUserText(newBrep, "Dot_Marker_Count", dotCount) for i in range(int(dotCount)): dotText = rs.GetUserText(brepId, "Dot_Marker_" + str(i)) rs.SetUserText(newBrep, "Dot_Marker_" + str(i), str(dotText)) dotCount1 = rs.GetUserText(newBrep, "Dot_Marker_Count") if dotCount1: for i in range(int(dotCount1)): dotText = rs.GetUserText(newBrep, "Dot_Marker_" + str(i)) a=1 rs.DeleteObject(brepId) rs.GetUserText scriptcontext.doc.Views.Redraw() return str(newBrep)
def setPlanarBaseSurface(self): ''' set surface that is planar surface this surface will be made from additiveObj this surface will be used in offsetNonPlanarSurface() ''' explodedSurfaces = rs.ExplodePolysurfaces(self.additiveObj) editPoint = [] if len(explodedSurfaces) is 0: meshed = rhino.Geometry.Mesh.CreateFromBrep( rs.coercebrep(self.additiveObj)) editPoint = rs.MeshVertices(meshed[0]) else: for i in explodedSurfaces: meshed = rhino.Geometry.Mesh.CreateFromBrep(rs.coercebrep(i)) vertices = rs.MeshVertices(meshed[0]) editPoint.extend(vertices) rs.DeleteObjects(explodedSurfaces) xValues = [i[0] for i in editPoint] yValues = [i[1] for i in editPoint] xValues.sort() yValues.sort() xMin = xValues[0] xMax = xValues[-1] yMin = yValues[0] yMax = yValues[-1] lineForSur = [] lineForSur.append(rs.AddLine((xMin, yMin, 0), (xMax, yMin, 0))) lineForSur.append(rs.AddLine((xMax, yMin, 0), (xMax, yMax, 0))) lineForSur.append(rs.AddLine((xMax, yMax, 0), (xMin, yMax, 0))) lineForSur.append(rs.AddLine((xMin, yMax, 0), (xMin, yMin, 0))) joinedCurve = rs.JoinCurves(lineForSur) rs.DeleteObjects(lineForSur) curveForSur = rs.OffsetCurve(joinedCurve, (0, 0, 1), 20) if len(curveForSur) > 1: curveForSur = rs.OffsetCurve(joinedCurve, (0, 0, 1), -20) self.basePlanarSurface = rs.AddPlanarSrf(curveForSur) rs.DeleteObjects(curveForSur) if self.basePlanarSurface is None: return False return True
def process_floor(in_objects, floor_outline, outline_cut_height=None): """function used to process an individual floor. input: in_objects: the internal curves and breps selected for this floor floor_outline: the outline brep for the envelope outline_cut_height: height to cut at. output: (crv,[crv]) crv: the offset boundary curve for the floor [crv]: the internal curves for the floor pt: lower-left reference point bdims = bounding dims of this floor """ #classify the inputs in_crvs, in_breps = brep_or_crv(in_objects) #get list of crvs to project brep_sections = [] for b in in_breps: cut_height = wge.get_brep_height(b) / 2 pcurves = wge.get_brep_plan_cut(rs.coercebrep(b), cut_height, D_TOL) brep_sections.extend(pcurves) b_section_guids = wru.add_curves_to_layer(brep_sections, LCUT_INDICES[0]) in_crvs.extend(b_section_guids) #get the outline brep curve if not outline_cut_height: outline_cut_height = wge.get_brep_height(floor_outline) floor_outline_crvs = wge.get_brep_plan_cut(rs.coercebrep(floor_outline), outline_cut_height, D_TOL) floor_outline_crvs = wru.add_curves_to_layer(floor_outline_crvs, LCUT_INDICES[1]) #get bounding info for the floor outline bb = rs.BoundingBox(floor_outline) corner = bb[0] bdims = wge.get_bounding_dims(floor_outline) proj_srf = rs.AddSrfPt([bb[0], bb[1], bb[2], bb[3]]) internal_crvs = rs.ProjectCurveToSurface(in_crvs, proj_srf, [0, 0, -1]) if in_crvs else [] offset_floor_crv = rs.ProjectCurveToSurface(floor_outline_crvs, proj_srf, [0, 0, -1]) #rs.DeleteObjects(in_crvs) rs.DeleteObjects(floor_outline_crvs) rs.DeleteObject(proj_srf) out_floor_crvs = rs.coercecurve(offset_floor_crv) out_internal_crvs = [rs.coercecurve(x) for x in internal_crvs] rs.DeleteObject(offset_floor_crv) rs.DeleteObjects(internal_crvs) rs.DeleteObjects(b_section_guids) #TODO: make sure objects are being deleted return out_floor_crvs, out_internal_crvs, corner, bdims
def cleanSrfcInput(_srfcsInput): """If Brep or Polysrfc are input, explode them""" outputSrfcs = [] with idf2ph_rhDoc(): for inputObj in _srfcsInput: if isinstance(rs.coercesurface(inputObj), Rhino.Geometry.BrepFace): # Catches Bare surfaces outputSrfcs.append(inputObj) elif isinstance(rs.coercebrep(inputObj), Rhino.Geometry.Brep): # Catches Polysurfaces / Extrusions or other Masses faces = ghc.DeconstructBrep(rs.coercebrep(inputObj)).faces if isinstance(faces, list): for face in faces: outputSrfcs.append(face) elif isinstance(rs.coercegeometry(inputObj), Rhino.Geometry.PolylineCurve): # Catches PolylineCurves if not rs.coercegeometry(inputObj).IsClosed: warn = 'Non-Closed Polyline Curves found. Make sure all curves are closed.' ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Remark, warn) else: faces = ghc.DeconstructBrep( rs.coercegeometry(inputObj)).faces if isinstance(faces, list): for face in faces: outputSrfcs.append(face) else: outputSrfcs.append(faces) return outputSrfcs
def CollectChairs(): # collect chairs + CLs chair0 = rs.coercebrep(rs.ObjectsByLayer("chair0")) chair0_CL = rs.coercecurve(rs.ObjectsByLayer("chair0_CL")) chair1 = rs.coercebrep(rs.ObjectsByLayer("chair1")) chair1_CL = rs.coercecurve(rs.ObjectsByLayer("chair1_CL")) # create chair objects chair0_Obj = Chair(chair0, chair0_CL) chair1_Obj = Chair(chair1, chair1_CL) return([chair0_Obj, chair1_Obj])
def cutInsets(brepId, cutterId): brep = rs.coercebrep(brepId, True) cutter = rs.coercebrep(cutterId, True) tolerance = 0.5 pieces = brep.Split(cutter, tolerance) if not pieces: return brepId newBrep = getLargestPiece(pieces) newBrep = scriptcontext.doc.Objects.AddBrep(newBrep) if str(newBrep).startswith("00000000"): return brepId rs.DeleteObject(brepId) scriptcontext.doc.Views.Redraw() return str(newBrep)
def _build_volume_brep_from_zone(self): # Floor Surface floor_surface = rs.coercebrep(self.tfa_surface.surface) floor_surface = ghc.Move(floor_surface, ghc.UnitZ(self._offset_z) )[0] # 0 is the new translated geometry # Extrusion curve surface_centroid = Rhino.Geometry.AreaMassProperties.Compute(floor_surface).Centroid end_point = ghc.ConstructPoint(surface_centroid.X, surface_centroid.Y, surface_centroid.Z + self._space_height) extrusion_curve = rs.AddLine(surface_centroid, end_point) volume_brep = rs.ExtrudeSurface(surface=floor_surface, curve=extrusion_curve, cap=True) volume_brep = rs.coercebrep(volume_brep) return [volume_brep]
def create_shape(self, index, tangram_type, rotation=None): tangram_shape = None ref_tangram = self.get_growing_tangram(tangram_type) if tangram_type == self.shape_types["s"]: tangram_shape = create_shape(self, ref_tangram, index, 0) else: tangram_shape = create_shape(self, ref_tangram, index, rotation) center = find_center( Brep.Vertices.GetValue(rs.coercebrep(tangram_shape))) valid = check_if_valid(center, rs.coercebrep(tangram_shape), self.key) if valid: self.create_tangram(tangram_type, self.classification, tangram_shape, center, self.create_growing, (self.target_face, self.name), index)
def brep_list_from_guid_list(brep_list): bl = [] for i in xrange(len(brep_list)): bl.append(rs.coercebrep(brep_list[i])) return bl
def slice_plane(self, target, plane): ### Slice p = rs.coerceplane(plane) ### Geomrtry Type if rs.IsMesh(target): # print("Mesh!!") m = rs.coercemesh(target) # print(m) polylines = rg.Intersect.Intersection.MeshPlane(m, p) elif rs.IsBrep(target): # print("Brep!") b = rs.coercebrep(target) mp = rg.MeshingParameters.QualityRenderMesh m = rg.Mesh.CreateFromBrep(b, mp) # print(m[0]) polylines = rg.Intersect.Intersection.MeshPlane(m[0], p) else: # print("N/A") polylines = None return polylines
def __init__(self, name, type, classification, shape, center, can_grow, key, occupied=None, target=None): self.name = name # (str) name of the object self.type = type # (str) type of the object self.classification = classification # (int) 1 or 0 self.shape = rs.coercebrep( rs.CopyObject(shape)) # (brep) shape of the object self.center = center # (list<float>) x,y,z coordinates of the center of the object self.can_grow = can_grow # (bool) true if object can grow self.face_dict = self.set_faces( ) # (dictionary) shows status of the faces of the object self.set_occupied_face(occupied) self.func = None # (string) func of the object in the playground self.target_face = 0 # (int) self.key = key self.selected = False self.create_growing = False
def test_SimpleWithSurfaceAndDefaults(self): id = rs.AddCircle((0,0,0), 20) srf_id = rs.AddPlanarSrf(id) pt_ids = rs.AddPoints([(-20,0,0), (0,20,0), (20,0,0)]) id = rs.AddPatch(pt_ids, srf_id) brep = rs.coercebrep(id, True) self.assertTrue(brep.IsSurface)
def main(north,boundary,timeperiod,monthRange,location): if sc.sticky.has_key('ladybug_release'): try: if not sc.sticky['ladybug_release'].isCompatible(ghenv.Component): return -1 except: warning = "You need a newer version of Ladybug to use this component." + \ "Use updateLadybug component to update userObjects.\n" + \ "If you have already updated userObjects drag Ladybug_Ladybug component " + \ "into canvas and try again." w = gh.GH_RuntimeMessageLevel.Warning ghenv.Component.AddRuntimeMessage(w, warning) return -1 lb_sp = sc.sticky["ladybug_SunPath"]() lb_prep = sc.sticky["ladybug_Preparation"]() # setting solar noon variables latitude,longitude,timeZone,elevation = readLocation(_location) year = datetime.datetime.now().year day = 21 """ MONTH_DICT = {0:range(3,7), 1:range(3,10), 2:range(3,13),\ 3:range(6,10), 4:range(6,13),\ 5:range(9,13)} """ mth_lst = MONTH_DICT[monthRange] t = timeperiod/2.0 centerPt = rs.CurveAreaCentroid(boundary)[0] # do geometry operations boundary = clean_curve(boundary) brep_lst = [] for mth in mth_lst: solar_noon = get_solar_noon(mth,year,timeZone,day,latitude,longitude) hourlst = [solar_noon-t,solar_noon+t] #print mth #print 'month: ',mth,'th;', 'hours: ', hourlst sun_pts = get_sunpt(lb_sp,lb_prep,latitude,centerPt,mth,day,hourlst,north_=north,lon=longitude,tZ=timeZone,scale_=100) brep = rs.coercebrep(make_zone(sun_pts,boundary)) brep_lst.append(brep) SE = None TOL = sc.doc.ModelAbsoluteTolerance for i in range(len(brep_lst)-1): brep = brep_lst[i] brep_ = brep_lst[i+1] if not SE and rs.IsBrep(brep): SE_ = brep else: SE_ = SE if rs.IsBrep(brep_): SE = rc.Brep.CreateBooleanIntersection(SE_,brep_,TOL)[0] else: SE = SE_ return SE else: print "You should first let the Ladybug fly..." ghenv.Component.AddRuntimeMessage(ERROR_W, "You should first let the Ladybug fly...")
def exportData(): # Generating sensor points pts = setSensorLocation() # Make csv file file_object = open("points1.csv", "w") # import sensor value file_data = open("values.csv", "r") data = file_data.readlines() valList = [] for index in range(0, len(data)): valNum = float(data[index]) valList.append(valNum) maxNum = max(valList) minNum = min(valList) # index initialization i = 0 # Writing csv file: iteration for pt in pts: coord = rs.PointCoordinates(pt) dataLine = str(coord) dataLine = dataLine + " ," + data[i] val = float(data[i]) visLine = makeHeight(pt, val) pipe = makePipe(visLine) # Making layers and their colors depending on value color = mapVal2Color(minNum, maxNum, i, val) rs.EnableRedraw(False) # Visualization: assigning layer to point #rs.ObjectLayer(pt, layername) #rs.ObjectLayer(visLine, layername) #rs.ObjectLayer(pipe, layername) # GUID to Brep pipeBrep = rs.coercebrep(pipe) AddMaterial(pipeBrep, i, color) rs.DeleteObject(pt) rs.DeleteObject(visLine) rs.DeleteObject(pipe) i = i + 1 file_object.writelines(dataLine) file_object.close() file_data.close() print("data export done")
def test_SimpleWithSurfaceAndDefaults(self): id = rs.AddCircle((0, 0, 0), 20) srf_id = rs.AddPlanarSrf(id) pt_ids = rs.AddPoints([(-20, 0, 0), (0, 20, 0), (20, 0, 0)]) id = rs.AddPatch(pt_ids, srf_id) brep = rs.coercebrep(id, True) self.assertTrue(brep.IsSurface)
def IntersectBrepPlane(obj, plane): tolerance = rs.UnitAbsoluteTolerance() #BREP brep = rs.coercebrep(obj) intersectionCrvs = [] if brep is None: return None x = rc.Geometry.Intersect.Intersection.BrepPlane(brep, plane, tolerance) if x is None: return xCurves = x[1] if xCurves is None: return None try: newCurves = rc.Geometry.Curve.JoinCurves(xCurves) except: newCurves = xCurves finalCurves = [] for curve in newCurves: finalCurve = sc.doc.Objects.AddCurve(curve) utils.SafeMatchObjectAttributes(finalCurve, obj) finalCurves.append(finalCurve) return finalCurves
def write_strip_data(layer, point_ind): # get all surfaces on layer strips = rs.ObjectsByLayer(layer) strip_ind = 1 strip_dict = {} for strip in strips: # get only surfaces if rs.IsSurface(strip): if rs.IsSurfacePlanar(strip): strip_dict['Strip=' + layer + str(strip_ind)] = [] strip_brep = rs.coercebrep(strip) edges = Rhino.Geometry.Brep.DuplicateEdgeCurves(strip_brep) edge_ids = [] ind = 0 for edge in edges: edge_id = sc.doc.Objects.AddCurve(edge) if edge_id: rs.ObjectName(edge_id, 'active' + str(ind)) edge_ids.append(edge_id) ind += 1 # Get strip geometry # change color to help find strip rs.ObjectColor(strip, color=(255, 0, 255)) start_edge = rs.GetObject('Select start edge.', 4, False, False, active_strip_filter) start_length = rs.CurveLength(start_edge) sp = rs.CurveMidPoint(start_edge) rs.ObjectName(rs.AddPoint(sp), name='SP_' + str(point_ind)) end_edge = rs.GetObject('Select end edge.', 4, False, False, active_strip_filter) end_length = rs.CurveLength(end_edge) ep = rs.CurveMidPoint(end_edge) rs.ObjectName(rs.AddPoint(ep), name='SP_' + str(point_ind)) # Clean up rs.DeleteObjects(edge_ids) rs.ObjectColor(strip, color=(128, 0, 128)) # write to json start = { 'Point': point_ind, 'GlobalX': round(sp.X, 4), 'GlobalY': round(sp.Y, 4), 'WALeft': round(start_length * 0.5, 4), 'WARight': round(start_length * 0.5, 4), 'Autowiden': 'No' } point_ind += 1 end = { 'Point': point_ind, 'GlobalX': round(ep.X, 4), 'GlobalY': round(ep.Y, 4), 'WBLeft': round(end_length * 0.5, 4), 'WBRight': round(end_length * 0.5, 4), } strip_dict['Strip=' + layer + str(strip_ind)].append(start) strip_dict['Strip=' + layer + str(strip_ind)].append(end) point_ind += 1 strip_ind += 1 return strip_dict
def get_connection_angle(self, shape_type, ref_tangram, face_index, vector): if shape_type == "square": return 0 elif math.fabs(vector[2]) > 0: return 0 else: shape1 = create_shape(self, ref_tangram, face_index, 90) center1 = find_center(Brep.Vertices.GetValue( rs.coercebrep(shape1))) distance1 = get_distance(vector, center1) shape2 = create_shape(self, ref_tangram, face_index, 270) center2 = find_center(Brep.Vertices.GetValue( rs.coercebrep(shape2))) distance2 = get_distance(vector, center2) if distance1 <= distance2: return 90 return 270
def check_intersection(self, t): other_keys = [i for i in keys.Keys if i != self.key] intersect = False for key in other_keys: if intersect == True: return intersect intersect = check_intersection(t.get_center(), rs.coercebrep(t.get_shape()), key) return intersect
def MeshBrep(brep_id, params): brep = rs.coercebrep(brep_id) if brep: mesh = Rhino.Geometry.Mesh() mesh_parts = Rhino.Geometry.Mesh.CreateFromBrep(brep, params) for mesh_part in mesh_parts: mesh.Append(mesh_part) mesh.Compact() return mesh
def main(north, _boundary, timeperiod, monthRange, location, height): if sc.sticky.has_key('ladybug_release'): try: if not sc.sticky['ladybug_release'].isCompatible(ghenv.Component): return -1 if sc.sticky['ladybug_release'].isInputMissing(ghenv.Component): return -1 except: warning = "You need a newer version of Ladybug to use this compoent." + \ "Use updateLadybug component to update userObjects.\n" + \ "If you have already updated userObjects drag Ladybug_Ladybug component " + \ "into canvas and try again." w = gh.GH_RuntimeMessageLevel.Warning ghenv.Component.AddRuntimeMessage(w, warning) return -1 latitude, longitude, timeZone, elevation = readLocation(location) year = datetime.datetime.now().year day = 21 s_mth, e_mth = MONTH_DICT[monthRange][0], MONTH_DICT[monthRange][1] s_snoon = get_solarnoon(s_mth, year, timeZone, day, latitude, longitude) e_snoon = get_solarnoon(e_mth, year, timeZone, day, latitude, longitude) """solar variables""" shourlst, ehourlst, day = getSolarData(timeperiod, s_snoon, e_snoon) """work with curves""" curve_ = rs.coercecurve(_boundary, -1, True) boundary_lst = checkConcaveConvex(curve_) chull_lst = [] top_lst = [] # for testing purposes if type(boundary_lst) != type([]): boundary_lst = [_boundary] for boundary_ in boundary_lst: boundary = clean_curve(boundary_) bcurve,tc = getSolarGeom(boundary,height,latitude,\ shourlst,ehourlst,day,north,longitude,timeZone,s_mth,e_mth) chull_lst.append(bcurve) top_lst.extend(tc) b2ch = Curve2ConvexHull3d() breplst, ptlst = b2ch.get_convexhull(chull_lst) L = map(lambda m: rs.coercebrep(m), breplst) CB = CleanBrep(TOL, L) map(lambda id: sc.doc.Objects.Delete(id, True), breplst) #delete breplst return CB.cleanBrep() ##bcurve = boundary_lst ## for testing purposes ##top_curves = top_lst ## for testing purposes else: print "You should first let the Ladybug fly..." ghenv.Component.AddRuntimeMessage( ERROR_W, "You should first let the Ladybug fly...")
def get_reference_shape(self, ref_object, target_srf_num): ref_points = ref_object.get_reference_points(target_srf_num) target_points = self.get_target_points(target_srf_num) new_shape = rs.OrientObject(rs.CopyObject(ref_object.shape), ref_points, target_points) if is_intersect(self.shape, rs.coercebrep(rs.CopyObject(new_shape))): new_shape = rs.OrientObject( rs.CopyObject(ref_object.shape), ref_object.get_target_points(self.target_face), target_points) return new_shape
def get_brep(self,pts): h = Hull(pts) #print i,h F = [] for f in h.faces: ptlst = map(lambda i:rs.AddPoint(i.v.x,i.v.y,i.v.z), f.vertex) F.append(rs.AddPlanarSrf(rs.AddCurve(ptlst+[ptlst[0]],1))) brepfacelst = map(lambda c: rs.coercebrep(c),F) brep = rs.JoinSurfaces(brepfacelst) return brep
def get_brep(self, pts): h = Hull(pts) #print i,h F = [] for f in h.faces: ptlst = map(lambda i: rs.AddPoint(i.v.x, i.v.y, i.v.z), f.vertex) F.append(rs.AddPlanarSrf(rs.AddCurve(ptlst + [ptlst[0]], 1))) brepfacelst = map(lambda c: rs.coercebrep(c), F) brep = rs.JoinSurfaces(brepfacelst) return brep
def set_surface_values(self, _srfc_guids): """Pulls Rhino Scene parameters for a list of Surface Object Guids Takes in a list of surface GUIDs and goes to Rhino. Looks in their UserText to get any user applied parameter data. Will also find the surface area of each surface in the list. Calculates the total surface area of all surfaces in the list, as well as the area-weighted U-Value of the total. Will return tuple(0, 0) on any trouble getting parameter values or any fails Args: self: _flrSrfcs (list): A list of Surface GUIDs to look at in the Rhino Scene Returns: totalFloorArea, floorUValue (tuple): The total floor area (m2) and the area weighted U-Value """ if _srfc_guids == None: return 0, 0 if len(_srfc_guids) > 0: floorAreas = [] weightedUvales = [] for srfcGUID in _srfc_guids: # Get the Surface Area Params srfcGeom = rs.coercebrep(srfcGUID) if srfcGeom: srfcArea = ghc.Area(srfcGeom).area floorAreas.append(srfcArea) # Get the Surface U-Values Params srfcUvalue = self._get_surface_U_value(srfcGUID) weightedUvales.append(srfcUvalue * srfcArea) else: floorAreas.append(1) weightedUvales.append(1) warning = 'Error: Input into _floor_surfaces is not a Surface?\n'\ 'Please ensure inputs are Surface Breps only.' self.ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Warning, warning) totalFloorArea = sum(floorAreas) floorUValue = sum(weightedUvales) / totalFloorArea else: totalFloorArea = 0 floorUValue = 0 self.floor_area = totalFloorArea self.floor_U_value = floorUValue
def create_from_brepid(brepid): brep = rs.coercebrep(brepid) scope = Scope.create_from_brepid(brepid) base = rhgt.get_brep_bottom_boundary(brep) if base: height = scope.size[2] extr = ExtrBlock(base, scope=scope) extr.representations['brep'] = brep extr.source_id = brepid return extr return None
def initialize(type, location): function_map = {0: "platform", 1: "semi_open"} name = "square_1" vector = location starting_shape = move(square, vector) center = find_center(Brep.Vertices.GetValue(rs.coercebrep(starting_shape))) key = len(tangram_dict.Keys) + 1 starting_tangram = T_Square(name, "square", type, starting_shape, center, True, key) starting_tangram.set_func(function_map[type]) return [starting_tangram, starting_shape]
def sharpEdges(brep, fAngleTol_Deg=sc.doc.ModelAngleToleranceDegrees, idxConcavityType=2): """ Parameters: brep: Can be Object document or geometry. fAngleTol_Deg: Used to determine how many iterations to use to refine fAngle. idxConcavityType: 0=Concave only, 1=Convex only , 2=Either concave or convex Returns: List of indices of sharp BrepEdges of desired concavity in brep. """ rgBrep = brep if isinstance(brep, rg.Brep) else rs.coercebrep(brep) idx_rgEdges_Sharp = [] gCrvs1 = [] # Accumulation of duplicated edges (curves) fAngleTol_Rad = Rhino.RhinoMath.ToRadians(fAngleTol_Deg) decimalFractions = 0.5, 0.4, 0.6, 0.3, 0.7, 0.2, 0.8, 0.1, 0.9, 0.0, 1.0 # Accumulate indices of sharp edges. for rgEdge in rgBrep.Edges: if rgEdge.Valence != rg.EdgeAdjacency.Interior: # Skip edge because it doesn't have 2 faces. continue if rgEdge.IsSmoothManifoldEdge(fAngleTol_Rad): continue if idxConcavityType != 2: # Test for concavity vs. convexity against desired state. tMax = rgEdge.Domain.Max tMin = rgEdge.Domain.Min for d in decimalFractions: t = (tMax-tMin) * d + tMin concavity = rgEdge.ConcavityAt( t=t, tolerance=fAngleTol_Rad) if idxConcavityType == 0 and concavity == rg.Concavity.Concave: # Concave found. break elif idxConcavityType == 1 and concavity == rg.Concavity.Convex: # Convex found. break else: # Desired concavity not found, so continue onto next edge. continue idx_rgEdges_Sharp.append(rgEdge.EdgeIndex) return idx_rgEdges_Sharp
def _findWindowPlane(self, _srfcs): """ Takes in a set of surfaces, returns a list of their Centroids in 'order' Assess the surface normal of the group of surfaces and attempts to figuere out the 'order' of the srfcs when viewed from 'outside' (according to the surface normal) and orders the centroids from left--->right """ setXs = [] setYs = [] setZs = [] Centroids = [] for srfc in _srfcs: windowBrep = rs.coercebrep(srfc) surfaceList = windowBrep.Surfaces for eachSurface in surfaceList: srfcCentroid = rs.SurfaceAreaCentroid(eachSurface)[0] b, u, v = eachSurface.ClosestPoint(srfcCentroid) srfcNormal = eachSurface.NormalAt(u, v) setXs.append(srfcNormal.X) setYs.append(srfcNormal.Y) setZs.append(srfcNormal.Z) Centroids.append(srfcCentroid) # Find the average Normal Vector of the set px = sum(setXs) / len(setXs) py = sum(setYs) / len(setYs) pz = sum(setZs) / len(setZs) avgNormalVec = Rhino.Geometry.Point3d(px, py, pz) # Find a line through all the points and its midpoint fitLine = rs.LineFitFromPoints(Centroids) # Find the Midpoint of the Line midX = (fitLine.From.X + fitLine.To.X) / 2 midY = (fitLine.From.Y + fitLine.To.Y) / 2 midZ = (fitLine.From.Z + fitLine.To.Z) / 2 lineMidpoint = Rhino.Geometry.Point3d(midX, midY, midZ) # Rotate new Plane to match the window avg newAvgWindowPlane = rs.CreatePlane(lineMidpoint, avgNormalVec, [0, 0, 1]) finalPlane = rs.RotatePlane(newAvgWindowPlane, 90, [0, 0, 1]) # Plot the window Centroids onto the selection Set Plane centroidsReMaped = [] for eachCent in Centroids: centroidsReMaped.append(finalPlane.RemapToPlaneSpace(eachCent)) # Return a list of the new Centroids remapped onto the Set's Plane return centroidsReMaped
def main(north,_boundary,timeperiod,monthRange,location,height): if sc.sticky.has_key('ladybug_release'): try: if not sc.sticky['ladybug_release'].isCompatible(ghenv.Component): return -1 if sc.sticky['ladybug_release'].isInputMissing(ghenv.Component): return -1 except: warning = "You need a newer version of Ladybug to use this compoent." + \ "Use updateLadybug component to update userObjects.\n" + \ "If you have already updated userObjects drag Ladybug_Ladybug component " + \ "into canvas and try again." w = gh.GH_RuntimeMessageLevel.Warning ghenv.Component.AddRuntimeMessage(w, warning) return -1 latitude,longitude,timeZone,elevation = readLocation(location) year = datetime.datetime.now().year day = 21 s_mth,e_mth = MONTH_DICT[monthRange][0], MONTH_DICT[monthRange][1] s_snoon = get_solarnoon(s_mth,year,timeZone,day,latitude,longitude) e_snoon = get_solarnoon(e_mth,year,timeZone,day,latitude,longitude) """solar variables""" shourlst,ehourlst,day = getSolarData(timeperiod,s_snoon,e_snoon) """work with curves""" curve_ = rs.coercecurve(_boundary, -1, True) boundary_lst = checkConcaveConvex(curve_) chull_lst = [] top_lst = [] # for testing purposes if type(boundary_lst) != type([]): boundary_lst = [_boundary] for boundary_ in boundary_lst: boundary = clean_curve(boundary_) bcurve,tc = getSolarGeom(boundary,height,latitude,\ shourlst,ehourlst,day,north,longitude,timeZone,s_mth,e_mth) chull_lst.append(bcurve) top_lst.extend(tc) b2ch = Curve2ConvexHull3d() breplst,ptlst = b2ch.get_convexhull(chull_lst) L = map(lambda m: rs.coercebrep(m),breplst) CB = CleanBrep(TOL,L) map(lambda id: sc.doc.Objects.Delete(id,True), breplst) #delete breplst return CB.cleanBrep() ##bcurve = boundary_lst ## for testing purposes ##top_curves = top_lst ## for testing purposes else: print "You should first let the Ladybug fly..." ghenv.Component.AddRuntimeMessage(ERROR_W, "You should first let the Ladybug fly...")
def clean_and_coerce_list(brep_list): #""" Ladybug - This definition cleans the list and adds them to RhinoCommon""" outputMesh = [] outputBrep = [] for id in brep_list: if rs.IsMesh(id): geo = rs.coercemesh(id) if geo is not None: outputMesh.append(geo) try: rs.DeleteObject(id) except: pass elif rs.IsBrep(id): geo = rs.coercebrep(id) if geo is not None: outputBrep.append(geo) try: rs.DeleteObject(id) except: pass else: # the idea was to remove the problematice surfaces # not all the geometry which is not possible since # badGeometries won't pass rs.IsBrep() tempBrep = [] surfaces = rs.ExplodePolysurfaces(id) for surface in surfaces: geo = rs.coercesurface(surface) if geo is not None: tempBrep.append(geo) try: rs.DeleteObject(surface) except: pass geo = JoinBreps(tempBrep, 0.01) for Brep in tempBrep: Brep.Dispose() try: rs.DeleteObject(id) except: pass outputBrep.append(geo) return outputMesh, outputBrep
def IntersectGeo(obj, level): tolerance = rs.UnitAbsoluteTolerance() plane = rc.Geometry.Plane(rs.coerce3dpoint((0, 0, level)), rs.coerce3dvector((0, 0, 1))) finalCurves = [] #BLOCKS if rs.IsBlockInstance(obj): matrix = rs.BlockInstanceXform(obj) blockObjs = rs.BlockObjects(rs.BlockInstanceName(obj)) for eachBlockObj in blockObjs: newCopy = rs.CopyObject(eachBlockObj) xformedObj = rs.TransformObject(newCopy, matrix) #EXTRUSIONS if isinstance(xformedObj, rc.Geometry.Extrusion): temp = sc.doc.Objects.AddBrep(xformedObj.ToBrep(False)) xformedObj = rs.coercebrep(temp) rs.DeleteObject(temp) #BREPS IN BLOCK result = IntersectBrepPlane(xformedObj, plane) if result is None: continue for each in result: if each is not None: finalCurves.append(each) rs.DeleteObject(xformedObj) #MESHES IN BLOCK <---This code might not be necessary result = IntersectMeshPlane(xformedObj, plane) if result is None: continue for each in result: if each is not None: finalCurves.append(each) rs.DeleteObject(xformedObj) #BREPS elif rs.IsBrep(obj): result = IntersectBrepPlane(obj, plane) if result is None: return None for each in result: if each is not None: finalCurves.append(each) #MESHES elif rs.IsMesh(obj): result = IntersectMeshPlane(obj, plane) if result is None: return None for each in result: if each is not None: finalCurves.append(each) return finalCurves
def GetTriangulatedMeshes(layers_objects): #list to hold the list of layer object guids layers_objects_brep = [] #for each layers list of lists for layer_objects in layers_objects: #create a new list to hold the layers list of guids represented as objrefs layer_objects_brep = [] for layer_object in layer_objects: #convert the guid to a brep layer_brep = rs.coercebrep(layer_object) #if the obj ref for the object was returned if (layer_brep): #convert the brep into a mesh mesh = Rhino.Geometry.Mesh.CreateFromBrep( layer_brep, smoothAndSlower) #if the mesh is not null if (mesh): #create a new empty mesh objref new_mesh = Rhino.Geometry.Mesh() #for each face in the mesh list [of type array] for m in mesh: #add the mesh face to the new_mesh objref new_mesh.Append(m) #check if the new mesh contains any quad faces #if(new_mesh and new_mesh.Faces.QuadCount > 0): if (new_mesh): #convert the facelist of the new_mesh objref new_mesh_triangulated = new_mesh.Faces.ConvertQuadsToTriangles( ) #if the new_mesh_triangulated was returned if (new_mesh_triangulated): #coerce the guid from the objref of the triangulate mesh [layer_object describes the guid that the objref was generated from] id = rhutil.coerceguid(layer_object, True) #add the guid of the triangulated mesh to the active document added_mesh = scriptcontext.doc.Objects.AddMesh( new_mesh) #move the mesh to the layer of its source guid that generated the objref rs.ObjectLayer(added_mesh, rs.ObjectLayer(layer_object)) #add the guid of the triangulated mesh to the layer_objects list layer_objects_brep.append(added_mesh) #compare the length of the layer_objects_brep and the length of the layer_objects if (len(layer_objects_brep) == len(layer_objects)): #append the layer_objects_brep to the layers_objects_brep layers_objects_brep.append(layer_objects_brep) #if the length of the layers_objects_brep is equal to the length of layers_objects then return the layers_objects_brep list if (len(layers_objects_brep) == len(layers_objects)): return layers_objects_brep else: return False
def SampleBoxSpaceMorph(): obj_id = rs.GetObject("Select surface or polysurface", rs.filter.surface and rs.filter.polysurface) if None == obj_id: return brep = rs.coercebrep(obj_id) if brep is None: return box = rs.BoundingBox(obj_id) corners = box[:] corners[6] = box[6] * 2 morph = BoxMorph(box, corners) if morph.Morph(brep): scriptcontext.doc.Objects.AddBrep(brep) scriptcontext.doc.Views.Redraw()
def RunCommand(): srfid = rs.GetObject("select surface", rs.filter.surface | rs.filter.polysurface) if not srfid: return brep = rs.coercebrep(srfid) if not brep: return pts = Intersect.Intersection.ProjectPointsToBreps( [brep], # brep on which to project [Point3d(0, 0, 0), Point3d(3,0,3), Point3d(-2,0,-2)], # points to project Vector3d(0, 1, 0), # project on Y axis doc.ModelAbsoluteTolerance) if pts != None and pts.Length > 0: for pt in pts: doc.Objects.AddPoint(pt) doc.Views.Redraw()
def points_in_breps(self, breps, points): ### Segment Points with Brep.IsPointInside bool_array = [] for i in xrange(len(breps)): brep = breps[i] brep_geo = rs.coercebrep(brep) bool_array.append(self.points_in_brep(brep_geo, points)) ### Arrays # print(len(bool_array)) bool_inside = ut.bitwise_or_arrays(bool_array) return bool_inside
def extrude_solid(pt,cp,b): # int_solid: (listof pt) pt curve -> (listof solid) lo_solid = [] ptlst = rs.CurvePoints(b) srf = rs.AddPlanarSrf(rs.AddCurve(ptlst,1)) # make curve and extrude line = rs.AddCurve([cp,pt],1) max = get_max_side(b) curve = rs.ExtendCurveLength(line,0,1,max*40) #extrude surface brep = rs.coercebrep(srf, True) curve = rs.coercecurve(curve, -1, True) newbrep = brep.Faces[0].CreateExtrusion(curve, True) if newbrep: rc = sc.doc.Objects.AddBrep(newbrep) sc.doc.Views.Redraw() return rc
def extractPolysrfEdges(_polysurface, _naked_interior, _join): if _polysurface: brep_o = rs.coercebrep(_polysurface) bEdges = brep_o.Edges if bEdges: nakedE = [] interiorE = [] nonManifoldE = [] for bEdge in bEdges: edgAdj = bEdge.Valence if edgAdj == Rhino.Geometry.EdgeAdjacency.Naked: nakedE.append(bEdge.DuplicateCurve()) elif edgAdj == Rhino.Geometry.EdgeAdjacency.Interior: interiorE.append(bEdge.DuplicateCurve()) else: nonManifoldE.append(bEdge.DuplicateCurve()) if _naked_interior == "Naked": naked_or_InteriorCrvs = nakedE elif _naked_interior =="Interior": naked_or_InteriorCrvs = interiorE sel = [] if _join == "Yes" or _join == 1: joinNaked = Rhino.Geometry.Curve.JoinCurves(naked_or_InteriorCrvs) for crv in joinNaked: crv_id = sc.doc.Objects.AddCurve(crv) rs.ObjectColor(crv_id, [255,0,0]) sel.append(crv_id) rs.SelectObjects(sel) elif _join == "No" or _join == 0: for crv in naked_or_InteriorCrvs: crv_id = sc.doc.Objects.AddCurve(crv) rs.ObjectColor(crv_id, [255,0,0]) sel.append(crv_id) rs.SelectObjects(sel) else: print "Something is wrong with you polysurface edges. Function terminated" return else: print "You did not choose the polysurface. Function terminated" return
def RunCommand(): # select a surface srfid = rs.GetObject("select serface", rs.filter.surface | rs.filter.polysurface) if not srfid: return # get the brep brep = rs.coercebrep(srfid) if not brep: return x = rs.GetReal("value of x", 0) y = rs.GetReal("value of y", 0) pts = [(abs(point.Z), point.Z) for point in Intersect.Intersection.ProjectPointsToBreps( [brep], [Point3d(x, y, 0)], Vector3d(0, 0, 1), doc.ModelAbsoluteTolerance)] pts.sort(reverse=True) if pts == []: print "no Z for given X, Y" else: rs.AddPoint(Point3d(x, y, pts[0][1]))
def main(north,_boundary,timeperiod,monthRange,location,height): if sc.sticky.has_key('ladybug_release'): latitude,longitude,timeZone,elevation = readLocation(location) year = datetime.datetime.now().year day = 21 s_mth,e_mth = MONTH_DICT[monthRange][0], MONTH_DICT[monthRange][1] s_snoon = get_solarnoon(s_mth,year,timeZone,day,latitude,longitude) e_snoon = get_solarnoon(e_mth,year,timeZone,day,latitude,longitude) """solar variables""" shourlst,ehourlst,day = getSolarData(timeperiod,s_snoon,e_snoon) """work with curves""" curve_ = rs.coercecurve(_boundary, -1, True) boundary_lst = checkConcaveConvex(curve_) chull_lst = [] top_lst = [] # for testing purposes if type(boundary_lst) != type([]): boundary_lst = [_boundary] for boundary_ in boundary_lst: boundary = clean_curve(boundary_) bcurve,tc = getSolarGeom(boundary,height,latitude,\ shourlst,ehourlst,day,north,longitude,timeZone,s_mth,e_mth) chull_lst.append(bcurve) top_lst.extend(tc) b2ch = Curve2ConvexHull3d() breplst,ptlst = b2ch.get_convexhull(chull_lst) L = map(lambda m: rs.coercebrep(m),breplst) CB = CleanBrep(TOL,L) map(lambda id: sc.doc.Objects.Delete(id,True), breplst) #delete breplst return CB.cleanBrep() ##bcurve = boundary_lst ## for testing purposes ##top_curves = top_lst ## for testing purposes else: print "You should first let the Ladybug fly..." ghenv.Component.AddRuntimeMessage(ERROR_W, "You should first let the Ladybug fly...")
if rc: results[i] = crvs else: results[i] = None except: pass if parallel: tasks.Parallel.ForEach(xrange(slice_count), slice_brep_at_angle) else: for i in xrange(slice_count): slice_brep_at_angle(i) return results if __name__=="__main__": brep = rs.GetObject("Select Brep", rs.filter.polysurface) brep = rs.coercebrep(brep) if brep: # Make sure the Brep is not under the control of the document. This is # just done so we know we have a quick to access local copy of the brep # and nothing else can interfere while performing calculations brep.EnsurePrivateCopy() #run the function on a sinlge thread start = time.time() slices1 = radial_contour(brep, False) end = time.time() print "serial = ", end-start #run the function on mulitple threads start = time.time() slices2 = radial_contour(brep, True) end = time.time()
def processObject(object, parentInstances) : global g_instances global g_instancesByName global g_parts global g_materials name = rs.ObjectName(object) if not name : name = "Unnamed" type = rs.ObjectType(object) layer = rs.ObjectLayer(object) if type == rs.filter.instance : type = rs.BlockInstanceName(object) xform = rs.BlockInstanceXform(object) # Seems like transforms are in global frame already # --> Probably due to exploding the block hierarchies... #for parent in reversed(parentInstances[1:]) : # xform = parent["xform"] * xform subObjects = rs.ExplodeBlockInstance(object) fullName = name if len(parentInstances) > 1 : for parent in parentInstances[1:] : fullName = parent["name"] + "." + fullName originalFullName = fullName appendixCtr = 1 while fullName in g_instancesByName : fullName = format("%s+%d" % (originalFullName, appendixCtr)) appendixCtr += 1 if fullName != originalFullName : print("WARNING: Renamed %s => %s" % (originalFullName, fullName)) instance = \ { "name" : name, "fullName" : fullName, "type" : type, "xform" : xform, "parents" : list(parentInstances), "parts" : [], "touched" : False, } g_instances.append(instance) g_instancesByName[fullName] = instance for subObject in subObjects : processObject(subObject, parentInstances + [instance]) return skipReason = None if rs.LayerLocked(layer) : skipReason = "layer locked" elif not rs.LayerVisible(layer) : skipReason = "layer hidden" elif type != rs.filter.polysurface and type != rs.filter.surface : skipReason = "bad type - " + typeStr[type] if skipReason : # make sure we can delete object by moving to current layer rs.ObjectLayer(object, rs.CurrentLayer()) print("Skipping %s (%s)" % (str(object), skipReason)) else : brep = rs.coercebrep(object) meshes = rc.Geometry.Mesh.CreateFromBrep(brep, g_meshParams) joinedMesh = rc.Geometry.Mesh() for mesh in meshes : joinedMesh.Append(mesh) joinedMesh.Reduce(0, False, 10, False) if not joinedMesh.Faces.ConvertQuadsToTriangles() : print("WARNING: Failed to convert quads to tris for %s" % (str(object))) if not joinedMesh.Compact() : print("WARNING: Failed to compact %s" % (str(object))) materialSrc = rs.ObjectMaterialSource(object) if materialSrc == 0 : materialIdx = rs.LayerMaterialIndex(rs.ObjectLayer(object)) else : materialIdx = rs.ObjectMaterialIndex(object) material = rs.MaterialName(materialIdx) if not material : material = "None" g_materials[material] = materialIdx joinedMeshGuid = sc.doc.Objects.AddMesh(joinedMesh) rs.ObjectName(joinedMeshGuid, name) rs.ObjectMaterialSource(joinedMeshGuid, 1) rs.ObjectMaterialIndex(joinedMeshGuid, materialIdx) part = \ { "name" : name, "mesh" : joinedMesh, "instance" : parentInstances[-1], "material" : material, } parentInstances[-1]["parts"].append(part) if not parentInstances[-1]["touched"] : for parentInstance in parentInstances : parentInstance["touched"] = True g_parts.append(part) rs.DeleteObject(object)
def checkTheInputs(): #Create a dictionary of all of the input temperatures and shades. checkData1 = True allDataDict = {} for i in range(_testRegion.BranchCount): path = [] for index in _testRegion.Path(i): path.append(index) path = str(path) if not allDataDict.has_key(path): allDataDict[path] = {} allDataDict[path]["regionSrf"] = _testRegion.Branch(i) allDataDict[path]["shadeSrfs"] = _testShades.Branch(i) allDataDict[path]["temperatures"] = _temperatures.Branch(i) #Check that both a region brep and test shade brep have only one surface. checkData2 = True if _testShades.BranchCount != 0 and _testRegion.BranchCount != 0: for path in allDataDict: newRegionList = [] for srf in allDataDict[path]["regionSrf"]: if srf.Faces.Count == 1: newRegionList.append(srf) else: for subSrf in srf.Faces: srfBrep = subSrf.ToBrep() newRegionList.append(srfBrep) allDataDict[path]["regionSrf"] = newRegionList newShadesList = [] for srf in allDataDict[path]["shadeSrfs"]: try: newSrf = rs.coercebrep(srf) if newSrf.Faces.Count == 1: newShadesList.append(newSrf) else: for subSrf in newSrf.Faces: srfBrep = subSrf.ToBrep() newShadesList.append(srfBrep) except: newSrf = rs.coercemesh(srf) newShadesList.append(newSrf) allDataDict[path]["shadeSrfs"] = newShadesList else: checkData2 = False print 'Connect a brep for both the _testRegion and the _testShade.' #Check to see if users have connected a grid size. If not, assign a grid size based on a bounding box around the test shade. checkData3 = True if gridSize_: if gridSize_ > 0: gridSize = float(gridSize_) else: warning = 'Values for gridSize_ must be positive.' print warning ghenv.Component.AddRuntimeMessage(w, warning) gridSize = 0 checkData3 = False else: for branch in allDataDict: testKey = branch boundBox = allDataDict[testKey]["shadeSrfs"][0].GetBoundingBox(False) box = rc.Geometry.Box(boundBox) if box.X[1] - box.X[0] < box.Y[1] - box.Y[0]: gridSize = (box.X[1] - box.X[0])/10 else: gridSize = (box.Y[1] - box.Y[0])/10 print "A default coarse grid size was chosen for your shades since you did not input a grid size." #Test to be sure that each window has a respective shade, and set of temperatures. If not, take them out of the dictionary. newAllDataDict = {} for branch in allDataDict: if allDataDict[branch].has_key('regionSrf') and allDataDict[branch].has_key('shadeSrfs') and allDataDict[branch].has_key('temperatures'): if not newAllDataDict.has_key(branch): newAllDataDict[branch] = {} newAllDataDict[branch]["regionSrf"] = allDataDict[branch]["regionSrf"] newAllDataDict[branch]["shadeSrfs"] = allDataDict[branch]["shadeSrfs"] newAllDataDict[branch]["temperatures"] = allDataDict[branch]["temperatures"] else: print "One of the data tree branches of the input data does not have all 3 required inputs of window, shade, and temperatures and has thus been disconted from the shade benefit evaluation." #Test to be sure that the correct headers are on the temperatures and that the correct data type is referenced in these headers. Also check to be sure that the data is hourly. checkData4 = True analysisPeriods = [] locations = [] def checkDataHeaders(dataBranch, dataType, dataType2, dataName, bCount, numKey): if str(dataBranch[0]) == "key:location/dataType/units/frequency/startsAt/endsAt": try: analysisStart = dataBranch[5].split(')')[0].split('(')[-1].split(',') analysisEnd = dataBranch[6].split(')')[0].split('(')[-1].split(',') anaS = [] anaE = [] for item in analysisStart:anaS.append(int(item)) for item in analysisEnd:anaE.append(int(item)) analysisPeriods.append([tuple(anaS), tuple(anaE)]) except: analysisPeriods.append([dataBranch[5], dataBranch[6]]) locations.append(dataBranch[1]) if dataType in dataBranch[2] or dataType2 in dataBranch[2]: if dataBranch[4] == "Hourly": newList = [] for itemCount, item in enumerate(dataBranch): if itemCount > 6: newList.append(item) newAllDataDict[branch][numKey] = newList else: checkData4 = False warning = "Data in the " + dataName + " input is not the right type of data. Data must be of the correct type." print warning ghenv.Component.AddRuntimeMessage(w, warning) else: checkData4 = False warning = "Data in the " + dataName + " input is not hourly. Data must be hourly." print warning ghenv.Component.AddRuntimeMessage(w, warning) else: warning = 'Data in the ' + dataName + ' input does not possess a valid Ladybug header. Data must have a header to use this component.' print warning ghenv.Component.AddRuntimeMessage(w, warning) for branchCount, branch in enumerate(newAllDataDict): checkDataHeaders(newAllDataDict[branch]["temperatures"], "Temperature", "Universal Thermal Climate Index", "_temperatures", branchCount, "temperture") #Make sure that the analysis periods and locations are all the same. checkData5 = True checkData6 = True checkData7 = True analysisPeriod = None location = None if checkData4 == True: if len(analysisPeriods) != 0: analysisPeriod = analysisPeriods[0] for period in analysisPeriods: if period == analysisPeriod: pass else: checkData5 = False if checkData5 == False: warning = 'All of the analysis periods on the connected data are not the same. Data must all be from the same analysis period.' print warning ghenv.Component.AddRuntimeMessage(w, warning) if len(locations) != 0: location = locations[0] for loc in locations: if loc == location: pass else: checkData6 = False if checkData6 == False: warning = 'All of the locations on the connected data are not the same. Data must all be from the same location.' print warning ghenv.Component.AddRuntimeMessage(w, warning) if balanceTemperature_ == None: balanceTemp = 17.5 print "A default balanceTemperature_ of 17.5 C has been set, which defines the range of outdoor comfort temperature (UTCI) of no thermal stress (9 < UTCI <26)." elif balanceTemperature_ >= 9 and balanceTemperature_ <= 26: balanceTemp = balanceTemperature_ else: checkData7 = False balanceTemp = None print 'balanceTemperature_ must be between 9 C and 26 C. Anything else is frankly not human.' ghenv.Component.AddRuntimeMessage(w, "_balanceTemperature must be between 9 C and 26 C. Anything else is frankly not human.") checkData10 = True if temperatureOffest_ == None: temperatureOffest = 8.5 print "A default temperatureOffest_ of 8.5 C has been set, which defines the range of outdoor comfort temperature (UTCI) of no thermal stress (9 < UTCI <26)." elif temperatureOffest_ >= 0: temperatureOffest = temperatureOffest_ else: checkData10 = False temperatureOffest = None print 'temperatureOffest_ must be greater than zero.' ghenv.Component.AddRuntimeMessage(w, "temperatureOffest_ must be greater than zero.") #Check the sky resolution and set a default. checkData8 = True if skyResolution_ == None: skyResolution = 4 print "Sky resolution has been set to 4, which should be a high enough resolution to deal with almost all cases.\n You may want to decrease it for a faster simulation or increase it for a smoother gradient." else: if skyResolution_ >= 0: skyResolution = skyResolution_ print "Sky resolution set to " + str(skyResolution) else: checkData8 = False warning = 'Sky resolution must be greater than 0.' print warning ghenv.Component.AddRuntimeMessage(w, warning) #Check the location, make sure that it matches the location of the inputData, and get the latitude, longitude, and time zone. checkData9 = True latitude = None longitude = None timeZone = None if _location != None: try: locList = _location.split('\n') for line in locList: if "Latitude" in line: latitude = float(line.split(',')[0]) elif "Longitude" in line: longitude = float(line.split(',')[0]) elif "Time Zone" in line: timeZone = float(line.split(',')[0]) except: checkData9 = False warning = 'The connected _location is not a valid location from the "Ladybug_Import EWP" component or the "Ladybug_Construct Location" component.' print warning ghenv.Component.AddRuntimeMessage(w, warning) else: checkData9 = False print 'Connect a _location from the "Ladybug_Import EWP" component or the "Ladybug_Construct Location" component.' #Check the north direction and, if none is given, set a default to the Y-Axis. if north_ == None: north = 0 else: north, northVec = lb_preparation.angle2north(north_) #Check if all of the above Checks are True if checkData1 == True and checkData2 == True and checkData3 == True and checkData4 == True and checkData5 == True and checkData6 == True and checkData7 == True and checkData8 == True and checkData9 == True and checkData10 == True: checkData = True else: checkData = False return checkData, gridSize, newAllDataDict, skyResolution, analysisPeriod, location, latitude, longitude, timeZone, north, balanceTemp, temperatureOffest
def test_SimpleWithUVSpansAndDefaults(self): pt_ids = rs.AddPoints([(-20,0,0), (0,20,0), (20,0,0)]) id = rs.AddPatch(pt_ids, (10,10)) brep = rs.coercebrep(id, True) self.assertTrue(brep.IsSurface)
def checkTheInputs(df_textGen, df_UWGGeo): #Check to be sure that there are not more than 4 building typologies connected. checkData1 = True if len(_buildingTypologies) > 4: checkData1 = False warning = "At present, the Urban Weather Generator can only model up to 4 building typologies. \n This feature will hopefully be enhanced in the future. \n For the time being, please make sure that the number of typologies connected to _buildingTypologies does not exceed 4." print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning) else: try: for typology in _buildingTypologies: if typology.startswith(' <typology'): pass else: checkData1 = False if checkData1 == False: warning = "The input to the _buildingTypologies does not appear to be a valid UWG Building Typology \n generated with either the 'Dragonfly_Building Typology from HBZone' or the 'Dragonfly_Building Typology from Parameters' component." print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning) except: checkData1 = False warning = "Null value connected for _buildingTypologies." print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Error, warning) #Check the typologyRatios_ and be sure that the length of the list matches the length of the _buildingTypologies list. checkData2 = False typologyRatios = [] if len(typologyRatios_) != 0: if len(typologyRatios_) == len(_buildingTypologies): if sum(typologyRatios_) <= 1.01 and sum(typologyRatios_) >= 0.99: for count, ratio in enumerate(typologyRatios_): if count != len(_buildingTypologies)-1: typologyRatios.append(int(round(ratio*100))) else: typologyRatios.append(100-sum(typologyRatios)) checkData2 = True else: warning = "The ratios connected to typologyRatios_ does not sum to 1. \n Make sure that your ratios sum to 1." print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning) else: warning = "The number of ratios connected to typologyRatios_ does not match \n the number of typologies connected to the _buildingTypologies input." print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning) else: if len(_buildingTypologies) == 1: typologyRatios = [100] if len(_buildingTypologies) == 2: typologyRatios = [50, 50] if len(_buildingTypologies) == 3: typologyRatios = [34, 33, 33] if len(_buildingTypologies) == 4: typologyRatios = [25, 25, 25, 25] print "No value has been connected for typologyRatios. \n It will be assumed that each typology occupies an equal part of the urban area." checkData2 = True #Check the roofAngles_ and be sure that the length of the list matches the length of the _buildingTypologies list. checkData3 = True roofAngles = [] if len(roofAngles_) != 0: if len(roofAngles_) == len(_buildingTypologies): for count, val in enumerate(roofAngles_): if val <= 1 and val >= 0: roofAngles.append(val) else: checkData3 = False warning = "One of the values connected to roofAngles_ is not between 1 and 0. \n Roof angles mut be dimensioless values between 0 and 1." print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning) else: checkData3 = False warning = "The number of values connected to roofAngles_ does not match \n the number of typologies connected to the _buildingTypologies input." print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning) else: for val in _buildingTypologies: roofAngles.append(1) print "No value has been connected for roofAngles. \n It will be assumed that each typology has perfectly flat roofs." #Check the wallAngles_ and be sure that the length of the list matches the length of the _buildingTypologies list. checkData4 = True wallAngles = [] if len(wallAngles_) != 0: if len(wallAngles_) == len(_buildingTypologies): for count, val in enumerate(wallAngles_): if val <= 1 and val >= 0: wallAngles.append(val) else: checkData4 = False warning = "One of the values connected to wallAngles_ is not between 1 and 0. \n Roof angles mut be dimensioless values between 0 and 1." print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning) else: checkData4 = False warning = "The number of values connected to wallAngles_ does not match \n the number of typologies connected to the _buildingTypologies input." print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning) else: for val in _buildingTypologies: wallAngles.append(0) print "No value has been connected for wallAngles. \n It will be assumed that each typology has perfectly vertical walls." #Check to be sure that the buildingBreps are closed. checkData5 = True for brep in _buildingBreps: if not brep.IsSolid: checkData5 = False warning = "One of the breps in the connected _buildingBreps is not closed. The input buildings into this component must be closed." print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning) #Set default vegetation parameters if none are connected. if vegetationPar_: vegetationParString = vegetationPar_ else: vegetationParString = df_textGen.defaultVegStr #Set default pavement parameters if none are connected. checkData8 = True if pavementConstr_: try: pavementConstrString = df_textGen.createXMLFromEPConstr(pavementConstr_, 'urbanRoad', 'valToReplace', 'setByEPW') except: checkData8 = False warning = "Converting the conctruction name connected to 'pavementConstr_' failed. Note that the component cannot yet handle full EnergyPlus construction definitions." print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning) else: pavementConstrString = df_textGen.defaultPavementStr #Set default non-Building anthropogenic heat. checkData6 = True if nonBldgLatentFract_: nonBldgLatentFract = nonBldgLatentFract_ if nonBldgLatentFract < 0 or nonBldgLatentFract > 1: checkData6 = False warning = "nonBldgLatentFract_ must be between 0 and 1." print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning) else: nonBldgLatentFract = 0 print "No value is connected for nonBldgLatentFract_ and so it will be assumed that this value is 0 and that all heat within the canyon is sensible." #Check the non-bldg sensible heat. checkData7 = True if nonBldgHeat_: nonBldgSensHeat = nonBldgHeat_*(1-nonBldgLatentFract) nonBldgLatentHeat = nonBldgHeat_*(nonBldgLatentFract) if nonBldgSensHeat < 0: checkData7 = False warning = "nonBldgHeat_ cannot be less than 0." print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning) else: nonBldgSensHeat = 7*(1-nonBldgLatentFract) nonBldgLatentHeat = 7*(nonBldgLatentFract) print "No value is connected for nonBldgHeat_ and so a default of 7 W/m2 will be used, which is characteristic of medium density urban areas." #Check the booleaned buildings. if len(booleanedBldgs_) != 0: booleanedBldgs = booleanedBldgs_ else: booleanedBldgs = _buildingBreps #Do a final check of everything and, if it's good, project any goemtry that needs to be projected in order to extract relevant parameters. checkData = False if checkData1 == True and checkData2 == True and checkData3 == True and checkData4 == True and checkData5 == True and checkData6 == True and checkData7 == True and checkData8 == True: checkData = True #Set Default Parameters. groundProjection = rc.Geometry.Transform.PlanarProjection(rc.Geometry.Plane.WorldXY) maxRoofAngle, maxFloorAngle = 45, 60 #Make empty parameters to be filled. projectedBldgBreps = [] projectedTreeBreps = [] projectedPaveBreps = [] projectedGrassBreps = [] buildingBrepAreas = [] buildingHeights = [] selfIntersectList = [] srfNormalVecs = [] totalBuiltArea = 0 totalPavedArea = 0 totalGrassArea = 0 totalTreeArea = 0 totalTerrainArea = 0 #Define the final variables that we need. averageBuildingHeight = 0 siteCoverageRatio = 0 totalGrassCoverage = 0 totalTreeCoverage = 0 characteristicLength = 500 #Project geometry into the XYPlane to extract the if checkData == True: # Project the building breps into the XYPlane and extract the horizontal area. buildingBreps = [] for bldg in _buildingBreps: buildingBreps.append(bldg.DuplicateBrep()) bldgVertices = [] bldgHeights = [] for brep in buildingBreps: #Pull out info related to bldg heights and neighborhood boundaries. bldgBBox = rc.Geometry.Brep.GetBoundingBox(brep, rc.Geometry.Plane.WorldXY) bldgHeights.append(bldgBBox.Diagonal[2]) bldgVertices.extend(brep.DuplicateVertices()) #Pull out the projected building footprints. #Separate out the surfaces of the Brep footPrintBreps, upSrfs, sideSrfs, sideNormals, roofNormals, topNormVectors, allCentPts, allNormVectors = df_UWGGeo.separateBrepSrfs(brep, maxRoofAngle, maxFloorAngle) #Collect the surface normals. srfNormalVecs.append(allNormVectors) #Check to see if there are any building breps that self-intersect once they are projected into the XYPlane. If so, we have to use an alternative method. meshedBrep = rc.Geometry.Mesh.CreateFromBrep(brep, rc.Geometry.MeshingParameters.Coarse) selfIntersect = False for count, normal in enumerate(topNormVectors): srfRay = rc.Geometry.Ray3d(allCentPts[count], normal) for mesh in meshedBrep: intersectTest = rc.Geometry.Intersect.Intersection.MeshRay(mesh, srfRay) if intersectTest <= sc.doc.ModelAbsoluteTolerance: pass else: selfIntersect = True selfIntersectList.append(selfIntersect) if selfIntersect == True: # Use any downward-facing surfaces that we can identify as part of the building footprint and boolean them together to get the projected area. grounBreps = [] for srf in footPrintBreps: srf.Transform(groundProjection) grounBreps.append(srf) booleanSrf = rc.Geometry.Brep.CreateBooleanUnion(grounBreps, sc.doc.ModelAbsoluteTolerance)[0] buildingBrepAreas.append(rc.Geometry.AreaMassProperties.Compute(booleanSrf).Area) projectedBldgBreps.append(booleanSrf) else: #Project the whole building brep into the X/Y plane and take half its area. brep.Transform(groundProjection) buildingBrepAreas.append(rc.Geometry.AreaMassProperties.Compute(brep).Area/2) projectedBldgBreps.append(brep) totalBuiltArea = sum(buildingBrepAreas) #Use the projected building breps to estimate the neighborhood characteristic length. neighborhoodBB = rc.Geometry.BoundingBox(bldgVertices) neighborhoodDiagonal = neighborhoodBB.Diagonal characteristicLength = neighborhoodDiagonal.Length/2 #Get an area-weighted average building height. multipliedBldgHeights = [a*b for a,b in zip(buildingBrepAreas,bldgHeights)] averageBuildingHeight = sum(multipliedBldgHeights)/totalBuiltArea #Project the pavement breps into the XYPlane and extract their area. groundAreas = [] for srf in _pavementBrep: if not srf.IsSolid: srf.Transform(groundProjection) groundAreas.append(rc.Geometry.AreaMassProperties.Compute(srf).Area) else: srf.Transform(groundProjection) groundAreas.append(rc.Geometry.AreaMassProperties.Compute(srf).Area/2) projectedPaveBreps.append(srf) totalPavedArea = sum(groundAreas) - totalBuiltArea #Project the grass breps into the XYPlane and extract their area. if len(grassOrCoverage_) != 0: try: #The user has connected a single number to represent the fraction of the ground covered in grass totalGrassCoverage = float(grassOrCoverage_[0]) if totalGrassCoverage >= 0 or totalGrassCoverage <=1: pass else: checkData = False warning = "If you are inputting a number for grassOrCoverage_, this number must be between 0 and 1." print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning) except: grassAreas = [] for brep in grassOrCoverage_: srf = rs.coercebrep(brep) if not srf.IsSolid: srf.Transform(groundProjection) grassAreas.append(rc.Geometry.AreaMassProperties.Compute(srf).Area) else: srf.Transform(groundProjection) grassAreas.append(rc.Geometry.AreaMassProperties.Compute(srf).Area/2) projectedGrassBreps.append(srf) totalGrassArea = sum(grassAreas) totalGrassCoverage = totalGrassArea/(totalPavedArea+totalGrassArea) #Replace the vegetation coverage in the ground construction. pavementConstrStringSplit = pavementConstrString.split('valToReplace') pavementConstrString = pavementConstrStringSplit[0] + str(totalGrassCoverage) + pavementConstrStringSplit[-1] #With all of the ground breps accounted for, compute the siteCoverageRatio. totalTerrainArea = totalBuiltArea + totalPavedArea + totalGrassCoverage siteCoverageRatio = totalBuiltArea / totalTerrainArea #Project the tree breps into the XYPlane and extract their area. if len(treesOrCoverage_) != 0: try: #The user has connected a single number to represent the fraction of the ground covered in grass totalTreeCoverage = float(treesOrCoverage_[0]) if totalTreeCoverage >= 0 or totalTreeCoverage <=1: pass else: checkData = False warning = "If you are inputting a number for treesOrCoverage_, this number must be between 0 and 1." print warning ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning) except: treeAreas = [] for brep in treesOrCoverage_: srf = rs.coercebrep(brep) if not srf.IsSolid: srf.Transform(groundProjection) treeAreas.append(rc.Geometry.AreaMassProperties.Compute(srf).Area) else: srf.Transform(groundProjection) treeAreas.append(rc.Geometry.AreaMassProperties.Compute(srf).Area/2) projectedTreeBreps.append(srf) totalTreeArea = sum(treeAreas) totalTreeCoverage = totalTreeArea/(totalPavedArea + totalGrassArea) return checkData, _buildingTypologies, _buildingBreps, buildingBrepAreas, srfNormalVecs, typologyRatios, roofAngles, wallAngles, averageBuildingHeight, siteCoverageRatio, totalGrassCoverage, totalTreeCoverage, vegetationParString, pavementConstrString, nonBldgSensHeat, nonBldgLatentHeat, characteristicLength, totalTerrainArea, projectedBldgBreps, projectedTreeBreps, projectedPaveBreps, projectedGrassBreps, booleanedBldgs